第9章 MCP协议集成

第9章 MCP协议集成

本章目标:理解 MCP 协议,掌握连接和使用外部 MCP 工具服务器


9.1 MCP 协议简介

9.1.1 什么是 MCP

MCP(Model Context Protocol)是由 Anthropic 提出的开放协议,用于连接 AI 应用与外部工具服务:

┌─────────────────────────────────────────────────────────────┐
│                      MCP 生态系统                            │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│   ┌─────────────┐                                           │
│   │ AgentScope  │                                           │
│   │   应用      │                                           │
│   └──────┬──────┘                                           │
│          │ MCP 协议                                         │
│          │                                                  │
│   ┌──────┴────────────────────────────────────────────┐    │
│   │                  MCP 服务器                         │    │
│   │                                                    │    │
│   │  ┌──────────┐  ┌──────────┐  ┌──────────┐        │    │
│   │  │ 文件系统  │  │   Git    │  │  数据库  │ ...    │    │
│   │  └──────────┘  └──────────┘  └──────────┘        │    │
│   │                                                    │    │
│   └────────────────────────────────────────────────────┘    │
│                                                             │
│   社区提供了大量现成的 MCP 服务器:                          │
│   - @modelcontextprotocol/server-filesystem                │
│   - @modelcontextprotocol/server-git                       │
│   - @modelcontextprotocol/server-postgres                  │
│   - ...更多见 https://github.com/modelcontextprotocol       │
│                                                             │
└─────────────────────────────────────────────────────────────┘

9.1.2 MCP 的优势

优势说明
标准化统一的工具接口协议
生态丰富社区提供大量现成服务器
语言无关服务器可以用任何语言实现
灵活部署支持本地进程、远程服务

9.2 传输类型

MCP 支持三种传输方式:

9.2.1 StdIO 传输

通过标准输入输出与本地进程通信:

import io.agentscope.core.mcp.McpClientBuilder;
import io.agentscope.core.mcp.McpClientWrapper;

// ========================================
// 【StdIO 传输】
// 启动本地进程,通过 stdin/stdout 通信
// ========================================

McpClientWrapper mcpClient = McpClientBuilder.create("filesystem")
        .stdioTransport(
                "npx",                                    // 命令
                "-y",                                     // 参数
                "@modelcontextprotocol/server-filesystem",
                "/workspace"                              // 允许访问的目录
        )
        .buildAsync()
        .block();

// 注意:需要先安装 Node.js 和对应的 MCP 服务器包

9.2.2 SSE 传输

通过 HTTP Server-Sent Events 与远程服务通信:

// ========================================
// 【SSE 传输】
// 连接到远程 MCP 服务器
// ========================================

McpClientWrapper sseClient = McpClientBuilder.create("remote-tools")
        .sseTransport("https://mcp.example.com/sse")
        .header("Authorization", "Bearer " + token)
        .timeout(Duration.ofSeconds(30))
        .buildAsync()
        .block();

9.2.3 HTTP 传输

标准 HTTP 请求响应模式:

// ========================================
// 【HTTP 传输】
// ========================================

McpClientWrapper httpClient = McpClientBuilder.create("http-tools")
        .httpTransport("https://mcp.example.com/api")
        .header("X-API-Key", apiKey)
        .buildAsync()
        .block();

9.3 连接 MCP 服务器

9.3.1 完整连接示例

import io.agentscope.core.ReActAgent;
import io.agentscope.core.mcp.McpClientBuilder;
import io.agentscope.core.mcp.McpClientWrapper;
import io.agentscope.core.tool.Toolkit;

public class McpExample {
    public static void main(String[] args) {
        // ========================================
        // 【步骤 1】连接 MCP 服务器
        // ========================================
        
        McpClientWrapper filesystemMcp = McpClientBuilder
                .create("filesystem")
                .stdioTransport(
                        "npx", "-y",
                        "@modelcontextprotocol/server-filesystem",
                        "/tmp"
                )
                .buildAsync()
                .block();
        
        System.out.println("已连接到 MCP 服务器");
        
        // 查看可用工具
        filesystemMcp.listTools().block().forEach(tool -> {
            System.out.println("工具: " + tool.getName());
            System.out.println("描述: " + tool.getDescription());
        });
        
        // ========================================
        // 【步骤 2】注册到 Toolkit
        // ========================================
        
        Toolkit toolkit = new Toolkit();
        toolkit.registerMcpClient(filesystemMcp).block();
        
        // ========================================
        // 【步骤 3】创建智能体
        // ========================================
        
        ReActAgent agent = ReActAgent.builder()
                .name("FileAssistant")
                .sysPrompt("你是一个文件助手,可以读写 /tmp 目录下的文件。")
                .model(model)
                .toolkit(toolkit)
                .build();
        
        // ========================================
        // 【步骤 4】使用
        // ========================================
        
        Msg response = agent.call(
                Msg.builder().textContent("列出 /tmp 目录下的文件").build()
        ).block();
        
        System.out.println(response.getTextContent());
        
        // ========================================
        // 【步骤 5】清理
        // ========================================
        
        filesystemMcp.close();
    }
}

9.3.2 常用 MCP 服务器

# 文件系统
npm install -g @modelcontextprotocol/server-filesystem

# Git
npm install -g @modelcontextprotocol/server-git

# PostgreSQL
npm install -g @modelcontextprotocol/server-postgres

# Brave 搜索
npm install -g @anthropic/mcp-server-brave-search

# Slack
npm install -g @anthropic/mcp-server-slack

9.4 工具过滤与工具组

9.4.1 过滤工具

// ========================================
// 【仅启用特定工具】
// ========================================

toolkit.registration()
        .mcpClient(filesystemMcp)
        .enableTools(List.of("read_file", "list_directory"))
        // 只注册这两个工具,其他忽略
        .apply();

// ========================================
// 【禁用特定工具】
// ========================================

toolkit.registration()
        .mcpClient(filesystemMcp)
        .disableTools(List.of("delete_file", "write_file"))
        // 禁用危险操作
        .apply();

9.4.2 分配到工具组

// 创建工具组
toolkit.createToolGroup("file_tools", "文件操作工具", false);

// MCP 工具分配到工具组
toolkit.registration()
        .mcpClient(filesystemMcp)
        .group("file_tools")
        .apply();

// 需要时激活
toolkit.updateToolGroups(List.of("file_tools"), true);

9.5 Higress AI Gateway 集成

通过 Higress 网关管理 MCP 服务:

// ========================================
// 【Higress MCP 集成】
// ========================================

McpClientWrapper higressMcp = McpClientBuilder
        .create("higress-mcp")
        .sseTransport("https://higress.example.com/mcp/sse")
        .header("Authorization", "Bearer " + higressToken)
        .buildAsync()
        .block();

toolkit.registerMcpClient(higressMcp).block();

9.6 本章小结

本章我们学习了:

  1. MCP 协议

- 标准化的工具接口协议 - 丰富的社区生态

  1. 传输类型

- StdIO:本地进程 - SSE:远程流式 - HTTP:标准请求

  1. 连接和使用

- McpClientBuilder 创建客户端 - 注册到 Toolkit

  1. 工具管理

- 过滤启用/禁用工具 - 分配到工具组


下一章 → 第10章 RAG知识检索

← 返回目录