turbomcp 4.0.0-alpha.2

Rust SDK for the Model Context Protocol (MCP): macro-driven servers and a typed client, dual protocol versions, stdio/HTTP/WebSocket transports, OAuth 2.1, OpenTelemetry.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
//! # turbomcp
//!
//! The TurboMCP v4 SDK facade: a single crate that re-exports the layered
//! workspace crates and the `#[server]` / `#[tool]` / `#[resource]` / `#[prompt]`
//! macros, plus a [`prelude`] for the common imports.
//!
//! ```
//! use turbomcp::prelude::*;
//!
//! #[derive(Clone)]
//! struct Hello;
//!
//! #[server(name = "hello", version = "1.0.0")]
//! impl Hello {
//!     /// Say hello to someone.
//!     #[tool]
//!     async fn hello(&self, name: String) -> McpResult<String> {
//!         Ok(format!("Hello, {name}!"))
//!     }
//! }
//!
//! # async fn run() -> Result<(), turbomcp::ProtocolError> {
//! // Logs MUST go to stderr — stdout carries the MCP protocol framing.
//! Hello.run_stdio().await
//! # }
//! ```
//!
//! ## Tool return types
//!
//! A `#[tool]` returns `String`/`&str`, any numeric or `bool` scalar, `()`
//! (empty success), [`Json<T>`] (structured output — the value lands in
//! `structuredContent` and the macro generates the tool's `outputSchema` from
//! `T`), [`Image`] / [`Audio`] (base64 `data` + `mime_type` → a content
//! block), or a [`neutral::CallToolResult`] — each optionally wrapped in
//! [`McpResult`]. A returned [`McpError`] becomes a *tool-level* error
//! (`CallToolResult { isError: true }`) the model can read and correct, not a
//! transport error.
//!
//! ```
//! use turbomcp::prelude::*;
//!
//! #[derive(serde::Serialize, turbomcp::schemars::JsonSchema)]
//! struct Stats { count: u64, mean: f64 }
//!
//! #[derive(Clone)]
//! struct Kitchen;
//!
//! #[server(name = "kitchen-sink", version = "1.0.0")]
//! impl Kitchen {
//!     /// A bare scalar becomes a text content block.
//!     #[tool]
//!     async fn add(&self, a: i64, b: i64) -> i64 { a + b }
//!
//!     /// `Json<T>` becomes `structuredContent` + a generated `outputSchema`.
//!     #[tool]
//!     async fn stats(&self) -> Json<Stats> { Json(Stats { count: 3, mean: 1.5 }) }
//!
//!     /// `Image`/`Audio` become a single image/audio content block.
//!     #[tool]
//!     async fn chart(&self) -> Image {
//!         Image { data: String::new(), mime_type: "image/png".into() }
//!     }
//!
//!     /// A returned `McpError` is a tool-level error, not a transport error.
//!     #[tool]
//!     async fn divide(&self, a: f64, b: f64) -> McpResult<f64> {
//!         if b == 0.0 {
//!             return Err(McpError::invalid_params("b must be non-zero"));
//!         }
//!         Ok(a / b)
//!     }
//! }
//! ```
//!
//! Note: on the `2025-11-25` wire `structuredContent` must be a JSON object,
//! so a `Json<T>` serializing to a scalar or array carries its value in the
//! text mirror only there; the `2026-07-28` wire accepts any JSON value.
//!
//! ## RPC middleware
//!
//! Cross-cutting concerns wrap the built dispatcher as [`tower::Layer`]s over
//! `Service<JsonRpcMessage>` — one `call` for every method under every
//! transport, and the tower ecosystem (`ServiceBuilder`, `timeout`,
//! `ConcurrencyLimit`, …) composes onto an MCP server unchanged. `tower` itself
//! is re-exported as [`tower`] so the `Layer` you write is the one the SDK
//! expects. Start from [`TracingLayer`] (the shape in 30 lines) and the
//! [`middleware` example](https://github.com/Epistates/turbomcp/blob/main/crates/turbomcp/examples/middleware.rs).
//!
//! Auth and rate limiting are *not* RPC middleware here: both need the HTTP
//! request a JSON-RPC frame no longer carries, so they are transport-level seams
//! (`HttpConfig::with_authenticator` / `with_rate_limiter`, feature `http`).
//! Per-tool authorization is `#[tool(scopes(…))]`.
#![forbid(unsafe_code)]
// docs.rs builds with `--cfg docsrs` on nightly so every feature-gated item
// renders with the feature that unlocks it.
#![cfg_attr(docsrs, feature(doc_cfg))]
// Every example in these docs is a real doctest — they are the API contract
// users read first, so they compile or the build fails.
#![warn(missing_docs)]

