什么是 MCP?
MCP(Model Context Protocol)是 Anthropic 提出的一套开放协议,旨在标准化 AI 模型与外部工具/数据源之间的通信方式。它解决了一个核心痛点:每个 AI 应用都在重复造轮子做工具集成。
在 MCP 出现之前,如果你想让你 AI 编程助手连接一个数据库:
你要在助手的代码里写数据库连接逻辑 你要处理认证、权限、查询构建 每个 AI 工具都要重复这些工作
有了 MCP:
你运行一个 MCP 服务器(比如 @modelcontextprotocol/server-postgres)你的 AI 助手通过标准协议与这个服务器通信 所有 MCP 兼容的 AI 应用都能复用这个服务器
一套工具,到处使用。
Boxagnts 的 MCP 实现架构
Boxagnts 的 MCP 客户端完全独立在 boxagnts-mcp crate 中,这意味着它可以被任何 Rust 项目复用。
boxagnts-mcp/├── lib.rs # 入口:expand_env_vars + 公共导出├── backend.rs # 后端抽象层├── rmcp_backend.rs # 基于 rmcp crate 的后端实现├── connection_manager.rs # 连接管理与自动重连└── oauth.rs # OAuth 认证流程传输层:双模式支持
// 模式一:stdio(子进程通信)// 启动一个 MCP 服务器作为子进程,通过 stdin/stdout JSON-RPC 通信{"command": "npx","args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/dir"]}// 模式二:HTTP + SSE(网络通信)// 连接一个远程 MCP 服务器{"url": "https://mcp.example.com/sse","headers": { "Authorization": "Bearer token" }}stdio 适用于本地工具(文件系统、数据库),HTTP/SSE 适用于远程服务(云端 API、企业服务)。
连接管理器:指数退避重连
MCP 服务器可能因为各种原因断开——网络波动、服务重启、进程崩溃。Boxagnts 的连接管理器实现了指数退避重连策略:
尝试 1:立即重连尝试 2:等待 1 秒尝试 3:等待 2 秒尝试 4:等待 4 秒尝试 5:等待 8 秒...最大退避:60 秒每次成功连接后,退避计数器重置。这种策略既保证了快速恢复,又避免了在服务端持续故障时的无效重试风暴。
MCP 协议交互流程
1. 初始化握手
Client → Server: {"method": "initialize", "params": {"protocolVersion": "2024-11-05","capabilities": { "tools": {} },"clientInfo": { "name": "Boxagnts", "version": "0.1.0" }}}Server → Client: {"result": {"protocolVersion": "2024-11-05","capabilities": { "tools": { "listChanged": true } },"serverInfo": { "name": "Filesystem Server", "version": "1.0.0" }}}Client → Server: {"method": "notifications/initialized"}2. 工具发现
Client → Server: {"method": "tools/list"}Server → Client: {"result": {"tools": [ {"name": "read_file","description": "Read the complete contents of a file","inputSchema": {"type": "object","properties": {"path": {"type": "string"} } } }, {"name": "write_file","description": "Create or overwrite a file","inputSchema": { ... } }]}}3. 工具调用
Client → Server: {"method": "tools/call", "params": {"name": "read_file","arguments": {"path": "/home/user/hello.txt"}}}Server → Client: {"result": {"content": [{"type": "text", "text": "Hello, world!"}]}}与工具的智能汇聚
Boxagnts 的一个巧妙设计是:MCP 工具与内置工具在同一个池子里管理。
// gateway/src/api/tool.rspub async fn build_tools_with_mcp() -> Vec<Box<dyn Tool>> {let mut tools = all_tools(); // 内置工具// 从所有已连接的 MCP 服务器获取工具let mcp_manager = connect_mcp_manager_arc().await;if let Ok(mcp_tools) = mcp_manager.list_all_tools().await { tools.extend(mcp_tools); // 合并 MCP 工具 } tools}对于 AI 模型来说,它不知道也不关心一个工具是内置的还是来自 MCP——所有工具都通过相同的接口呈现。这让工具生态系统可以无限扩展。
环境变量替换:配置即安全
MCP 服务器配置常包含敏感信息(API 密钥、数据库密码)。Boxagnts 支持环境变量替换,避免硬编码:
# MCP 服务器配置[[mcp_servers]]name = "database"command = "npx"args = ["-y", "mcp-server-postgres"]env = { DATABASE_URL = "${DB_URL}", # 必须存在,否则启动失败 TIMEOUT = "${DB_TIMEOUT:-30}", # 可选,默认 30 秒 LOG_LEVEL = "${LOG_LEVEL:-info}" # 可选,默认 info}${VAR} 语法:变量必须存在,不存在则报错。 ${VAR:-default} 语法:变量不存在时使用默认值。
OAuth 集成
企业级 MCP 服务器通常要求认证。Boxagnts 支持 OAuth 2.0 授权码流程:
1. 用户配置 OAuth 凭据(client_id, client_secret)2. Boxagnts 打开浏览器引导用户授权3. 用户授权后,回调获取授权码4. Boxagnts 用授权码换取 access_token5. access_token 自动附加到 MCP 服务器请求中6. token 过期时自动刷新整个过程对用户透明——配置一次,永久使用。
实际场景:用 MCP 扩展 Boxagnts 的能力
假设你有一个内部 API 服务,希望让 Boxagnts 能够调用它:
步骤 1:编写 MCP 服务器
# internal_api_server.pyimport jsonimport sysdef handle_request(request): method = request.get("method")if method == "tools/list":return {"tools": [{"name": "query_internal_api","description": "Query the internal company API","inputSchema": {"type": "object","properties": {"endpoint": {"type": "string"},"params": {"type": "object"} } } }] }elif method == "tools/call": tool_name = request["params"]["name"] args = request["params"]["arguments"]# 调用你的内部 API result = call_your_api(args["endpoint"], args.get("params", {}))return {"content": [{"type": "text", "text": json.dumps(result)}]}# JSON-RPC over stdiofor line in sys.stdin: request = json.loads(line) response = handle_request(request)print(json.dumps(response), flush=True)步骤 2:在 Boxagnts 中配置
[[mcp_servers]]name = "internal-api"command = "python"args = ["internal_api_server.py"]步骤 3:直接使用
配置完成后,Boxagnts 的 AI 模型就会自动发现 query_internal_api 工具,并能在对话中调用它——不需要修改 Boxagnts 的任何代码。
MCP 生态展望
MCP 协议正在快速发展,社区已经贡献了数百个 MCP 服务器,覆盖:
数据库:PostgreSQL、MySQL、SQLite、MongoDB 云服务:AWS、Google Cloud、Azure 开发工具:Git、Docker、Kubernetes SaaS 平台:Slack、Notion、GitHub、Jira
Boxagnts 通过完善的 MCP 支持,让用户可以直接接入这个蓬勃发展的工具生态,将 AI 编程助手的能力边界从"代码编辑"扩展到整个软件开发生命周期。
相关资源
Boxagnts:https://github.com/guyoung/boxagnts
夜雨聆风