tower-mcp
Tower-native Model Context Protocol (MCP) implementation for Rust.
Overview
tower-mcp provides a composable, middleware-friendly approach to building MCP servers using the Tower service abstraction. Unlike framework-style MCP implementations, tower-mcp treats MCP as just another protocol that can be served through Tower's Service trait.
This means:
- Standard tower middleware (tracing, metrics, rate limiting, auth) just works
- Same service can be exposed over multiple transports (stdio, HTTP, WebSocket)
- Easy integration with existing tower-based applications (axum, tonic)
Familiar to axum Users
If you've used axum, tower-mcp's API will feel familiar:
- Extractor pattern: Tool handlers use extractors like
State<T>,Json<T>, andContext - Router composition:
McpRouter::merge()andMcpRouter::nest()work like axum's router methods - Per-handler middleware: Apply Tower layers to individual tools, resources, or prompts via
.layer() - Builder pattern: Fluent builders for tools, resources, and prompts
Why tower-mcp?
Strengths
| Tower-native middleware | Timeout, rate-limit, auth, tracing -- on the whole server or on individual tools. Any tower::Layer works. |
| All transports | stdio, HTTP/SSE (with stream resumption), WebSocket, and child process. Same router, any transport. |
| In-process testing | TestClient lets you test MCP servers without spawning a subprocess or opening a socket. |
| Conformance | 39/39 server and 265/265 client conformance checks pass in CI on every PR. |
| Capability filtering | Session-based tool/resource/prompt visibility for multi-tenant patterns. |
| No proc macros required | Builder pattern API with optional trait-based tools. Nothing hidden behind #[derive]. Optional #[tool_fn] / #[prompt_fn] / #[resource_fn] macros available for convenience (feature: macros). |
| Async tasks | Full task lifecycle -- background execution, cancellation, TTL cleanup, per-tool task support mode. Clients can poll or wait for long-running tool results. |
| Multi-server proxy | Aggregate N backend servers behind a single endpoint with per-backend middleware and namespace isolation. |
| axum ecosystem | HTTP and WebSocket transports build on axum, so existing axum middleware and extractors work. |
Trade-offs
- More boilerplate than macro-based approaches for simple servers, though the optional
macrosfeature narrows this gap significantly. - Requires Tower/Service familiarity. The
.layer()composition model is powerful but has a learning curve if you haven't used Tower before. - Heavier dependency tree than minimal single-transport implementations, especially with
features = ["full"].
Quick Start
use ;
use JsonSchema;
use Deserialize;
// Define your input type - schema is auto-generated
// Build a tool with type-safe handler
let greet = new
.title
.description
.handler
.build;
// Create router with tools
let router = new
.server_info
.instructions
.tool;
// The router implements tower::Service and can be composed with middleware
Installation
Add to your Cargo.toml:
[]
= "0.9"
Feature Flags
| Feature | Description |
|---|---|
full |
Enable all optional features |
http |
HTTP transport with SSE support (adds axum, hyper) |
websocket |
WebSocket transport for full-duplex communication |
childproc |
Child process transport for spawning subprocess MCP servers |
oauth |
OAuth 2.1 resource server support -- JWT validation, protected resource metadata (requires http) |
jwks |
JWKS endpoint fetching for remote key sets (requires oauth) |
http-client |
HTTP client transport for connecting to remote MCP servers |
oauth-client |
OAuth 2.0 client-side token acquisition -- client credentials grant, auto-discovery, token caching (requires http-client) |
testing |
Test utilities (TestClient) for in-process testing |
dynamic-tools |
Runtime registration/deregistration of tools, prompts, and resources |
proxy |
Multi-server aggregation proxy (McpProxy) |
macros |
Optional proc macros (#[tool_fn], #[prompt_fn], #[resource_fn], #[resource_template_fn]) |
resilience |
Re-export tower-resilience circuit breaker, rate limiter, and bulkhead layers |
stateless |
SEP-1442 stateless MCP mode (experimental) -- serve requests without sessions |
Example with features:
[]
= { = "0.8", = ["full"] }
Types Only
If you only need MCP protocol types and error types -- without tower, tokio, or axum --
use the tower-mcp-types crate directly.
This is useful for editor integrations, code generators, protocol validators, or
any context where you want to serialize/deserialize MCP messages without a runtime.
[]
= "0.9"
tower-mcp-types provides all types from tower_mcp::protocol and tower_mcp::error
with minimal dependencies (serde, serde_json, thiserror, base64). The full
tower-mcp crate re-exports everything from tower-mcp-types, so there is no
duplication if you use both.
Tool Definition
Builder Pattern (Recommended)
use ;
use JsonSchema;
use Deserialize;
let add = new
.description
.read_only // Hint: this tool doesn't modify state
.handler
.build;
Proc Macros (Optional)
Enable with features = ["macros"]. The macros generate builder code -- you can always eject to the builder pattern for full control.
use ;
use ;
use ;
async
async
async
// Each macro generates a constructor: add_tool(), greet_prompt(), config_resource()
let router = new
.server_info
.tool
.prompt
.resource;
Trait-Based (For Complex Tools)
use McpTool;
use ;
use JsonSchema;
use ;
use Arc;
// Convert to Tool and register
let calc = Calculator ;
let router = new.tool;
Handler with Extractors (State, Context, JSON)
Use axum-style extractors to access state, context, and typed input:
use Arc;
use ;
use ;
let state = new;
let search = new
.description
.extractor_handler
.build;
See docs.rs for more patterns including per-tool middleware, icons and titles, raw JSON handlers, and output schemas.
Resource Definition
use ResourceBuilder;
// Static resource with inline content
let config = new
.name
.description
.json
.build;
// Dynamic resource with handler
let status = new
.name
.description
.handler
.build;
let router = new
.resource
.resource;
Prompt Definition
use ;
let greet = new
.description
.required_arg
.optional_arg
.handler
.build;
let router = new.prompt;
Router Composition
Combine routers like in axum:
// Merge routers (combines all tools/resources/prompts)
let api_router = new
.tool
.tool;
let admin_router = new
.tool
.tool;
let combined = new
.merge
.merge;
// Nest with prefix (adds prefix to all tool names)
let v1 = new.tool;
let v2 = new.tool;
let versioned = new
.nest // Tools become "v1_legacy_tool"
.nest; // Tools become "v2_new_tool"
Multi-Server Proxy
Aggregate multiple backend MCP servers behind a single endpoint with McpProxy (feature: proxy). Each backend's tools, resources, and prompts are namespaced to avoid collisions:
use McpProxy;
use StdioClientTransport;
let proxy = builder
.backend
.await
.backend
.await
.build
.await?;
// Tools become db_query, fs_read, etc.
// Serve over any transport.
new.run.await?;
Per-backend Tower middleware applies to individual backends:
use Duration;
use TimeoutLayer;
let proxy = builder
.backend.await
.backend_layer
.backend.await
.backend_layer
.build.await?;
The proxy also supports notification forwarding (backend list-changed events propagate to clients), health checks (proxy.health_check().await), and request coalescing via tower-resilience's CoalesceLayer.
Backends don't need to be built with tower-mcp -- the proxy communicates over standard MCP (JSON-RPC), so it works with servers written in any language or framework: Python (FastMCP), TypeScript, Go, or anything that speaks the MCP protocol. This makes tower-mcp a natural aggregation and middleware layer for polyglot MCP deployments.
See the proxy module docs and examples/proxy.rs.
Router-Level State
Share state across all handlers using with_state():
use Arc;
use Extension;
let state = new;
// Tools access state via Extension<T> extractor
let tool = new
.extractor_handler
.build;
let router = new
.with_state // Makes AppState available to all handlers
.tool;
Transports
Stdio (CLI/local)
use ;
let router = new
.server_info
.tool;
// Serve over stdin/stdout
new.serve.await?;
HTTP with SSE
use ;
let router = new
.server_info
.tool;
let transport = new;
let app = transport.into_router;
// Serve with axum
let listener = bind.await?;
serve.await?;
With Authentication Middleware
use extract_api_key;
use middleware;
// Add auth layer to the HTTP transport
let app = transport.into_router
.layer;
MCP Middleware
tower-mcp ships three MCP-specific middleware layers alongside standard tower middleware:
| Layer | Target | Purpose |
|---|---|---|
McpTracingLayer |
All requests | Structured tracing with spans for request lifecycle |
ToolCallLoggingLayer |
tools/call only |
Focused tool call audit logging with annotation hints |
AuditLayer |
All requests | Comprehensive audit events (mcp::audit tracing target) |
use ServiceBuilder;
use ;
let transport = new
.layer;
Standard tower middleware (timeout, rate limiting, concurrency) also composes naturally via .layer() on transports and individual tools.
Testing
tower-mcp includes TestClient (feature: testing) for in-process server testing -- no subprocess, no network, no port management:
use TestClient;
use json;
let mut client = from_router;
client.initialize.await;
// List and call tools
let tools = client.list_tools.await;
assert_eq!;
let result = client.call_tool.await;
assert_eq!;
// Typed deserialization
let stats: ServerStats = client.call_tool_typed.await;
// Assert expected errors
let err = client.call_tool_expect_error.await;
TestClient handles JSON-RPC framing, request IDs, and protocol initialization. Methods panic on unexpected errors, keeping test code concise.
Capability Filtering
Control which tools, resources, and prompts each session can see. This enables multi-tenant patterns where different clients get different capabilities based on auth claims or session state:
use CapabilityFilter;
// Hide write tools from sessions that aren't authorized
let router = new
.tool
.tool
.tool_filter;
write_guard uses tool annotations: tools marked .read_only() are always visible, while other tools are only shown to sessions where the predicate returns true. Hidden tools return "method not found" by default, or configure DenialBehavior::Unauthorized to reveal their existence without granting access.
Filters work on resources and prompts too:
let router = new
.resource
.resource
.resource_filter;
Architecture
+-----------------+
| Your App |
+-----------------+
|
+-----------------+
| Tower Middleware| <-- tracing, metrics, auth, etc.
+-----------------+
|
+-----------------+
| JsonRpcService | <-- JSON-RPC 2.0 framing
+-----------------+
|
+-----------------+
| McpRouter | <-- Request dispatch
+-----------------+
|
+------------+------------+
| | |
+--------+ +--------+ +--------+
| Tool 1 | | Tool 2 | | Tool N |
+--------+ +--------+ +--------+
Protocol Compliance
tower-mcp targets the MCP specification 2025-11-25 with backward compatibility for 2025-03-26. The official MCP conformance test suite runs in CI on every PR, currently passing 39/39 server tests and 265/265 client checks (24/24 scenarios).
- JSON-RPC 2.0 message format
- Protocol version negotiation (supports
2025-11-25and2025-03-26) - Capability negotiation
- Initialize/initialized lifecycle
- tools/list and tools/call
- Tool annotations
- Batch requests
- resources/list, resources/read, resources/subscribe
- resources/templates/list
- prompts/list, prompts/get
- Logging (notifications/message, logging/setLevel)
- Icons on tools/resources/prompts (SEP-973)
- Implementation metadata
- Sampling with tools/toolChoice (SEP-1577)
- Elicitation (form and URL modes)
- Session management
- Progress notifications
- Request cancellation
- Completion (autocomplete)
- Roots (filesystem discovery)
- Sampling (all transports)
- Async tasks (task ID, status tracking, TTL cleanup, per-tool task support mode)
- SSE event IDs and stream resumption (SEP-1699)
-
_metafield on all protocol types
We track all MCP Specification Enhancement Proposals (SEPs) as GitHub issues. A weekly workflow syncs status from the upstream spec repository.
Examples
A full-featured MCP server for querying crates.io is available as a standalone project: cratesio-mcp. A demo instance is deployed at https://cratesio-mcp.fly.dev -- connect with any MCP client that supports HTTP transport.
The repo includes 23 focused examples organized by topic:
| Category | Examples |
|---|---|
| Getting started | getting_started -- tools, resources, prompts, stdio transport |
| Transports | http_server, websocket_server |
| Middleware | middleware (transport, per-tool, per-resource, per-prompt, guards), rate_limiting, capability_filtering, tool_selection |
| Authentication | http_auth, oauth_client, external_api_auth |
| Clients | client_cli, http_client, http_sse_client |
| Bidirectional | sampling_server, client_handler |
| Dynamic | dynamic_capabilities -- runtime tool/prompt/resource registration |
| Advanced | proxy, resource_templates, structured_output, error_handling, testing |
| Real-world | weather_server -- external API integration |
| Macros | tool_macro -- #[tool_fn], #[prompt_fn], #[resource_fn] |
Clone the repo and the .mcp.json configures example servers automatically:
# Run your MCP agent here - servers will be available automatically
Development
# Format, lint, and test
License
MIT OR Apache-2.0