关于 🔍 Rust MCP Server + Inspector Example: SSE Transport with an Add Tool
这个 Rust 示例展示通过 SSE 通信的 MCP 服务端和客户端,并提供两数相加工具。它还演示 RIG Agent 如何调用该工具,以及如何使用 MCP Inspector 进行测试。
主要功能
- 01通过 SSE 配置 MCP 服务
- 02注册两数相加工具
- 03连接 MCP 客户端并列出工具
- 04通过 RIG Agent 使用工具
- 05用 MCP Inspector 检查服务
适用场景
- 01学习基于 SSE 的 MCP 服务配置
- 02用 Agent 测试自定义加法工具
- 03通过 Inspector 探索 MCP 连接
MCP 相关
示例创建通过 SSE 暴露加法工具的 MCP 服务,并连接可列出和调用该工具的 MCP 客户端。可使用 MCP Inspector 连接服务进行测试。
配置
本地服务的配置在各客户端中通用,复制后粘贴到客户端的 MCP 配置文件即可。
工具
本地服务需要在你的电脑上运行后才能读取工具,维护者暂未提供工具列表。
详细介绍
🔍 Rust MCP 服务 + Inspector 示例:使用 SSE 传输的加法工具
致谢:https://dev.to/joshmo_dev/using-model-context-protocol-with-rig-m7o
本项目演示如何使用服务器发送事件(SSE)进行通信,搭建 MCP(Model Context Protocol)服务和客户端。项目包含一个用于将两个数字相加的简单工具,并与 RIG Agent 集成,以进行大模型提示。
🚀 快速开始
克隆此仓库并运行:
cargo run
在另一个终端中启动 MCP Inspector:
npx @modelcontextprotocol/inspector sse http://127.0.0.1:3001/sse
你将看到类似以下输出:
Starting MCP inspector...
Proxy server listening on port 3000
New SSE connection
Query parameters: { transportType: 'sse', url: 'http://localhost:3001/sse' }
SSE transport: url=http://localhost:3001/sse, headers=
Connected to SSE transport
Connected MCP client to backing server transport
Created web app transport
Set up MCP proxy
🔍 MCP Inspector is up and running at http://localhost:5173 🚀
现在可以在 http://localhost:5173 查看 Web 界面。
🛠️ 功能
- ✅ 使用
ServerSseTransport搭建自定义 MCP 服务 - ✅ 将 MCP 客户端连接到服务
- ✅ 注册自定义工具:
AddTool,用于将两个数字相加 - ✅ 通过 MCP 列出已注册的工具
- ✅ 与 RIG 集成,并使用该工具向大模型 Agent 发送提示词
🧠 代码概览
#[tool(
name = "Add",
description = "Adds two numbers together.",
params(a = "The first number to add", b = "The second number to add")
)]
async fn add_tool(a: f64, b: f64) -> Result<ToolResponseContent> {
Ok(tool_text_content!((a + b).to_string()))
}
这定义了在 MCP 服务中注册的 Add 工具。
主函数会设置:
- 跟踪
- MCP 服务和传输方式(SSE)
- 初始化并列出可用工具的 MCP 客户端
- 使用 OpenAI 后端、可调用 MCP 工具的 RIG Agent
随后,Agent 会运行提示词:
let response = agent.prompt("Add 10 + 10").await;
🧪 示例输出
成功运行后,你将看到类似以下日志:
Initialized: Ok(...)
Tools: Ok([...])
Building RIG agent
Prompting RIG agent
Agent response: Some("20")
🧰 技术栈
- 🦀 Rust 和 tokio
- 📡 来自
mcp_core的 SSE 传输 - 🔧 MCP 服务端/客户端架构
- 🤖 使用 OpenAI 模型的 RIG Agent
- 🌐 MCP Inspector Web 界面
📦 依赖项
确保 Cargo.toml 中包含以下依赖:
[dependencies]
tokio = { version = "1", features = ["full"] }
anyhow = "1"
serde_json = "1"
mcp_core = "..."
mcp_core_macros = "..."
rig = "..."
请根据你的环境,将
...替换为适当的版本。
📍 Inspector 图形界面
访问 http://localhost:5173 查看 MCP Inspector 界面并与之交互。
✅ 测试日志示例
Query parameters: { transportType: 'sse', url: 'http://localhost:3001/sse' }
Connected to SSE transport
Connected MCP client to backing server transport
Set up MCP proxy
Received message for sessionId cdd4a8be-57e2-44e3-9b81-3df300e86f22
📬 有问题或反馈?
欢迎提交 issue 或发起讨论!
评论
一个开放协议,规定了 AI 应用如何以统一方式连接外部工具与数据源。客户端负责与模型对话,MCP 服务负责提供工具、资源和提示模板,两者通过标准消息通信,同一个服务可以被不同客户端复用。