// ---- foundation -------------------------------------------------------------

pub use turbomcp_core::{
    Claims, Identity, Implementation, JsonRpcError, JsonRpcMessage, JsonRpcNotification,
    JsonRpcRequest, JsonRpcResponse, LogLevel, McpError, McpResult, ProtocolVersion,
    RequestContext, RequestId, codes,
};

/// Version-stable, handler-facing types (the surface user handlers speak).
pub use turbomcp_protocol::neutral;

/// The MCP method-name constants (`methods::request::TOOLS_CALL`, …). Match on
/// these rather than string literals in RPC middleware — a literal is where a
/// renamed method silently stops matching.
pub use turbomcp_protocol::methods;

/// Reading the component tags that `#[tool(tags(…))]` / `#[resource(tags(…))]`
/// / `#[prompt(tags(…))]` write into a component's `_meta`.
pub use turbomcp_server::tags;

/// Progressive disclosure: which components a given caller may see — and
/// therefore reach. Install with
/// [`ServerBuilder::with_visibility`](ServerBuilder::with_visibility).
///
/// A hidden component is refused *exactly as one that does not exist*, since a
/// distinct "forbidden" answer would disclose what the policy is hiding.
/// [`Visibility`] covers the two common cases (hide by tag, hide what the
/// caller lacks the scopes for); implement [`VisibilityPolicy`] — a bare
/// closure will do — for anything else, including per-session unlocking keyed
/// on your own store.
pub use turbomcp_server::visibility;

pub use turbomcp_server::{ComponentKind, Visibility, VisibilityPolicy, VisibleComponent};

// ---- service seam + codec ---------------------------------------------------

pub use turbomcp_codec::{Codec, CodecError, DefaultCodec, SerdeJsonCodec};
pub use turbomcp_service::{
    CancellationToken, McpService, ProtocolError, ServeConfig, Transport, serve, serve_with,
};

/// RPC middleware: [`tower::Layer`]s over the `Service<JsonRpcMessage>` seam,
/// applying identically under stdio, HTTP, and WebSocket.
///
/// [`TracingLayer`] wraps each RPC in a `tracing` span naming the method — it is
/// also the smallest complete worked example of the shape (see its source).
/// Compose it, or your own, around the built dispatcher:
///
/// ```no_run
/// use turbomcp::prelude::*;
/// use turbomcp::{LegacySessionAdapter, TracingLayer, serve_stdio, tower::Layer};
///
/// # #[derive(Clone)]
/// # struct MyServer;
/// # #[server(name = "my-server", version = "1.0.0")]
/// # impl MyServer {
/// #     #[tool]
/// #     async fn ping(&self) -> String { "pong".into() }
/// # }
/// # async fn run() -> Result<(), turbomcp::ProtocolError> {
/// // What `run_stdio()` does, with one layer added.
/// let service = TracingLayer.layer(LegacySessionAdapter::new(MyServer.into_server().build()));
/// serve_stdio(service).await
/// # }
/// ```
///
/// See the [`middleware` example](https://github.com/Epistates/turbomcp/blob/main/crates/turbomcp/examples/middleware.rs)
/// for an observing layer and a short-circuiting one, and
/// [`MIGRATION.md`](https://github.com/Epistates/turbomcp/blob/main/crates/turbomcp/MIGRATION.md)
/// for the mapping from v3's `McpMiddleware` hooks.
pub use turbomcp_service::TracingLayer;

