Skip to main content
The Model Context Protocol (MCP) is an open standard for connecting AI applications with external data sources and tools. AG-Kit provides comprehensive MCP integration support, enabling you to easily extend your Agent’s capabilities.

What is MCP?

MCP uses a client-server architecture that allows AI applications to securely access external resources:
  • MCP Servers: Provide tools, data sources, and prompt templates
  • MCP Clients: AI applications that consume these resources (like AG-Kit Agents)

Use Cases

1. Connect to Existing Tool Ecosystems

Many development tools and services already provide MCP servers that you can use directly in AG-Kit:

2. Expose AG-Kit Tools

Wrap your AG-Kit tools as MCP servers for use by other AI applications:
  • Internal Tool Sharing: Reuse tools across teams
  • Cross-Platform Integration: Interoperate with other AI frameworks
  • Service Deployment: Provide tools as standalone services

Quick Start

Using External MCP Tools

The most common scenario is connecting to existing MCP servers to access their tools:
from agkit.tools import create_mcp_toolkit
import os

# Create MCP toolkit using object mapping (recommended)
mcp_toolkit = await create_mcp_toolkit({
    'playwright': {
        'command': 'npx',
        'args': ['@playwright/mcp@latest']
    }
})

# Get tools (automatically loaded after addServer)
tools = mcp_toolkit.get_tools()

Exposing AG-Kit Tools

Expose your AG-Kit tools as an MCP server:
from agkit.tools.mcp import AGKitMCPServer
from agkit.tools import tool
from pydantic import BaseModel, Field
from typing import Literal

class WeatherInput(BaseModel):
    city: str = Field(description="City name")
    units: Literal['celsius', 'fahrenheit'] = Field(default='celsius')

async def weather_func(input_data: WeatherInput):
    # Simulate weather API call
    weather_data = {
        'city': input_data.city,
        'temperature': 22 if input_data.units == 'celsius' else 72,
        'condition': 'sunny',
        'humidity': 65
    }

    return {
        'success': True,
        'data': weather_data
    }

# Create AG-Kit tool
weather_tool = tool(
    func=weather_func,
    name='get_weather',
    description='Get weather information for a specified city',
    schema=WeatherInput
)

# Create MCP server
server = AGKitMCPServer(
    name='weather-service',
    version='1.0.0'
)

# Register tool
server.register_tool(weather_tool)

# Start server
await server.run({'type': 'stdio'})

Connection Types

Standard Input/Output (Stdio)

The most common connection type, suitable for local tools and command-line programs:
# Using object mapping format (recommended)
toolkit = await create_mcp_toolkit({
    'python-tools': {
        'command': 'python',
        'args': ['-m', 'my_mcp_server'],
        'timeout': 10000
    },
    'node-tools': {
        'command': 'npx',
        'args': ['@company/mcp-server']
    }
})

HTTP Connection

Suitable for remote services and web applications:
# Using object mapping format (recommended)
toolkit = await create_mcp_toolkit({
    'remote-api': {
        'url': 'https://api.example.com/mcp',
        'timeout': 15000
    }
})

Memory Connection

Used for testing and in-process communication:
# Server side
await server.run({
    'type': 'memory',
    'memory_id': 'test-server'
})

# Client side
toolkit = await create_mcp_toolkit({
    'test-server': {
        'memory_id': 'test-server'
    }
})

Real-World Examples

Multi-Server Integration

In real projects, you may need to connect multiple MCP servers to gain different capabilities:
import os

# Create comprehensive toolkit using object mapping (recommended)
toolkit = await create_mcp_toolkit({
    'filesystem': {
        'command': 'npx',
        'args': ['@modelcontextprotocol/server-filesystem', './workspace']
    },
    'database': {
        'command': 'python',
        'args': ['-m', 'database_server'],
        'env': {
            'DATABASE_URL': os.getenv('DATABASE_URL')
        }
    },
    'search': {
        'url': 'https://search-api.company.com/mcp'
    }
}, 'enterprise-tools')

# Get tools from specific servers
fs_tools = toolkit.get_server_tools('filesystem')
db_tools = toolkit.get_server_tools('database')
search_tools = toolkit.get_server_tools('search')

# Or get all tools
all_tools = toolkit.get_tools()

Error Handling and Monitoring

Production environments require comprehensive error handling and monitoring:
import asyncio

# Server event monitoring
def server_event_handler(event):
    if event.type == 'connected':
        print(f"Client connected: {event.client_name}")
    elif event.type == 'tool_called':
        print(f"Tool called: {event.tool_name}", event.arguments)
    elif event.type == 'error':
        print(f"Server error: {event.error}")
        # Send to monitoring system
        monitoring.report_error(event.error)

server.add_event_listener(server_event_handler)

# Client connection management
toolkit = MCPToolkit('monitored-toolkit')

def client_event_handler(event):
    if event.type == 'connected':
        print(f"Connected to server: {event.client_name}")
    elif event.type == 'disconnected':
        print(f"Disconnected from server: {event.client_name}")
        # Attempt reconnection
        asyncio.create_task(asyncio.sleep(5)).add_done_callback(
            lambda _: asyncio.create_task(toolkit.refresh())
        )
    elif event.type == 'error':
        print(f"Client error: {event.error}")

toolkit.add_event_listener(client_event_handler)

Next Steps

Need Advanced Features?This guide covers basic MCP integration. For production features like connection pooling, retry policies, event monitoring, schema transformation, and performance optimization, see the complete MCP reference.