MCP 服务器集成

MCP 协议支持说明

MCP(Model Context Protocol,模型上下文协议)是 Anthropic 推出的开放标准协议,旨在为 AI 模型提供标准化的工具和数据上下文访问接口。与 ACP 侧重于编辑器与代理通信不同,MCP 的焦点在于将外部工具和数据源以统一的方式暴露给 AI 模型。

Hermes Agent 对 MCP 协议提供了原生支持,可以通过 MCP 服务器接入丰富的第三方工具和数据源。这意味着开发者可以像安装 VS Code 插件一样,为 Hermes Agent 安装各种能力扩展——从数据库查询到 API 调用,从文件分析到网络请求,一切皆可通过 MCP 服务器实现。

内置 MCP 客户端功能

Hermes Agent 内置了一个完整的 MCP 客户端,支持以下核心功能:

自动发现与连接

当 Hermes Agent 启动时,它会自动扫描配置目录下的 MCP 服务器配置,并建立连接:

# .hermes/mcp-config.yaml
mcp_servers:
  # 内置服务器
  filesystem:
    command: hermes-mcp-filesystem
    args: ["--allowed-paths", "/workspace"]
    autoStart: true

  database:
    command: hermes-mcp-database
    args: ["--config", "./database-config.json"]
    autoStart: true

  # 外部服务器
  github:
    command: npx
    args: ["-y", "@modelcontextprotocol/server-github"]
    env:
      GITHUB_TOKEN: ${GITHUB_TOKEN}
    autoStart: false

工具注册与调用

MCP 服务器向客户端注册的工具,会被自动整合到 Hermes Agent 的工具链中。Agent 在规划任务时会智能选择和使用这些工具:

// MCP 客户端核心接口
interface MCPClient {
  // 连接管理
  connect(server: MCPServerConfig): Promise<void>;
  disconnect(serverId: string): Promise<void>;
  listTools(): Promise<MCPTool[]>;

  // 工具调用
  callTool(toolName: string, args: Record<string, unknown>): Promise<MCPResult>;

  // 资源访问
  readResource(uri: string): Promise<MCPResource>;
  subscribeResource(uri: string): Promise<void>;

  // 事件监听
  onToolCall: EventEmitter<{ tool: string; args: unknown }>;
  onError: EventEmitter<{ serverId: string; error: Error }>;
}

配置外部 MCP 服务器

除了内置服务器,Hermes Agent 还支持配置社区和第三方开发的 MCP 服务器。目前 MCP 生态已有数百个可用服务器,覆盖数据库、云服务、开发工具等多个领域。

常用 MCP 服务器配置示例

# .hermes/mcp-servers.yaml
servers:
  # PostgreSQL 数据库
  postgres:
    command: npx
    args: ["-y", "@modelcontextprotocol/server-postgres"]
    env:
      POSTGRES_CONNECTION_STRING: "postgresql://user:pass@localhost:5432/mydb"

  # Redis 缓存
  redis:
    command: npx
    args: ["-y", "@modelcontextprotocol/server-redis"]
    env:
      REDIS_URL: "redis://localhost:6379"

  # AWS 云服务
  aws:
    command: npx
    args: ["-y", "@modelcontextprotocol/server-aws"]
    env:
      AWS_ACCESS_KEY_ID: ${AWS_ACCESS_KEY_ID}
      AWS_SECRET_ACCESS_KEY: ${AWS_SECRET_ACCESS_KEY}
      AWS_REGION: us-west-2

  # Jira 项目管理
  jira:
    command: npx
    args: ["-y", "@modelcontextprotocol/server-jira"]
    env:
      JIRA_URL: "https://company.atlassian.net"
      JIRA_EMAIL: ${JIRA_EMAIL}
      JIRA_API_TOKEN: ${JIRA_API_TOKEN}

自定义 MCP 服务器开发

开发者还可以基于 MCP SDK 开发自己的 MCP 服务器,将私有工具和数据源接入 Hermes Agent。

快速开始

使用 MCP SDK 创建一个简单的文件分析服务器:

import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
  CallToolRequestSchema,
  ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";

const server = new Server(
  { name: "custom-analyzer", version: "1.0.0" },
  { capabilities: { tools: {} } }
);

