tower-mcp 0.10.1

Tower-native Model Context Protocol (MCP) implementation
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
//! Service types for transport-level middleware support
//!
//! This module provides the types needed to apply tower middleware layers
//! to MCP request processing within HTTP and WebSocket transports.
//!
//! The key type is `ServiceFactory`, a function that takes an [`McpRouter`]
//! and produces a boxed, middleware-wrapped service. Transports store this
//! factory and use it when creating sessions.
//!
//! [`CatchError`] is a wrapper that converts middleware errors (e.g., timeouts)
//! into [`RouterResponse`] errors, preserving the `Error = Infallible` contract
//! that [`JsonRpcService`] requires.
//!
//! [`McpRouter`]: crate::router::McpRouter
//! [`RouterResponse`]: crate::router::RouterResponse
//! [`JsonRpcService`]: crate::jsonrpc::JsonRpcService

use std::convert::Infallible;
use std::fmt;
use std::future::Future;
use std::pin::Pin;
#[cfg(any(feature = "http", feature = "websocket"))]
use std::sync::Arc;
use std::task::{Context, Poll};

use pin_project_lite::pin_project;

use tower::util::BoxCloneService;
use tower_service::Service;

use crate::error::JsonRpcError;
use crate::protocol::{McpRequest, RequestId};
#[cfg(any(feature = "http", feature = "websocket"))]
use crate::router::McpRouter;
use crate::router::{RouterRequest, RouterResponse, ToolAnnotationsMap};

/// A boxed, cloneable MCP service with `Error = Infallible`.
///
/// This is the service type that transports use internally after applying
/// middleware layers. It wraps any `Service<RouterRequest>` implementation
/// so that [`JsonRpcService`](crate::jsonrpc::JsonRpcService) can consume it
/// without knowing the concrete middleware stack.
pub type McpBoxService = BoxCloneService<RouterRequest, RouterResponse, Infallible>;

/// A factory function that produces a [`McpBoxService`] from an [`McpRouter`].
///
/// Transports store this factory and call it when creating new sessions.
/// The default factory (from `identity_factory`) returns the router as-is.
/// When `.layer()` is called on a transport, the factory wraps the router
/// with the given middleware and a [`CatchError`] adapter.
#[cfg(any(feature = "http", feature = "websocket"))]
pub(crate) type ServiceFactory = Arc<dyn Fn(McpRouter) -> McpBoxService + Send + Sync>;

/// Create a `ServiceFactory` that returns the router unchanged.
///
/// This is the default factory used by transports when no `.layer()` is applied.
/// Tool annotations are still injected into request extensions.
#[cfg(any(feature = "http", feature = "websocket"))]
pub(crate) fn identity_factory() -> ServiceFactory {
    Arc::new(|router: McpRouter| {
        let annotations = router.tool_annotations_map();
        BoxCloneService::new(InjectAnnotations::new(router, annotations))
    })
}

/// A service wrapper that injects [`ToolAnnotationsMap`] into request
/// extensions for `tools/call` requests.
///
/// This allows middleware to inspect tool annotations (e.g., `read_only_hint`,
/// `destructive_hint`) without needing direct access to the router.
/// Transports apply this wrapper automatically.
#[derive(Clone)]
pub struct InjectAnnotations<S> {
    inner: S,
    annotations: ToolAnnotationsMap,
}

impl<S> InjectAnnotations<S> {
    /// Create a new `InjectAnnotations` wrapping the given service.
    pub fn new(inner: S, annotations: ToolAnnotationsMap) -> Self {
        Self { inner, annotations }
    }
}

impl<S: fmt::Debug> fmt::Debug for InjectAnnotations<S> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("InjectAnnotations")
            .field("inner", &self.inner)
            .finish()
    }
}

impl<S> Service<RouterRequest> for InjectAnnotations<S>
where
    S: Service<RouterRequest, Response = RouterResponse>,
{
    type Response = RouterResponse;
    type Error = S::Error;
    type Future = S::Future;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, mut req: RouterRequest) -> Self::Future {
        if matches!(&req.inner, McpRequest::CallTool(_)) {
            req.extensions.insert(self.annotations.clone());
        }
        self.inner.call(req)
    }
}

/// A service wrapper that catches errors from middleware and converts them
/// into [`RouterResponse`] error values, maintaining the `Error = Infallible`
/// contract required by [`JsonRpcService`](crate::jsonrpc::JsonRpcService).
///
/// When a middleware layer (e.g., `TimeoutLayer`) produces an error, this
/// wrapper converts it into a JSON-RPC internal error response using the
/// request ID from the original request. This allows error information to
/// flow through the normal response path rather than requiring special
/// error handling at the transport level.
pub struct CatchError<S> {
    inner: S,
}

