Skip to main content

Crate turbomcp

Crate turbomcp 

Source
Expand description

§TurboMCP - Model Context Protocol SDK

Rust SDK for the Model Context Protocol (MCP) with zero-boilerplate macros, transport-agnostic design, and WASM support.

§Features

  • Zero Boilerplate - #[server], #[tool], #[resource], #[prompt] macros
  • Transport Agnostic - STDIO, HTTP, WebSocket, TCP, Unix sockets
  • Runtime Selection - Choose transport at runtime without recompilation
  • BYO Server - Integrate with existing Axum/Tower infrastructure
  • WASM Ready - no_std compatible core for edge deployment
  • Type Safe - Automatic JSON schema generation from Rust types

§Quick Start

use turbomcp::prelude::*;

#[derive(Clone)]
struct Calculator;

#[server(name = "calculator", version = "1.0.0")]
impl Calculator {
    /// Add two numbers together
    #[tool]
    async fn add(&self, a: i64, b: i64) -> i64 {
        a + b
    }

    /// Multiply two numbers
    #[tool]
    async fn multiply(&self, a: i64, b: i64) -> i64 {
        a * b
    }
}

#[tokio::main]
async fn main() {
    Calculator.run_stdio().await.unwrap();
}

§Runtime Transport Selection

With the full feature set, and Calculator from above:

ⓘ
use turbomcp::prelude::*;

#[tokio::main]
async fn main() {
    let transport = std::env::var("MCP_TRANSPORT").unwrap_or_default();

    Calculator.builder()
        .transport(match transport.as_str() {
            "http" => Transport::http("0.0.0.0:8080"),
            "ws" => Transport::websocket("0.0.0.0:8080"),
            "tcp" => Transport::tcp("0.0.0.0:9000"),
            _ => Transport::stdio(),
        })
        .serve()
        .await
        .unwrap();
}

§BYO Server (Axum Integration)

With the http feature:

ⓘ
use axum::{Router, routing::get};
use turbomcp::prelude::*;

