Model Context Protocol Rust SDK

repository·main·Indexed 25 days ago

https://github.com/modelcontextprotocol/rust-sdk

RMCP is the official Rust implementation of the Model Context Protocol (MCP) using the tokio async runtime. It provides crates for building MCP clients and servers supporting the 2026-07-28 specification. The SDK includes procedural macros for defining tool and prompt handlers, multiple transport implementations (stdio, HTTP, TCP, Unix Socket, Websocket), and support for OAuth 2.0 authentication and the SEP-2663 Tasks extension.

Tokens
41.1K
Snippets
83
Records
188
Agent score
83%

What's inside modelcontextprotocol-rust-sdk

  1. Understand the MCP OAuth Authorization Flow

    main

    The Model Context Protocol (MCP) implements a secure OAuth 2.1-compliant authorization flow. The process follows these steps:

    1. Resource Metadata Discovery: The client probes the server for WWW-Authenticate parameters (including resource_metadata URL and scope).
    2. Protected Resource Metadata: The client fetches resource server metadata (RFC 9728).
    3. AS Metadata Discovery: The client discovers authorization server metadata via RFC 8414 and OpenID Connect endpoints.
    4. Client Registration: The client may dynamically register itself or use a URL-based Client ID.
    5. Scope Selection: Scopes are selected based on a hierarchy: WWW-Authenticate > PRM > AS metadata > caller defaults.
    6. Authorization Request: An authorization URL is built using PKCE (S256) and RFC 8707 resource parameters.
    7. Authorization Code Exchange: The code is exchanged for an access token.
    8. Token Usage: Tokens are used via AuthClient or AuthorizedHttpClient.
    9. Token Refresh: The SDK automatically uses refresh tokens, forwarding previously granted scopes to ensure compatibility with providers like Azure AD v2.
    10. Scope Upgrade: If a 403 insufficient_scope error occurs, the SDK computes the scope union and re-authorizes with upgraded scopes.
  2. Assess MCP Rust SDK Conformance Status

    main

    The Rust SDK (rmcp) is currently classified as Tier 3. While it meets Tier 2 standards for server and client conformance (both > 80%), it fails Tier 2 requirements regarding issue triage, labeling, stable releases (no version ≥ 1.0.0), and documentation coverage.

    Key Conformance Metrics:

    • Server Conformance: 83.3% (25/30 scenarios pass).
    • Client Conformance: 85.0% (17/20 scenarios pass).
    • Current Version: rmcp-v0.16.0 (Pre-1.0.0).
  3. Available MCP Features and Documentation Status

    main

    The following table summarizes the current state of feature documentation and examples within the rust-sdk. Use this to identify which features have robust support (PASS) versus those that may lack guidance (FAIL/PARTIAL).

    Fully Documented Features (PASS)

    • Tools: Listing and calling tools, including text results.
    • Elicitation: Form mode.
    • Transports: stdio (client and server) and Streamable HTTP (client and server).
    • Schema: JSON Schema 2020-12 support.

    Partially Documented Features (PARTIAL)

    • Resources: Listing, reading text, and templates.
    • Prompts: Listing, getting simple prompts, and getting prompts with arguments.
    • Sampling: Creating messages.
    • Completions: Resource and prompt arguments.
    • Progress: Progress notifications.
    • Elicitation: Enum values.

    Experimental Features (INFO)

    • Tasks: get, result, and cancel (Note: these are experimental and may change).

    Note: Many core features like binary resource reading, image/audio tool results, subscriptions, roots, logging, and cancellation are currently undocumented.

  4. Implement MCP Tasks Extension

    main

    The MCP Tasks extension (io.modelcontextprotocol/tasks) allows servers to handle long-running operations.

    Implementation details:

    • A tool (e.g., slow_sum) can be materialized as a task by returning a CreateTaskResult with resultType: "task" when the client declares task capability support.
    • The server must serve tasks/get, tasks/update, and tasks/cancel endpoints via a TaskManager.
    • This allows a lifecycle of: Create $\rightarrow$ Poll $\rightarrow$ Inline result.
  5. Build and run the WASI-p2 MCP example

    main

    To build the wasi-mcp-example for the wasm32-wasip2 target and run it using the MCP inspector with wasmtime, follow these steps:

    1. Build the project: Use cargo build specifying the package and the WASI-p2 target.
    2. Run with Inspector: Use npx @modelcontextprotocol/inspector followed by your WASM runtime (e.g., wasmtime) and the path to the compiled .wasm file.

    Once running, the MCP inspector will print a URL. Open this URL in a browser to establish a connection to the module via STDIO.

    # Build
    cargo build -p wasi-mcp-example --target wasm32-wasip2
    
    # Run
    npx @modelcontextprotocol/inspector wasmtime target/wasm32-wasip2/debug/wasi_mcp_example.wasm
  6. Set up a Stateless Streamable HTTP Server

    main

    The rmcp library supports stateless Streamable HTTP automatically for the 2026-07-28 protocol.

    To serve legacy clients (< 2026-07-28) without sessions, set with_legacy_session_mode(false) in StreamableHttpServerConfig. You can also use with_json_response(true) to allow simple request/response tools to reply with a single application/json body instead of an SSE stream.

    Note: Because the service is stateless, the service_factory runs per request. Shared state (like DB pools) should be captured in the closure via a Clone handle.

    use rmcp::transport::streamable_http_server::{
        StreamableHttpService, StreamableHttpServerConfig,
        session::local::LocalSessionManager,
    };
    
    let config = StreamableHttpServerConfig::default()
        .with_legacy_session_mode(false) // stateless for legacy versions too
        .with_json_response(true);       // plain JSON replies for simple tools
    
    let service = StreamableHttpService::new(
        || Ok(Counter::new()),           // a fresh handler per request
        LocalSessionManager::default().into(),
        config,
    );
    
    // `StreamableHttpService` is a Tower service — mount it on any router.
    let router = axum::Router::new().nest_service("/mcp", service);
  7. Implement Multi Round-Trip Requests (MRTR)

    main

    MRTR (SEP-2322) allows for complex interactions where a server can ask a client for input mid-request.

    Workflow:

    1. Server answers a tools/call with an InputRequiredResult.
    2. Client uses call_tool to fulfill the elicitation and retry, or call_tool_once for manual control.
    3. Integrity is maintained by sealing/opening the requestState using RequestStateCodec (HMAC).
    4. Both parties must negotiate version 2026-07-28 or higher.
  8. Notify Resource Changes

    main

    Servers can notify clients when resource state changes to trigger re-fetching.

    Server Notifications:

    • context.peer.notify_resource_list_changed(): Notifies that the entire resource list has changed.
    • context.peer.notify_resource_updated(ResourceUpdatedNotificationParam): Notifies that a specific URI has been updated.

    Client Handling: Implement on_resource_list_changed and on_resource_updated in your ClientHandler to react to these notifications.

  9. Install the RMCP crate

    main

    To add the RMCP SDK to your project, use cargo add. You must specify the server feature to build a server.

    Stable version:

    cargo add rmcp --features server

    Development version (main branch):

    cargo add rmcp --features server --git https://github.com/modelcontextprotocol/rust-sdk --branch main
    cargo add rmcp --features server
  10. Stop a Dev Container

    main

    To terminate your development session:

    Locally in Visual Studio Code: Open the command palette and execute Remote: Close Remote Connection.

    In GitHub Codespaces: Codespaces will automatically stop after a period of inactivity, or you can manually stop it via the Codespaces menu in GitHub.

    Remote: Close Remote Connection