MCP Integration
The AG-Kit Python MCP integration provides seamless bidirectional conversion between AG-Kit’s tool system and the Model Context Protocol (MCP). This allows you to:- Connect to standard MCP servers and use their tools as AG-Kit BaseTool instances
- Expose AG-Kit tools as MCP servers for external clients to consume
- Support multiple transport protocols including stdio, HTTP, SSE, in-memory etc.
Overview
The MCP integration consists of several key components:- MCPClientTool: Wraps external MCP tools to work within AG-Kit
- MCPToolkit: High-level toolkit for managing MCP tools
- AGKitMCPServer: Exposes AG-Kit tools as a standard MCP server
- MCPClientManager: Manages connections to multiple MCP servers
Quick Start
Using External MCP Tools in AG-Kit
Exposing AG-Kit Tools as MCP Server
Transport Protocols
Stdio Transport
The most common transport for MCP servers, using standard input/output.Server Configuration
Client Configuration
HTTP Transport (StreamableHTTP)
For web-based MCP servers and clients.Server Configuration
Client Configuration
SSE Transport
Server-Sent Events transport for real-time communication.Server Configuration
Client Configuration
In-Memory Transport
For testing and same-process communication.Server Configuration
Client Configuration
Core Examples
Example 1: Creating and Running an MCP Server
Expose AG-Kit tools as a standard MCP server:Example 2: Connecting to External MCP Servers
Use external MCP servers as AG-Kit tools:Example 3: Using MCPToolkit for Simplified Management
High-level toolkit approach for managing multiple MCP connections:Example 4: Memory Transport for Testing
Use memory transport for testing MCP integrations:Example 5: Advanced Connection Management
Handle connection options and error scenarios:Example 6: Event Handling and Monitoring
Monitor MCP operations with event listeners:Advanced Configuration
Tool Configuration
Customize how AG-Kit tools are exposed via MCP:Client Tool Configuration
Customize MCP client tools:Connection Management
Advanced connection options:Event Handling
Monitor MCP operations:Schema Conversion
AG-Kit automatically converts between Pydantic models and MCP JSON schemas:Pydantic to MCP Schema
MCP to Pydantic Schema
Error Handling
Server Error Handling
Client Error Handling
API Reference
For complete API documentation including all interfaces, types, and detailed method signatures, see the MCP API Reference. AGKitMCPServer - Exposes AG-Kit tools as a standard MCP serverregister_tool(tool: BaseTool, config: dict = None) -> dict- Register a single toolregister_tools(tools: list[BaseTool], config: dict = None) -> list[dict]- Register multiple toolsunregister_tool(name: str) -> bool- Remove a tool from the serverrun(transport_config: dict) -> None- Start the server with specified transportstop() -> None- Stop the server and cleanup resourcescall_tool(name: str, args: dict) -> dict- Execute a tool directlylist_tools() -> list[dict]- Get list of all registered toolsis_server_running() -> bool- Check if server is runningget_stats() -> dict- Get server statistics
add_server(server_id: str, config: dict, options: dict = None) -> None- Connect to an MCP serverdisconnect_server(server_id: str) -> None- Disconnect from a specific serverdisconnect_all() -> None- Disconnect from all serverscreate_client_tools(server_id: str = None) -> list[MCPClientTool]- Create AG-Kit tool wrapperscreate_client_tool(server_id: str, tool_name: str, agkit_tool_name: str = None) -> MCPClientTool- Create specific tool wrappercall_tool(server_id: str, tool_name: str, args: Any) -> Any- Call an MCP tool directlyis_server_connected(server_id: str) -> bool- Check connection statusget_stats() -> dict- Get client manager statistics
invoke(input_data: Any, context: dict = None) -> ToolResult- Execute the MCP toolget_mcp_metadata() -> dict- Get original MCP tool metadatais_connected() -> bool- Check if underlying client is connectedupdate_config(new_config: dict) -> None- Update tool configuration
add_server(server_id: str, config: dict) -> None- Add an MCP serverremove_server(server_id: str) -> None- Remove a serverget_connected_servers() -> list[str]- Get list of connected serversget_server_tools(server_id: str) -> list[MCPClientTool]- Get tools from specific serverrefresh() -> None- Refresh all connectionsdestroy() -> None- Cleanup all resourcesget_client_manager() -> MCPClientManager- Get underlying client manager
Best Practices
- Use appropriate transports: stdio for CLI tools, HTTP for web services, memory for testing
- Handle errors gracefully: Implement proper error handling and retry logic
- Monitor connections: Use event listeners to track connection status
- Clean up resources: Always call cleanup methods when done
- Test thoroughly: Use memory transport for comprehensive testing
- Schema validation: Ensure your schemas are compatible between Pydantic and MCP JSON Schema
- Connection management: Use connection options for reliable production deployments
- Async/await properly: Use
asyncio.create_task()for background server tasks and handleCancelledErrorproperly
Troubleshooting
Common Issues
- Connection timeouts: Increase timeout values in transport configuration
- Schema conversion errors: Ensure Pydantic models use supported types
- Tool not found: Check tool registration and naming
- Transport errors: Verify transport configuration and server availability
- Memory leaks: Always clean up connections and event listeners
- CancelledError: Handle task cancellation properly in async contexts
Debug Mode
Enable logging for debugging:Examples Repository
Find complete working examples at:- mcp_basic.py - Basic MCP integration examples
- mcp_transports.py - Transport protocol examples