#[tokio::main]
async fn main() {
    // Get MCP routes as an Axum router
    let mcp = Calculator.builder().into_axum_router();

    // Merge with your existing routes
    let app = Router::new()
        .route("/health", get(|| async { "OK" }))
        .merge(mcp);

    // Run with your own server
    let listener = tokio::net::TcpListener::bind("0.0.0.0:8080").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

§Feature Flags

Choose the right feature set for your use case:

# Minimal (STDIO only, recommended for CLI tools)
turbomcp = { version = "3.6.0", default-features = false, features = ["minimal"] }

# Full (all transports)
turbomcp = { version = "3.6.0", features = ["full"] }

Available features:

  • stdio - Standard I/O transport (default, works with Claude Desktop)
  • http - Streamable HTTP transport
  • websocket - WebSocket bidirectional transport
  • tcp - Raw TCP socket transport
  • unix - Unix domain socket transport

Re-exports§

pub use turbomcp_telemetry as telemetry;telemetry

Modules§

prelude
Convenient prelude for TurboMCP applications.
testing
In-memory test client for ergonomic MCP server testing. In-memory test client for ergonomic MCP server testing.

Structs§

Annotations
Annotations for content providing metadata.
AudioContent
Audio content (base64 encoded).
BlobResourceContents
Binary resource contents.
CallToolRequest
Request payload for tool invocation A request to execute a specific tool.
CallToolResult
Response payload for tool execution results Re-exports of the canonical tool types from turbomcp_types. The result of a CallToolRequest.
ClientCapabilities
Client capability declaration during initialization Capabilities supported by a client.
ComponentVisibilityRules
Exact-name visibility rules for tools, resources, and prompts Progressive disclosure through component visibility control. Exact-name visibility rules for one MCP component family.
EmbeddedResource
Embedded resource content in a message.
HttpAuthorizationhttp
MCP authorization (OAuth 2.1 protected resource) for the Streamable HTTP transport. With the auth feature, auth::server::JwtBearerValidator implements BearerTokenValidator. MCP authorization (OAuth 2.1 protected resource) for Streamable HTTP. Protected-resource configuration for the Streamable HTTP transport.
Icon
Icon for tools, resources, prompts, or servers.
Image
Image content type for multimodal responses Wrapper for returning base64-encoded image data.
ImageContent
Image content (base64 encoded).
InitializeRequest
Initial handshake request from client to server The initialize request sent by the client as the first message after connection.
InitializeResult
Initial handshake response with server capabilities The response to a successful initialize request.
Json
JSON content wrapper for structured data responses Wrapper for returning JSON-serialized data from a tool handler.
JsonRpcError
JSON-RPC 2.0 error object JSON-RPC error object
JsonRpcNotification
JSON-RPC 2.0 notification (no response expected) JSON-RPC notification message (no response expected)
JsonRpcRequest
JSON-RPC 2.0 request message JSON-RPC request message
JsonRpcResponse
JSON-RPC 2.0 response message JSON-RPC response message
McpError
Unified MCP error type
Message
A message in a prompt (PromptMessage per spec).
Prompt
Prompt definition.
PromptArgument
Argument definition for prompts.
PromptResult
Result from getting a prompt.
ProtocolConfig
Protocol version negotiation configuration
RequestContext
Canonical per-request context.
Resource
Resource definition.
ResourceAnnotations
Annotations for resources.
ResourceLink
A resource link (reference without embedding contents).
ResourceResult
Result from reading a resource.
ResourceTemplate
Resource template definition.
ServerBuilder
Builder for configuring and launching MCP servers with transports Server builder for configuring and running MCP servers.
ServerCapabilities
Server capability declaration during initialization Capabilities supported by a server.
ServerConfig
Configuration for MCP server behavior, timeouts, and protocol versions Server configuration.
ServerConfigBuilder
Builder for constructing ServerConfig with type-safe defaults Builder for server configuration.
ServerInfo
Server information for MCP initialization.
Text
Text content type for string responses Wrapper for explicitly returning text content.
TextContent
Text content with optional annotations.
TextResourceContents
Textual resource contents.
Tool
Tool definition.
ToolAnnotations
Annotations for tools describing behavior hints.
ToolError
Tool execution error with code and message Error type for tool handlers that supports the ? operator.
ToolInputSchema
JSON Schema for tool input parameters.
ToolOutputSchema
JSON Schema for a tool’s structured output (outputSchema per MCP spec).
ToolResult
Result from calling a tool.
VisibilityConfig
Runtime visibility configuration for reducing the MCP component surface Progressive disclosure through component visibility control. Complete runtime visibility configuration for an MCP server.
VisibilityLayer
Handler wrapper for progressive disclosure and AI-friendly tool filtering Progressive disclosure through component visibility control. A visibility layer that wraps an McpHandler and filters components.
VisibilitySessionGuard
RAII cleanup guard for session-specific visibility overrides Progressive disclosure through component visibility control. RAII guard that automatically cleans up session visibility state when dropped.

Enums§

BearerRejectionhttp
MCP authorization (OAuth 2.1 protected resource) for the Streamable HTTP transport. With the auth feature, auth::server::JwtBearerValidator implements BearerTokenValidator. MCP authorization (OAuth 2.1 protected resource) for Streamable HTTP. Why a bearer token was refused.
Content
Content block in MCP messages (ContentBlock per spec).
IconTheme
Theme for an icon.
MessageId
Unique identifier for correlating requests and responses Unique identifier for messages
ResourceContents
Contents of a resource (text or binary).
Role
Role in a conversation or prompt message.
SamplingContent
Content block for sampling messages (SamplingMessageContentBlock per spec).
SamplingContentBlock
Wrapper that deserializes as either a single content block or an array.
Transport
Transport configuration enum for runtime transport selection Transport configuration for the server.

Constants§

CRATE_NAME
TurboMCP crate name
VERSION
TurboMCP version from Cargo.toml

Traits§

BearerTokenValidatorhttp
MCP authorization (OAuth 2.1 protected resource) for the Streamable HTTP transport. With the auth feature, auth::server::JwtBearerValidator implements BearerTokenValidator. MCP authorization (OAuth 2.1 protected resource) for Streamable HTTP. Validates the bearer tokens presented to an HttpAuthorization-enabled server.
IntoPromptResult
Convert any type to a PromptResult.
IntoResourceResult
Convert any type to a ResourceResult.
IntoToolError
Trait for converting errors into tool error responses Convenience trait for converting to ToolError with context.
IntoToolResponse
Trait for converting values into tool responses Trait for types that can be converted into a tool response.
IntoToolResult
Convert any type to a ToolResult.
McpHandler
The unified MCP handler trait.
McpHandlerExt
Extension trait providing transport-specific run methods (run_stdio, run_http, etc.) Extension trait for running McpHandler on various transports.
McpServerExt
Extension trait for MCP server operations Extension trait for creating server builders from handlers.

Functions§

structured_content_if_object
Return value only if it may legally occupy structuredContent.

Type Aliases§

Implementation
Spec-aligned alias for ServerInfo.
McpResult
Result type alias for MCP operations
MetaMap
The _meta map carried by every MCP result type.
PromptMessage
Spec-aligned alias for Message.
ValidationFuturehttp
MCP authorization (OAuth 2.1 protected resource) for the Streamable HTTP transport. With the auth feature, auth::server::JwtBearerValidator implements BearerTokenValidator. MCP authorization (OAuth 2.1 protected resource) for Streamable HTTP. Future returned by BearerTokenValidator::validate.

Attribute Macros§

completion
Marks a method as the server’s argument-completion handler.
description
Provides a description for a tool parameter.
prompt
Marks a method as a prompt handler within a #[server] block.
resource
Marks a method as a resource handler within a #[server] block.
roots_changed
Marks a method as the handler for notifications/roots/list_changed.
server
Marks an impl block as an MCP server with automatic McpHandler implementation.
set_level
Marks a method as the handler for logging/setLevel.
subscribe
Marks a method as the handler for resources/subscribe.
tool
Marks a method as a tool handler within a #[server] block.
unsubscribe
Marks a method as the handler for resources/unsubscribe.