AI Agent Tool Design Patterns: Collaboration Tools
The Collaboration Tools pattern implements a Micro-Control-Protocol (MCP) server that transforms utility functions into first-class tools for LLM agents, enabling standardized discovery and invocation through a JSON-RPC-like interface.
The bojieli/ai-agent-book repository demonstrates this architecture in Chapter 4, where a modular MCP server turns isolated capabilities—like browser automation and human oversight—into composable endpoints. This design allows AI agents to orchestrate complex workflows by calling registered functions through a unified protocol.
MCP Server Architecture for Collaboration Tools
Tool Registration with FastMCP
In chapter4/collaboration-tools/src/main.py, the server initializes with FastMCP("collaboration-tools") and registers functions using the @mcp.tool(...) decorator. This decorator exposes Python functions as JSON-RPC endpoints that LLMs can discover and invoke dynamically, abstracting away the underlying async implementation.
The server listens on a Unix socket (or TCP port) and routes incoming requests to the appropriate Python function, handling serialization, error capture, and concurrent execution on a single asynchronous event loop.
Modular Tool Organization
The architecture separates concerns into distinct modules within src/. Each module encapsulates a specific capability domain, allowing developers to maintain and test tools independently while the central server aggregates them into a cohesive interface. This modularity ensures that adding browser automation does not affect notification logic or timer scheduling.
Tool Categories and Implementation
Browser Automation
The browser_tools.py module integrates the browser-use library to provide web navigation capabilities. Functions like browser_navigate accept parameters such as url and new_tab defined via Pydantic fields, enabling agents to perform research, extract content via mcp_browser_get_content, and capture screenshots while maintaining persistent sessions through the BROWSER_USER_DATA_DIR environment variable.
Human-in-the-Loop (HITL)
Implemented in hitl_tools.py, this module provides request_admin_approval and request_admin_input functions. These tools pause agent execution to solicit human judgment on critical decisions or ambiguous inputs, ensuring safety and accuracy during autonomous operations.
Notification Services
The notification_tools.py module supports multi-channel alerts including Email, Telegram, Slack, and Discord. Agents use functions like mcp_send_telegram_message to report status updates or request attention when long-running tasks complete, with chat_id and message parameters strictly validated.
Timer and Scheduling
Found in timer_tools.py, scheduling utilities like set_recurring_timer allow agents to create time-based triggers. These integrate with notification tools to implement reminder systems and periodic health checks, accepting interval_seconds and message payloads as structured arguments.
Sub-Agent Orchestration
The subagent_tools.py module manages the lifecycle of specialized worker agents. The spawn_subagent function delegates complex sub-tasks—such as extensive data scraping—to isolated processes while the parent agent monitors progress via get_subagent_status, retaining overall control without blocking the main reasoning thread.
Intelligence Utilities
Located in intelligence_tools.py, these higher-level functions provide reasoning helpers for code generation and complex problem solving. They extend the agent's cognitive capabilities beyond simple API calls, offering utilities that leverage LLM fallbacks configured in llm_fallback.py.
Configuration and Environment Management
The config.py module uses Pydantic models to load configuration from user-specific directories and environment variables. The system never hard-codes secrets; instead, it reads sensitive values like API keys from .env files when present, following security best practices. Environment variables such as BROWSER_USER_DATA_DIR configure browser persistence paths without code changes.
Practical Code Examples
Browser Navigation
import asyncio
from mcp.client import MCPClient
async def demo_browser():
client = MCPClient("tcp://localhost:5000")
result = await client.call(
"mcp_browser_navigate",
{"url": "https://github.com/bojieli/ai-agent-book", "new_tab": False}
)
print(result) # → {"success": true, "url": "...", "title": "..."}
asyncio.run(demo_browser())
Scheduling and Notifications
import asyncio
from mcp.client import MCPClient
async def demo_timer():
client = MCPClient("tcp://localhost:5000")
await client.call("set_recurring_timer", {"interval_seconds": 3600, "message": "Hourly check‑in"})
await client.call("mcp_send_telegram_message", {"message": "Timer set!", "chat_id": "12345"})
asyncio.run(demo_timer())
Sub-Agent Delegation
import asyncio
from mcp.client import MCPClient
async def demo_subagent():
client = MCPClient("tcp://localhost:5000")
sub_id = await client.call(
"spawn_subagent",
{"name": "scraper", "task": "extract all tables from https://example.com"}
)
status = await client.call("get_subagent_status", {"subagent_id": sub_id})
print(status)
asyncio.run(demo_subagent())
Composable Workflow Patterns
The MCP protocol enables agents to chain tools into complex workflows:
- Navigate → Extract → Summarize: The agent calls
mcp_browser_navigateto open a page, usesmcp_browser_get_contentto extract text, and feeds the result into downstream LLM processing for synthesis. - Schedule → Notify: A
set_timercall creates a future trigger that invokessend_telegram_messageupon completion, implementing automated reminder systems without persistent polling. - Spawn and Monitor: The parent agent delegates long-running tasks via
spawn_subagentwhile periodically checkingget_subagent_statusto maintain oversight, enabling parallel execution without blocking the main reasoning thread.
Extensibility and Testing
The design follows a plug-and-play pattern: developers add new capabilities by creating a module in src/, exposing functions with @mcp.tool, and restarting the server. This separation between tool definition and invocation simplifies unit testing—individual modules test in isolation, while integration tests exercise the full JSON-RPC stack through the MCP client.
All tools share a single asynchronous event loop, allowing concurrent execution while errors return as structured JSON objects that enable the agent to recover or escalate to HITL endpoints.
Summary
- The MCP server architecture in
bojieli/ai-agent-bookstandardizes how LLM agents discover and invoke tools through a JSON-RPC interface defined inmain.py. - Six modular categories—browser automation, HITL, notifications, timers, sub-agents, and intelligence utilities—provide comprehensive agent capabilities through dedicated modules.
- Pydantic-based configuration in
config.pyensures secure, environment-aware settings without hard-coded secrets, respecting variables likeBROWSER_USER_DATA_DIR. - Composable workflows allow agents to chain tools like
browser_navigate,set_recurring_timer, andspawn_subagentinto autonomous task pipelines. - The plug-and-play registration system via
@mcp.tooldecorators enables rapid extension without modifying core server logic, supporting both unit and integration testing strategies.
Frequently Asked Questions
What is the Micro-Control-Protocol (MCP) in AI agent collaboration tools?
MCP is a standardized protocol that exposes Python functions as JSON-RPC endpoints, allowing LLM agents to discover and invoke tools through a consistent interface. In the bojieli/ai-agent-book implementation, the FastMCP server registers decorated functions from main.py and handles serialization, error management, and concurrent execution on a single async event loop, enabling agents to interact with external systems through simple JSON payloads.
How does the browser automation tool handle complex navigation?
The browser_tools.py module leverages the browser-use library to provide functions like browser_navigate and mcp_browser_get_content. These accept structured arguments (e.g., url, new_tab) defined via Pydantic Field definitions, enabling agents to perform multi-step web research while maintaining session state through configurable user data directories specified in environment variables.
Can developers add custom tools to the existing MCP server?
Yes. Developers create a new Python module in chapter4/collaboration-tools/src/, implement an async function with typed parameters using Pydantic Field definitions, and decorate it with @mcp.tool(). The server automatically registers new tools on startup, making them immediately available to any MCP-compliant client without modifying the core registration logic in main.py beyond standard module imports.
How does the human-in-the-loop mechanism function during autonomous execution?
When an agent encounters uncertain situations or requires privileged actions, it calls request_admin_approval or request_admin_input from hitl_tools.py. These functions suspend the async operation and wait for human response through the MCP interface, returning the user's decision or input as structured JSON that the agent incorporates into its next reasoning step, ensuring safety and accountability without breaking the tool contract.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →