跳转到主要内容
模型上下文协议(MCP)是一种连接人工智能应用与外部数据源和工具的开放标准。AG-Kit 提供全面的 MCP 集成支持,使您能够轻松扩展 Agent 的能力。

什么是 MCP?

MCP 采用客户端-服务器架构,允许人工智能应用安全访问外部资源:
  • MCP 服务器:提供工具、数据源和提示模板
  • MCP 客户端:消费这些资源的人工智能应用(如 AG-Kit Agent)

使用场景

1. 连接现有工具生态

许多开发工具和服务已提供可直接在 AG-Kit 中使用的 MCP 服务器:

2. 暴露 AG-Kit 工具

将您的 AG-Kit 工具封装为 MCP 服务器供其他人工智能应用使用:
  • 内部工具共享:跨团队复用工具
  • 跨平台集成:与其他 AI 框架互操作
  • 服务化部署:将工具作为独立服务提供

快速入门

使用外部 MCP 工具

最常见场景是连接现有 MCP 服务器以访问其工具:
import { createMCPToolkit } from '@ag-kit/tools';

// 使用对象映射创建 MCP 工具包(推荐)
const mcpToolkit = await createMCPToolkit({
  playwright: {
    command: 'npx',
    args: ['@playwright/mcp@latest']
  }
});

// 获取工具(addServer 后自动加载)
const tools = mcpToolkit.getTools();

暴露 AG-Kit 工具

将您的 AG-Kit 工具作为 MCP 服务器暴露:
import { AGKitMCPServer } from '@ag-kit/tools/mcp';
import { tool } from '@ag-kit/tools';
import { z } from 'zod';

// 创建 AG-Kit 工具
const weatherTool = tool(
  async ({ city, units = 'celsius' }) => {
    // 模拟天气 API 调用
    const weatherData = {
      city,
      temperature: units === 'celsius' ? 22 : 72,
      condition: 'sunny',
      humidity: 65
    };

    return {
      success: true,
      data: weatherData
    };
  },
  {
    name: 'get_weather',
    description: '获取指定城市的天气信息',
    schema: z.object({
      city: z.string().describe('城市名称'),
      units: z.enum(['celsius', 'fahrenheit']).default('celsius')
    })
  }
);

// 创建 MCP 服务器
const server = new AGKitMCPServer({
  name: 'weather-service',
  version: '1.0.0'
});

// 注册工具
server.registerTool(weatherTool);

// 启动服务器
await server.run({ type: 'stdio' });

连接类型

标准输入/输出(Stdio)

最常见的连接类型,适用于本地工具和命令行程序:
// 使用对象映射格式(推荐)
const toolkit = await createMCPToolkit({
  'python-tools': {
    command: 'python',
    args: ['-m', 'my_mcp_server'],
    timeout: 10000
  },
  'node-tools': {
    command: 'npx',
    args: ['@company/mcp-server']
  }
});

HTTP 连接

适用于远程服务和 Web 应用:

内存连接

用于测试和进程内通信:

实际案例

多服务器集成

实际项目中可能需要连接多个 MCP 服务器以获得不同能力:

错误处理与监控

生产环境需要全面的错误处理和监控:

后续步骤

需要高级功能?本指南涵盖了基本的MCP集成。有关连接池、重试策略、事件监控、模式转换和性能优化等生产功能,请参阅完整的MCP参考