/// The service [`TracingLayer`] produces.
pub use turbomcp_service::Tracing;

/// The canonical [`McpError`] → JSON-RPC error mapping, for middleware that
/// rejects a request before it reaches a handler. Use
/// [`mcp_to_jsonrpc_error_for`] when the negotiated [`ProtocolVersion`] is in
/// hand — two codes are version-split.
pub use turbomcp_service::{mcp_to_jsonrpc_error, mcp_to_jsonrpc_error_for};

/// Re-export of [`tower`], version-matched to the one behind [`McpService`], so
/// middleware written against it composes without a duplicate-crate mismatch.
pub use tower;

// ---- server -----------------------------------------------------------------

/// Server composition: mount several servers under prefixes and serve them as
/// one. Tools and prompts are namespaced `{prefix}.{name}`; resource URIs are
/// left alone (a URI is already a namespace, and rewriting one makes it a lie).
///
/// ```no_run
/// use turbomcp::prelude::*;
/// use turbomcp::{Composite, Implementation};
///
/// # #[derive(Clone)] struct Weather;
/// # #[server(name = "weather", version = "1.0.0")]
/// # impl Weather { #[tool] async fn forecast(&self) -> String { "sunny".into() } }
/// # #[derive(Clone)] struct News;
/// # #[server(name = "news", version = "1.0.0")]
/// # impl News { #[tool] async fn headlines(&self) -> String { "…".into() } }
/// # async fn run() -> McpResult<()> {
/// // Serves `weather.forecast` and `news.headlines`.
/// let gateway = Composite::new(Implementation::new("gateway", "1.0.0"))
///     .mount("weather", Weather.into_server())?
///     .mount("news", News.into_server())?
///     .into_server()
///     .build();
/// # Ok(()) }
/// ```
pub use turbomcp_server::{Composite, CompositeServer};

pub use turbomcp_server::{
    Audio, CachePolicies, CallToolContext, ClientHandle, CompleteContext, GetPromptContext, Image,
    IntoCallToolResult, IntoGetPromptResult, IntoReadResourceResult, IntoServerBuilder, Json,
    LegacySessionAdapter, ListPromptsContext, ListResourceTemplatesContext, ListResourcesContext,
    ListToolsContext, LogSender, McpServerCore, MethodRouter, ProgressReporter,
    ReadResourceContext, ServerBuilder, ServerNotifier, SessionBackend, SessionState, SessionStore,
    TaskBackend, TaskError, TaskSnapshot, TaskStatus, TaskStore, VersionDispatcher,
    WithCompletions, WithPrompts, WithResources, WithTools,
};

/// Re-export of [`schemars`] for deriving `JsonSchema` on `#[tool]` argument
/// structs and [`Json`] structured-output types, so downstream crates don't pin
/// a separate `schemars` version. Use `#[derive(turbomcp::schemars::JsonSchema)]`.
pub use schemars;

// ---- transports -------------------------------------------------------------

pub use turbomcp_transport_stdio::{serve_stdio, serve_stdio_with, stdio};

