跳转到主要内容
AG-Kit 为模型上下文协议 (MCP) 提供全面支持,既能无缝集成外部工具与服务,又能将 AG-Kit 工具暴露给其他兼容 MCP 的应用程序。

AG-Kit MCP 支持

客户端实现

连接现有 MCP 服务器并使用其工具:
from ag_kit_py.tools.mcp import MCPToolkit
from ag_kit_py.agents import LangGraphAgent
from langgraph.graph import StateGraph, MessagesState

# Create MCP toolkit
toolkit = MCPToolkit('mcp-toolkit')
await toolkit.add_server('filesystem', {
    'name': 'filesystem-server',
    'version': '1.0.0',
    'transport': {
        'type': 'stdio',
        'command': 'npx',
        'args': ['@modelcontextprotocol/server-filesystem', './workspace']
    }
})

# Initialize toolkit to load tools
await toolkit.initialize()

# Get available tools
tools = toolkit.get_tools()

# Note: MCP tools integration with LangGraph would be implemented
# in the specific workflow nodes, similar to the examples in:
# python-sdk/examples/langgraph/agents/agentic_chat/agent.py

服务端实现

将 AG-Kit 工具暴露为 MCP 服务器:
from ag_kit_py.tools.mcp import AGKitMCPServer
from ag_kit_py.tools import tool
from pydantic import BaseModel

class WeatherInput(BaseModel):
    city: str

async def weather_func(input_data: WeatherInput, context=None):
    return {
        'city': input_data.city,
        'temperature': 22,
        'condition': 'sunny'
    }

weather_tool = tool(
    func=weather_func,
    name='get_weather',
    description='Get weather information',
    schema=WeatherInput
)

server = AGKitMCPServer({
    'name': 'weather-service',
    'version': '1.0.0'
})

server.register_tool(weather_tool)
await server.run({'type': 'stdio'})

连接类型

  • 标准输入输出: 本地命令行工具
  • HTTP: 远程网络服务
  • 内存通信: 测试与进程内通信

核心特性

  • 工具发现: 自动注册与发现工具
  • 类型安全: 强类型化的工具定义
  • 多传输协议: 支持标准输入输出、HTTP 和内存连接
  • 错误处理: 内置错误处理与恢复机制

后续步骤