// 注册工具列表
server.setRequestHandler(ListToolsRequestSchema, async () => ({
  tools: [
    {
      name: "analyze_complexity",
      description: "分析代码文件的圈复杂度",
      inputSchema: {
        type: "object",
        properties: {
          filePath: { type: "string", description: "文件路径" }
        },
        required: ["filePath"]
      }
    },
    {
      name: "find_duplicates",
      description: "检测代码重复",
      inputSchema: {
        type: "object",
        properties: {
          directory: { type: "string" },
          minLines: { type: "number", default: 10 }
        },
        required: ["directory"]
      }
    }
  ]
}));

// 实现工具调用
server.setRequestHandler(CallToolRequestSchema, async (request) => {
  const { name, arguments: args } = request.params;

  if (name === "analyze_complexity") {
    const complexity = await analyzeCodeComplexity(args.filePath);
    return { content: [{ type: "text", text: JSON.stringify(complexity) }] };
  }

  throw new Error("Unknown tool");
});

const transport = new StdioServerTransport();
await server.connect(transport);

注册自定义服务器

将开发完成的 MCP 服务器注册到 Hermes Agent 配置中:

# .hermes/mcp-custom.yaml
servers:
  custom-analyzer:
    command: node
    args: ["/path/to/custom-analyzer/dist/index.js"]
    env: {}
    toolFilter: ["analyze_complexity", "find_duplicates"]

对比表:ACP vs MCP 差异

对比维度ACPMCP
全称Agent Communication ProtocolModel Context Protocol
发起方Hermes Agent 团队Anthropic
核心定位代理与编辑器之间的通信模型与外部工具/数据的交互
通信方式WebSocket / stdiostdio / SSE / WebSocket
主要角色编辑器端 ↔ 代理端客户端(模型)↔ 服务器(工具)
核心能力代码编辑、文件操作、任务管理工具调用、资源读取、提示模板
使用场景AI 编程辅助、代码重构数据库查询、API 调用、系统操作
扩展方式扩展 ACP 方法集开发 MCP 服务器
生态规模聚焦编辑器集成广泛的工具和数据源生态
与 Hermes 关系前端通信接口后端能力扩展

实战:集成数据库 MCP 实现自然语言查询

下面演示如何通过 MCP 集成 PostgreSQL 数据库,让 Hermes Agent 支持自然语言查询。

第一步:配置数据库 MCP 服务器

# 安装 PostgreSQL MCP 服务器
npm install -g @modelcontextprotocol/server-postgres

第二步:配置 Hermes Agent 连接

# .hermes/config.yaml
mcp_servers:
  postgres:
    command: npx
    args: ["-y", "@modelcontextprotocol/server-postgres"]
    env:
      PGHOST: localhost
      PGPORT: 5432
      PGDATABASE: ecommerce
      PGUSER: admin
      PGPASSWORD: ${DB_PASSWORD}
    tools:
      - query
      - list_tables
      - describe_table

第三步:使用自然语言查询数据库

向 Hermes Agent 发送自然语言查询指令:

查询本月销售额排名前 10 的商品,
包括商品名称、销量、总金额和环比增长率

Agent 会自动调用 MCP 服务器的工具,分析数据库 schema 并生成 SQL 查询:

SELECT
  p.product_name,
  SUM(oi.quantity) as total_sold,
  SUM(oi.quantity * oi.unit_price) as total_revenue,
  ROUND(
    (SUM(oi.quantity * oi.unit_price) - prev.prev_revenue) /
    NULLIF(prev.prev_revenue, 0) * 100,
    2
  ) as growth_rate
FROM orders o
JOIN order_items oi ON o.order_id = oi.order_id
JOIN products p ON oi.product_id = p.product_id
LEFT JOIN (
  SELECT oi2.product_id, SUM(oi2.quantity * oi2.unit_price) as prev_revenue
  FROM orders o2
  JOIN order_items oi2 ON o2.order_id = oi2.order_id
  WHERE o2.order_date >= date_trunc('month', CURRENT_DATE - INTERVAL '1 month')
    AND o2.order_date < date_trunc('month', CURRENT_DATE)
  GROUP BY oi2.product_id
) prev ON p.product_id = prev.product_id
WHERE o.order_date >= date_trunc('month', CURRENT_DATE)
GROUP BY p.product_name, prev.prev_revenue
ORDER BY total_revenue DESC
LIMIT 10;

Heremes Agent 执行查询后将结果以表格形式呈现,并附带数据分析结论。整个过程无需手动编写任何 SQL,开发者只需用自然语言描述需求即可。

通过 MCP 服务器的集成,Hermes Agent 的能力边界得以极大扩展,从单纯的编程辅助进化为能够与整个开发生态系统深度协作的智能代理平台。