/// Streamable HTTP transport (axum 0.8). Enable with the `http` feature.
///
/// The one-liner is [`ServeHttp::run_http`](http::ServeHttp::run_http) on a
/// builder — it builds the dispatcher, wires session termination (`DELETE`)
/// automatically, and serves:
///
/// ```no_run
/// use turbomcp::prelude::*;
/// use turbomcp::http::{HttpConfig, ServeHttp};
///
/// #[derive(Clone)]
/// struct MyServer;
///
/// #[server(name = "my-server", version = "1.0.0")]
/// impl MyServer {
///     #[tool]
///     async fn ping(&self) -> String { "pong".into() }
/// }
///
/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
/// MyServer.into_server().run_http("127.0.0.1:8080".parse()?, HttpConfig::new()).await?;
/// # Ok(())
/// # }
/// ```
///
/// For full control — in particular to wrap the dispatcher in RPC middleware
/// such as the telemetry [`TraceContextLayer`](crate::telemetry::TraceContextLayer)
/// (feature `telemetry`) — build the service yourself and call
/// [`serve_http`](http::serve_http). Note that this path does *not* auto-wire
/// `DELETE` session termination; pass
/// [`HttpConfig::with_session_terminator`](http::HttpConfig::with_session_terminator)
/// if you need it.
///
/// ```no_run
/// # use turbomcp::prelude::*;
/// use turbomcp::http::{HttpConfig, serve_http};
///
/// # #[derive(Clone)]
/// # struct MyServer;
/// # #[server(name = "my-server", version = "1.0.0")]
/// # impl MyServer {
/// #     #[tool]
/// #     async fn ping(&self) -> String { "pong".into() }
/// # }
/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
/// # let addr = "127.0.0.1:8080".parse()?;
/// // …or `SomeLayer::new().layer(…)` around this to add RPC middleware.
/// let service = MyServer.into_server().build();
/// serve_http(addr, service, HttpConfig::new()).await?;
/// # Ok(())
/// # }
/// ```
#[cfg(feature = "http")]
#[cfg_attr(docsrs, doc(cfg(feature = "http")))]
pub mod http {
    use std::net::SocketAddr;
    use std::sync::Arc;

    pub use turbomcp_service::SessionTerminator;
    pub use turbomcp_transport_http::{HttpConfig, HttpError, router, serve_http};

    use turbomcp_server::{McpServerCore, ServerBuilder};

    /// One-call HTTP serving for a [`ServerBuilder`] (the value
    /// `MyServer.into_server()` produces).
    pub trait ServeHttp {
        /// Build this server's dispatcher and serve it over Streamable HTTP on
        /// `addr` until `config`'s shutdown token fires.
        ///
        /// Session termination (`DELETE`) is wired automatically from the built
        /// dispatcher, so the endpoint honors client-initiated termination by
        /// default. To compose RPC middleware first, build the dispatcher
        /// yourself and call [`serve_http`] instead.
        fn run_http(
            self,
            addr: SocketAddr,
            config: HttpConfig,
        ) -> impl std::future::Future<Output = Result<(), HttpError>> + Send;
    }

    impl<S> ServeHttp for ServerBuilder<S>
    where
        S: McpServerCore + Clone + Send + Sync + 'static,
    {
        async fn run_http(self, addr: SocketAddr, config: HttpConfig) -> Result<(), HttpError> {
            let dispatcher = self.build();
            let config = config.with_session_terminator(Arc::new(dispatcher.session_terminator()));
            // Graceful teardown: when the shutdown token fires, end the live
            // `subscriptions/listen` registrations — each gets the frozen
            // `2026-07-28` closing envelope before the transport tears its
            // listen SSE stream down off the same token.
            let closer = dispatcher.clone();
            let shutdown = config.shutdown_token();
            tokio::spawn(async move {
                shutdown.cancelled().await;
                closer.close_subscriptions().await;
            });
            serve_http(addr, dispatcher, config).await
        }
    }
}

/// WebSocket transport (bidirectional, non-spec convenience). Enable with the
/// `websocket` feature. Serve with
/// [`ws::serve_websocket`] over a `TcpListener` (see [`ws::WsConfig`] for
/// Origin policy, bearer auth, limits, and keepalive), or connect a client
/// transport with [`ws::connect`].
#[cfg(feature = "websocket")]
#[cfg_attr(docsrs, doc(cfg(feature = "websocket")))]
pub use turbomcp_transport_ws as ws;

/// OAuth 2.1 resource-server auth: bearer-token validation + RFC 9728 metadata.
/// Enable with the `auth` feature, then protect an HTTP endpoint with
/// [`HttpConfig::with_authenticator`](http::HttpConfig::with_authenticator).
#[cfg(feature = "auth")]
#[cfg_attr(docsrs, doc(cfg(feature = "auth")))]
pub use turbomcp_auth as auth;