impl<S> CatchError<S> {
    /// Create a new `CatchError` wrapping the given service.
    pub fn new(inner: S) -> Self {
        Self { inner }
    }
}

impl<S: Clone> Clone for CatchError<S> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
        }
    }
}

impl<S: fmt::Debug> fmt::Debug for CatchError<S> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CatchError")
            .field("inner", &self.inner)
            .finish()
    }
}

pin_project! {
    /// Future for [`CatchError`].
    pub struct CatchErrorFuture<F> {
        #[pin]
        inner: F,
        request_id: Option<RequestId>,
    }
}

impl<F, E> Future for CatchErrorFuture<F>
where
    F: Future<Output = Result<RouterResponse, E>>,
    E: fmt::Display,
{
    type Output = Result<RouterResponse, Infallible>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = self.project();
        match this.inner.poll(cx) {
            Poll::Pending => Poll::Pending,
            Poll::Ready(Ok(response)) => Poll::Ready(Ok(response)),
            Poll::Ready(Err(err)) => {
                let request_id = this.request_id.take().unwrap_or(RequestId::Number(0));
                Poll::Ready(Ok(RouterResponse {
                    id: request_id,
                    inner: Err(JsonRpcError::internal_error(err.to_string())),
                }))
            }
        }
    }
}

impl<S> Service<RouterRequest> for CatchError<S>
where
    S: Service<RouterRequest, Response = RouterResponse> + Clone + Send + 'static,
    S::Error: fmt::Display + Send,
    S::Future: Send,
{
    type Response = RouterResponse;
    type Error = Infallible;
    type Future = CatchErrorFuture<S::Future>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx).map_err(|_| unreachable!())
    }

    fn call(&mut self, req: RouterRequest) -> Self::Future {
        // Capture the request ID before passing the request to the inner service.
        // We need this to build a proper JSON-RPC error response if the middleware fails.
        let request_id = req.id.clone();
        let fut = self.inner.call(req);

        CatchErrorFuture {
            inner: fut,
            request_id: Some(request_id),
        }
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use super::*;
    use crate::protocol::{CallToolParams, CallToolResult, RequestId, ToolAnnotations};
    use crate::router::McpRouter;

    #[test]
    #[cfg(any(feature = "http", feature = "websocket"))]
    fn test_identity_factory_produces_service() {
        let router = McpRouter::new().server_info("test", "1.0.0");
        let factory = identity_factory();
        let _service = factory(router);
    }

    #[tokio::test]
    async fn test_catch_error_passes_through_success() {
        let router = McpRouter::new().server_info("test", "1.0.0");
        let mut service = CatchError::new(router);

        let req = RouterRequest {
            id: RequestId::Number(1),
            inner: crate::protocol::McpRequest::Ping,
            extensions: crate::router::Extensions::new(),
        };

        let result = Service::call(&mut service, req).await;
        assert!(result.is_ok());
        let response = result.unwrap();
        assert!(response.inner.is_ok());
    }

    #[test]
    fn test_catch_error_clone() {
        let router = McpRouter::new().server_info("test", "1.0.0");
        let service = CatchError::new(router);
        let _clone = service.clone();
    }

    #[test]
    fn test_catch_error_debug() {
        let router = McpRouter::new().server_info("test", "1.0.0");
        let service = CatchError::new(router);
        let debug = format!("{:?}", service);
        assert!(debug.contains("CatchError"));
    }

    #[tokio::test]
    async fn test_inject_annotations_for_call_tool() {
        use crate::{CallToolResult, ToolBuilder};

        let tool = ToolBuilder::new("read_data")
            .description("Read some data")
            .annotations(ToolAnnotations {
                read_only_hint: true,
                destructive_hint: false,
                ..Default::default()
            })
            .handler(|_: serde_json::Value| async move { Ok(CallToolResult::text("ok")) })
            .build();

        let router = McpRouter::new().server_info("test", "1.0.0").tool(tool);
        let annotations = router.tool_annotations_map();
        let mut service = InjectAnnotations::new(router, annotations);

        let req = RouterRequest {
            id: RequestId::Number(1),
            inner: McpRequest::CallTool(CallToolParams {
                name: "read_data".to_string(),
                arguments: serde_json::json!({}),
                meta: None,
                task: None,
            }),
            extensions: crate::router::Extensions::new(),
        };

        // Verify the service processes the request (we can't inspect extensions
        // after call, but we test the map is built correctly below)
        let result = Service::call(&mut service, req).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_inject_annotations_skips_non_call_tool() {
        let router = McpRouter::new().server_info("test", "1.0.0");
        let annotations = router.tool_annotations_map();
        let mut service = InjectAnnotations::new(router, annotations);

        let req = RouterRequest {
            id: RequestId::Number(1),
            inner: McpRequest::Ping,
            extensions: crate::router::Extensions::new(),
        };

        let result = Service::call(&mut service, req).await;
        assert!(result.is_ok());
    }

    #[test]
    fn test_tool_annotations_map_methods() {
        use crate::ToolBuilder;

        let read_tool = ToolBuilder::new("reader")
            .description("Read-only tool")
            .annotations(ToolAnnotations {
                read_only_hint: true,
                destructive_hint: false,
                idempotent_hint: true,
                ..Default::default()
            })
            .handler(|_: serde_json::Value| async move { Ok(CallToolResult::text("ok")) })
            .build();

        let write_tool = ToolBuilder::new("writer")
            .description("Destructive tool")
            .annotations(ToolAnnotations {
                read_only_hint: false,
                destructive_hint: true,
                idempotent_hint: false,
                ..Default::default()
            })
            .handler(|_: serde_json::Value| async move { Ok(CallToolResult::text("ok")) })
            .build();

        let plain_tool = ToolBuilder::new("plain")
            .description("No annotations")
            .handler(|_: serde_json::Value| async move { Ok(CallToolResult::text("ok")) })
            .build();

        let router = McpRouter::new()
            .server_info("test", "1.0.0")
            .tool(read_tool)
            .tool(write_tool)
            .tool(plain_tool);

        let map = router.tool_annotations_map();

        // read-only tool
        assert!(map.is_read_only("reader"));
        assert!(!map.is_destructive("reader"));
        assert!(map.is_idempotent("reader"));

        // destructive tool
        assert!(!map.is_read_only("writer"));
        assert!(map.is_destructive("writer"));
        assert!(!map.is_idempotent("writer"));

        // tool without annotations: not in map, defaults apply
        assert!(!map.is_read_only("plain"));
        assert!(map.is_destructive("plain")); // default is true
        assert!(!map.is_idempotent("plain"));

        // nonexistent tool: same defaults as no annotations
        assert!(!map.is_read_only("nonexistent"));
        assert!(map.is_destructive("nonexistent"));
        assert!(!map.is_idempotent("nonexistent"));

        // get() returns None for plain and nonexistent
        assert!(map.get("reader").is_some());
        assert!(map.get("writer").is_some());
        assert!(map.get("plain").is_none());
        assert!(map.get("nonexistent").is_none());
    }

    #[tokio::test]
    async fn test_annotations_visible_in_middleware() {
        use crate::ToolBuilder;
        use crate::router::ToolAnnotationsMap;
        use std::sync::atomic::{AtomicBool, Ordering};

        // A minimal middleware that checks for annotations in extensions.
        #[derive(Clone)]
        struct CheckAnnotations<S> {
            inner: S,
            found: Arc<AtomicBool>,
        }

        impl<S> Service<RouterRequest> for CheckAnnotations<S>
        where
            S: Service<RouterRequest, Response = RouterResponse, Error = Infallible>,
        {
            type Response = RouterResponse;
            type Error = Infallible;
            type Future = S::Future;

            fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
                self.inner.poll_ready(cx)
            }

            fn call(&mut self, req: RouterRequest) -> Self::Future {
                if let Some(map) = req.extensions.get::<ToolAnnotationsMap>()
                    && map.is_read_only("reader")
                {
                    self.found.store(true, Ordering::SeqCst);
                }
                self.inner.call(req)
            }
        }

        let tool = ToolBuilder::new("reader")
            .description("A read-only tool")
            .annotations(ToolAnnotations {
                read_only_hint: true,
                ..Default::default()
            })
            .handler(|_: serde_json::Value| async move { Ok(CallToolResult::text("ok")) })
            .build();

        let router = McpRouter::new().server_info("test", "1.0.0").tool(tool);
        let annotations = router.tool_annotations_map();
        let found = Arc::new(AtomicBool::new(false));

        // InjectAnnotations is outer (runs first, injects into extensions),
        // then CheckAnnotations sees the enriched request.
        let inner = CheckAnnotations {
            inner: router,
            found: found.clone(),
        };
        let mut service = InjectAnnotations::new(inner, annotations);

        let req = RouterRequest {
            id: RequestId::Number(1),
            inner: McpRequest::CallTool(CallToolParams {
                name: "reader".to_string(),
                arguments: serde_json::json!({}),
                meta: None,
                task: None,
            }),
            extensions: crate::router::Extensions::new(),
        };

        let result = Service::call(&mut service, req).await;
        assert!(result.is_ok());
        assert!(
            found.load(Ordering::SeqCst),
            "Middleware should see annotations in extensions"
        );
    }
}