modelcontextprotocol/rust-sdk

The official Rust SDK for the Model Context Protocol

RMCP – Rust Model Context Protocol SDK

简介

  • 这是 Model Context Protocol (MCP) 的官方 Rust 实现,该规范用于 AI 代理(客户端)与 AI 驱动服务(服务器)之间的通信。
  • 提供运行于 Tokio 异步执行环境的 客户端 与 服务器 库。
  • 包含一个过程宏 crate (rmcp-macros),可为 tools、prompts、resources、subscriptions 及其他 MCP 功能生成样板代码。

主要功能 (截至 2026‑07‑28 规范)

  • 服务器发现与版本协商 – 客户端可在发送任何请求前发现服务器支持的协议版本与功能。
  • 传输无关的订阅 – 长时间运行的更新流(例如资源变更、通知)可在任何传输层(stdio、child‑process、HTTP 等)上运行。
  • 多轮请求 – 单一逻辑请求可包含多次往返消息。
  • 响应缓存 – 内置响应缓存支持,避免重复工作。
  • 标准 HTTP 路由标头 – MCP 消息可携带 HTTP 风格的标头,用于路由、验证等。
  • 工具、提示词、资源 – 针对可调用函数、可重复使用的消息模板与数据块的一流抽象,皆以 JSON‑Schema 2020‑12 描述。
  • OAuth 支持 – SDK 可将 OAuth 令牌附加至请求中。

典型使用场景

  • 构建通过标准协议调用远程工具(例如计算器、图像生成器)的 AI 代理。
  • 将 LLM 支持的服务(代码审查、摘要工具)公开为 MCP 服务器,供任何客户端发现并调用。
  • 实现 RAG 流水线,其中资源(文件、数据库行)通过 MCP 提供并在客户端缓存。
  • 创建 即插即用工具生态系统,第三方开发者可发布可自动发现的工具 crate。

如何开始

# 将核心 crate(包含服务器功能)加入您的 Cargo.toml
cargo add rmcp --features server

或直接从 GitHub 拉取最新的开发版本:

cargo add rmcp --features server \
    --git https://github.com/modelcontextprotocol/rust-sdk --branch main

最小客户端示例

use rmcp::{ServiceExt, transport::TokioChildProcess, ConfigureCommandExt};
use tokio::process::Command;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 启动服务器进程(此处为实现参考服务器的 npm 包)
    let client = ().serve(
        TokioChildProcess::new(Command::new("npx").configure(|cmd| {
            cmd.arg("-y").arg("@modelcontextprotocol/server-everything");
        }))
    )?.await?;
    // 示例请求 – 列出服务器的根目录
    let roots = client.list_roots().await?;
    println!("Roots: {:?}", roots);
    Ok(())
}

最小服务器示例(简单计算器)

use rmcp::{tool, tool_router, ServiceExt, transport::stdio};
use serde::Deserialize;

#[derive(Debug, Deserialize, schemars::JsonSchema)]
struct AddParams { a: i32, b: i32 }

#[tool_router(server_handler)]
struct Calculator;

impl Calculator {
    #[tool(description = "Add two numbers")]
    fn add(&self, params: rmcp::handler::server::wrapper::Parameters<AddParams>) -> String {
        (params.0.a + params.0.b).to_string()
    }
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let service = Calculator.serve(stdio()).await?;
    service.waiting().await?;
    Ok(())
}

宏会自动生成工具参数的 JSON‑Schema 并连接 RPC 路由。

项目结构

  • crates/rmcp – 核心协议实现、客户端与服务器运行时、模型、传输层。
  • crates/rmcp-macros – 减少样板代码的过程宏 (#[tool]、#[prompt]、#[resource] 等)。
  • examples/ – 服务器(计算器、计数器)与客户端(通过 stdio 的一切)的可执行示例。

成熟度与生态系统

  • 已发布于 crates.io (rmcp crate),并附有显示自动化测试状态的 CI 徽章。
  • 实现 稳定版 MCP 规范 (2026‑07‑28),同时保持与 2025‑11‑25 版本的向后兼容性。
  • 文档托管于 docs.rs;完整的 MCP 规范位于 modelcontextprotocol.io。
  • 迁移至新规范版本的社区讨论可通过 GitHub 讨论链接获取。

了解更多


此 SDK 是一个真正的生产级 Rust 库,用于构建遵循 Model Context Protocol 的 AI 代理通信服务。

相关

  • 项目
  • 项目
  • 项目
  • 项目
  • 项目