/// The HTTP authentication seam (implemented by [`auth::ResourceServer`]).
#[cfg(feature = "http")]
#[cfg_attr(docsrs, doc(cfg(feature = "http")))]
pub use turbomcp_service::{AuthDecision, HttpAuthenticator};

/// The HTTP rate-limiting seam + the in-process `governor`-backed default.
/// Apply with [`HttpConfig::with_rate_limiter`](http::HttpConfig::with_rate_limiter).
#[cfg(feature = "http")]
#[cfg_attr(docsrs, doc(cfg(feature = "http")))]
pub use turbomcp_service::{GovernorRateLimiter, RateKey, RateLimiter};

/// OpenTelemetry observability: the [`TraceContextLayer`](telemetry::TraceContextLayer)
/// (W3C trace continuation over `_meta` + PII-safe identity spans), the
/// [`MetricsLayer`](telemetry::MetricsLayer) (request count / duration /
/// in-flight, labeled by method + version + outcome), and an optional OTLP
/// export pipeline (traces + metrics). Enable with the `telemetry` feature.
#[cfg(feature = "telemetry")]
#[cfg_attr(docsrs, doc(cfg(feature = "telemetry")))]
pub use turbomcp_telemetry as telemetry;

/// The MCP client: [`client::ClientBuilder`] runs the handshake + version
/// negotiation, then [`client::Client`] speaks the typed [`neutral`] API.
/// Enable with the `client` feature.
#[cfg(feature = "client")]
#[cfg_attr(docsrs, doc(cfg(feature = "client")))]
pub use turbomcp_client as client;

/// The draft Tasks extension (`io.modelcontextprotocol/tasks`, SEP-2663):
/// register [`ext_tasks::TasksExtension`] with `ServerBuilder::with_extension`
/// to answer `tools/call` with an async task handle. Enable with the
/// `ext-tasks` feature.
#[cfg(feature = "ext-tasks")]
#[cfg_attr(docsrs, doc(cfg(feature = "ext-tasks")))]
pub use turbomcp_ext_tasks as ext_tasks;

// ---- macros -----------------------------------------------------------------

pub use turbomcp_macros::{completion, mcp_header, prompt, resource, server, tool};

/// Support items referenced by `#[server]`-generated code. **Not** a stable API
/// — do not depend on it directly; it exists only so generated code has a single
/// rooted path (`::turbomcp::__macros::…`) for its dependencies.
#[doc(hidden)]
pub mod __macros {
    pub use schemars;
    pub use serde;
    pub use serde_json;

    pub use turbomcp_core::meta::keys::SCOPES as SCOPES_META_KEY;
    pub use turbomcp_core::meta::keys::TAGS as TAGS_META_KEY;
    pub use turbomcp_core::{McpError, McpResult};
    pub use turbomcp_protocol::neutral;
    pub use turbomcp_server::__macro_support::{
        close_object_schema, extend_object_schema, mark_mcp_header, match_uri_template,
        normalize_input_schema,
    };
}

/// The common imports for building a server.
pub mod prelude {
    pub use crate::neutral;
    pub use turbomcp_core::{Implementation, LogLevel, McpError, McpResult, RequestContext};
    pub use turbomcp_server::{
        Audio, CallToolContext, CompleteContext, GetPromptContext, Image, IntoServerBuilder, Json,
        ListPromptsContext, ListResourceTemplatesContext, ListResourcesContext, ListToolsContext,
        McpServerCore, ReadResourceContext, ServerBuilder, WithCompletions, WithPrompts,
        WithResources, WithTools,
    };
    pub use turbomcp_transport_stdio::serve_stdio;

    /// The HTTP one-liner `builder.run_http(addr, config)` (feature `http`).
    #[cfg(feature = "http")]
    #[cfg_attr(docsrs, doc(cfg(feature = "http")))]
    pub use crate::http::ServeHttp;

    pub use turbomcp_macros::{completion, mcp_header, prompt, resource, server, tool};
}