Rust MCP SDK

repository·main·Indexed 41 days ago

https://github.com/rust-mcp-stack/rust-mcp-sdk

A high-performance, asynchronous Rust toolkit for building Model Context Protocol (MCP) servers and clients. It provides full support for the MCP 2026-07-28 stateless specification and includes framework integrations for Actix-web and Axum, supporting both Streamable HTTP and SSE transports.

Tokens
141.1K
Snippets
372
Records
508
Agent score
46%

What's inside Rust MCP SDK

  1. Overview of the Rust MCP SDK

    main

    The rust-mcp-sdk is a high-performance, asynchronous Rust toolkit designed for building MCP servers and MCP clients. It ensures 100% conformance to the official Model Context Protocol (MCP) test suites and supports the 2025-11-25 protocol specification.

    Core Capabilities

    • Servers: Expose tools (executable functions), resources (readable data), and prompts (interaction templates).
    • Clients: Connect to servers to discover capabilities and invoke them.

    Key Features

    • Transport Support: Stdio, Streamable HTTP, and backward-compatible SSE.
    • Framework Integration: Native support for Axum and Actix-web, or a 'BYO-server' mode for existing applications.
    • Developer Experience: Procedural macros (mcp_tool, tool_box!, mcp_elicit) for automatic schema generation from Rust structs.
    • Security & Production Readiness: OAuth 2.1 support (DCR, PKCE, token refresh), DNS rebinding protection, resumability, health checks, and telemetry hooks.
  2. Understand the rust-mcp-sdk versioning policy

    main

    The project follows Semantic Versioning (SemVer) and maintains two active lines based on the Model Context Protocol (MCP) version they target:

    2.x (Current/Beta)

    • Target Protocol: MCP 2026-07-28
    • Status: Transitioning from beta to stable.
    • Compatibility: No backwards-compatibility with 1.x.
    • Crate Versions: Most crates (e.g., rust-mcp-sdk, rust-mcp-transport, rust-mcp-axum) are currently in the 2.0.0-beta.x range.

    1.x (LTS)

    • Target Protocol: MCP 2025-11-25
    • Status: Long-Term Support (LTS).
    • Support Lifecycle: Receives critical security fixes until at least 2027-07-28.
    • Scope of Fixes: Limited to security vulnerabilities (CVEs), build regressions on stable Rust, and critical protocol compliance gaps. It does not include new 2026-07-28 features or non-critical bug fixes.
  3. Available macros in rust-mcp-macros

    main

    The rust-mcp-macros crate provides several procedural macros to simplify MCP protocol implementation:

    • mcp_tool: Generates a rust_mcp_schema::Tool instance from a struct.
    • mcp_elicit: Generates elicitation logic for gathering user input (supports Form and URL modes).
    • mcp_resource: Generates a rust_mcp_schema::Resource instance from compile-time metadata.
    • mcp_resource_template: Generates a rust_mcp_schema::ResourceTemplate instance for parameterized resources.
    • mcp_prompt: Generates a rust_mcp_schema::Prompt instance and prompt rendering logic from a struct.
    • derive(JsonSchema): Derives a JSON Schema representation for structs and enums (required by other macros).
  4. Explore rust-mcp-sdk example categories

    main

    The rust-mcp-sdk repository provides examples categorized by functionality across different crates:

    Servers and Clients (rust-mcp-sdk crate)

    • Servers: Includes Stdio, Streamable HTTP, Core variants, and health checks.
    • Clients: Includes Stdio, SSE, Streamable HTTP, and Core variants.
    • Auth: Includes OAuth with DCR (Dynamic Client Registration).

    Authentication Providers (rust-mcp-extra crate)

    • Examples for Keycloak, WorkOS, and Scalekit.

    BYO-Server (Bring Your Own Server)

    If you want to embed MCP into an existing web application, use these crates:

    • Axum: Use rust-mcp-axum to embed MCP in existing Axum apps.
    • Actix: Use rust-mcp-actix to embed MCP in existing Actix apps.
  5. Available HTTP Backend Integrations

    main

    The rust-mcp-sdk provides native integrations for the Axum and Actix-web frameworks. You can choose between them based on your existing stack or preference:

    • Axum: Use the rust-mcp-axum crate and the create_axum_server() function.
    • Actix-web: Use the rust-mcp-actix crate and the create_actix_server() function.

    Both backends include support for streamable HTTP transport, SSE, multi-client concurrency, DNS rebinding protection, session management, health checks, event/task stores, and OAuth authentication.

  6. What is Streamable HTTP transport?

    main

    Streamable HTTP is the primary protocol used by HTTP-based MCP backends in this SDK. It provides three main capabilities:

    1. Non-streaming mode: Standard synchronous request-response cycle.
    2. Streaming mode: Allows the server to stream notifications and results to the client as they become available.
    3. Batch messages: Supports sending multiple JSON-RPC messages within a single HTTP request.
  7. Use OAuthProxy for providers without DCR

    main

    OAuthProxy is a mechanism designed to enable authentication with OAuth providers that do not support Dynamic Client Registration (DCR).

    It functions by:

    1. Accepting any client registration request locally.
    2. Handling the DCR process on your server side.
    3. Using pre-registered application credentials upstream.
    4. Forwarding callbacks to allow dynamic redirect URIs even with providers that require fixed ones.

    ⚠️ Note: OAuthProxy support is currently in development. For existing implementations, use RemoteAuthProvider instead.

  8. How Client Sampling works

    main

    Client Sampling allows an MCP server to request an LLM completion from the client. This pattern enables 'human-in-the-loop' workflows: when the server sends a sampling request, the client is responsible for presenting the request to the user, selecting an appropriate LLM model, executing the call, and returning the result to the server.

    When implementing a handler for these requests, the server receives CreateMessageRequestParams (containing the conversation history and system prompt) and must return a CreateMessageResult containing the assistant's response, the model used, and the stop reason.

    async fn handle_create_message_request(
        &self, params: CreateMessageRequestParams, _runtime: &dyn McpClient,
    ) -> Result<CreateMessageResult, RpcError> {
        // params contains the conversation so far, system prompt, etc.
        // The client selects a model, calls the LLM, and returns the result
    
        Ok(CreateMessageResult {
            role: Role::Assistant,
            content: CreateMessageContent::TextContent(TextContent::new(
                "Here is the completion from the LLM...".into(),
                None,
                None,
            )),
            model: "gpt-4".into(),
            stop_reason: Some("endTurn".into()),
            meta: None,
        })
    }
  9. Choose between Standard and Core handlers

    main

    The SDK provides two ways to handle messages, depending on the level of control required:

    • Standard Handler (ClientHandler): Provides per-message-type methods (e.g., handle_list_tools_request). This is the recommended approach for 90% of use cases. Use client_runtime::create_client() to instantiate.
    • Core Handler (ClientHandlerCore): Provides three raw methods for full message-level control. Use this only when you need to intercept or manipulate raw messages. Use client_runtime_core::create_client() to instantiate.
  10. Understand the Big 3 MCP capabilities

    main

    MCP servers primarily provide three types of capabilities. You implement these by overriding specific methods in your ServerHandler:

    CapabilityMethods to overrideDescription
    Toolshandle_list_tools_request + handle_call_tool_requestFunctions the LLM can call
    Resourceshandle_list_resources_request + handle_read_resource_requestData the LLM can read
    Promptshandle_list_prompts_request + handle_get_prompt_requestReusable message templates

    Note: Even if you implement the methods in your handler, a client will not use them unless you also declare the capability in your server's initialization.

  11. Understand the 2026-07-28 stateless protocol features

    main

    The conformance-server demonstrates several advanced features of the 2026-07-28 stateless MCP specification:

    • Stateless transport: Uses POST-only requests without sessions or SSE streaming.
    • InputRequiredResult (MRTR): Tools can request elicitation or sampling inline.
    • Response cache (SEP-2549): Supports principal-scoped caching using ttlMs and cacheScope.
    • Logging: Supports all severity levels (debug through emergency).
    • Completions: Provides prompt argument autocompletion.
    • Resource subscriptions: Supports subscribing/unsubscribing with update notifications.
    • DNS rebinding protection: Validates Host headers for localhost servers.
    • RequestContext: Provides per-request _meta containing authentication context.
  12. Compare MCP Server and Client roles

    main

    Understanding the division of responsibilities is critical for implementation:

    FeatureServer RoleClient Role
    ProvidesTools, resources, promptsLLM, user interaction, filesystem roots
    RequestsList/read resources, elicitation, samplingCall tools, read resources, get prompts
    NotifiesResource/tool/prompt list changedLogging level, cancellation, initialized
    ImplementationServerHandler / ServerHandlerCoreClientHandler / ClientHandlerCore