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
//! Tool call audit logging middleware.
//!
//! This module provides [`ToolCallLoggingLayer`], a Tower middleware that emits
//! structured [`tracing`] events specifically for `tools/call` requests. Unlike
//! [`McpTracingLayer`](super::McpTracingLayer) which traces all MCP requests,
//! this layer focuses on tool invocations and provides richer audit information.
//!
//! Note: [`McpRouter`](crate::McpRouter) now emits basic tool call logging
//! (tool name, duration, status) by default at `INFO` level on the `mcp::tools`
//! target. Use this layer when you need additional detail such as annotation
//! hints (`read_only`, `destructive`) or a custom log level.
//!
//! # Logged Information
//!
//! For each tool call, the layer emits a single event after completion with:
//! - **tool**: The tool name
//! - **duration_ms**: Execution time in milliseconds
//! - **status**: One of `"success"`, `"error"`, or `"denied"`
//! - **error_code** / **error_message**: Present on error responses
//!
//! All events use tracing target `mcp::tools` for easy filtering.
//! Non-`CallTool` requests pass through unchanged with no overhead.
//!
//! # Example
//!
//! ```rust,ignore
//! use tower_mcp::{McpRouter, StdioTransport};
//! use tower_mcp::middleware::ToolCallLoggingLayer;
//!
//! let router = McpRouter::new().server_info("my-server", "1.0.0");
//!
//! let mut transport = StdioTransport::new(router)
//!     .layer(ToolCallLoggingLayer::new());
//! ```

use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Instant;

use tower::Layer;
use tower_service::Service;
use tracing::Level;

use crate::protocol::McpRequest;
use crate::router::{RouterRequest, RouterResponse, ToolAnnotationsMap};

/// JSON-RPC error code for "invalid params", which may indicate a denied tool call.
const JSONRPC_INVALID_PARAMS: i32 = -32602;

/// Tower layer that adds audit logging for tool call requests.
///
/// This layer intercepts `tools/call` requests and emits structured
/// [`tracing`] events with the tool name, execution duration, and result
/// status. Non-tool-call requests pass through with zero overhead.
///
/// Events are emitted with tracing target `mcp::tools`, which can be used
/// for filtering in your tracing subscriber configuration.
///
/// # Example
///
/// ```rust,ignore
/// use tower_mcp::{McpRouter, StdioTransport};
/// use tower_mcp::middleware::ToolCallLoggingLayer;
///
/// let router = McpRouter::new().server_info("my-server", "1.0.0");
///
/// let mut transport = StdioTransport::new(router)
///     .layer(ToolCallLoggingLayer::new());
/// ```
#[derive(Debug, Clone, Copy)]
pub struct ToolCallLoggingLayer {
    level: Level,
}

impl Default for ToolCallLoggingLayer {
    fn default() -> Self {
        Self::new()
    }
}

impl ToolCallLoggingLayer {
    /// Create a new tool call logging layer with default settings (INFO level).
    pub fn new() -> Self {
        Self { level: Level::INFO }
    }

    /// Set the log level for tool call events.
    ///
    /// Default is `INFO`.
    pub fn level(mut self, level: Level) -> Self {
        self.level = level;
        self
    }
}

impl<S> Layer<S> for ToolCallLoggingLayer {
    type Service = ToolCallLoggingService<S>;

    fn layer(&self, inner: S) -> Self::Service {
        ToolCallLoggingService {
            inner,
            level: self.level,
        }
    }
}

/// Tower service that logs tool call requests.
///
/// Created by [`ToolCallLoggingLayer`]. See the layer documentation for details.
#[derive(Debug, Clone)]
pub struct ToolCallLoggingService<S> {
    inner: S,
    level: Level,
}

impl<S> Service<RouterRequest> for ToolCallLoggingService<S>
where
    S: Service<RouterRequest, Response = RouterResponse> + Clone + Send + 'static,
    S::Error: Send,
    S::Future: Send,
{
    type Response = RouterResponse;
    type Error = S::Error;
    type Future = Pin<Box<dyn Future<Output = Result<RouterResponse, S::Error>> + Send>>;

    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 {
        // Only intercept CallTool requests; pass everything else through directly.
        let tool_name = match &req.inner {
            McpRequest::CallTool(params) => params.name.clone(),
            _ => {
                let fut = self.inner.call(req);
                return Box::pin(fut);
            }
        };

        // Extract annotation hints if the transport injected them.
        let read_only = req
            .extensions
            .get::<ToolAnnotationsMap>()
            .map(|m| m.is_read_only(&tool_name));
        let destructive = req
            .extensions
            .get::<ToolAnnotationsMap>()
            .map(|m| m.is_destructive(&tool_name));

        let start = Instant::now();
        let fut = self.inner.call(req);
        let level = self.level;

        Box::pin(async move {
            let result = fut.await;
            let duration_ms = start.elapsed().as_secs_f64() * 1000.0;

            if let Ok(response) = &result {
                match &response.inner {
                    Ok(_) => {
                        log_tool_call(
                            level,
                            &tool_name,
                            duration_ms,
                            "success",
                            None,
                            read_only,
                            destructive,
                        );
                    }
                    Err(err) => {
                        let status = if err.code == JSONRPC_INVALID_PARAMS {
                            "denied"
                        } else {
                            "error"
                        };
                        log_tool_call(
                            level,
                            &tool_name,
                            duration_ms,
                            status,
                            Some((err.code, &err.message)),
                            read_only,
                            destructive,
                        );
                    }
                }
            }

            result
        })
    }
}

/// Emit a structured tracing event for a tool call.
fn log_tool_call(
    level: Level,
    tool: &str,
    duration_ms: f64,
    status: &str,
    error: Option<(i32, &str)>,
    read_only: Option<bool>,
    destructive: Option<bool>,
) {
    match (level, error) {
        (Level::TRACE, None) => {
            tracing::trace!(target: "mcp::tools", tool, duration_ms, status, ?read_only, ?destructive, "tool call completed")
        }
        (Level::TRACE, Some((code, message))) => {
            tracing::trace!(target: "mcp::tools", tool, duration_ms, status, error_code = code, error_message = message, ?read_only, ?destructive, "tool call completed")
        }
        (Level::DEBUG, None) => {
            tracing::debug!(target: "mcp::tools", tool, duration_ms, status, ?read_only, ?destructive, "tool call completed")
        }
        (Level::DEBUG, Some((code, message))) => {
            tracing::debug!(target: "mcp::tools", tool, duration_ms, status, error_code = code, error_message = message, ?read_only, ?destructive, "tool call completed")
        }
        (Level::INFO, None) => {
            tracing::info!(target: "mcp::tools", tool, duration_ms, status, ?read_only, ?destructive, "tool call completed")
        }
        (Level::INFO, Some((code, message))) => {
            tracing::info!(target: "mcp::tools", tool, duration_ms, status, error_code = code, error_message = message, ?read_only, ?destructive, "tool call completed")
        }
        (Level::WARN, None) => {
            tracing::warn!(target: "mcp::tools", tool, duration_ms, status, ?read_only, ?destructive, "tool call completed")
        }
        (Level::WARN, Some((code, message))) => {
            tracing::warn!(target: "mcp::tools", tool, duration_ms, status, error_code = code, error_message = message, ?read_only, ?destructive, "tool call completed")
        }
        (Level::ERROR, None) => {
            tracing::error!(target: "mcp::tools", tool, duration_ms, status, ?read_only, ?destructive, "tool call completed")
        }
        (Level::ERROR, Some((code, message))) => {
            tracing::error!(target: "mcp::tools", tool, duration_ms, status, error_code = code, error_message = message, ?read_only, ?destructive, "tool call completed")
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::protocol::{CallToolParams, RequestId};
    use crate::router::Extensions;

    #[test]
    fn test_layer_creation() {
        let layer = ToolCallLoggingLayer::new();
        assert_eq!(layer.level, Level::INFO);
    }

    #[test]
    fn test_layer_with_custom_level() {
        let layer = ToolCallLoggingLayer::new().level(Level::DEBUG);
        assert_eq!(layer.level, Level::DEBUG);
    }

    #[test]
    fn test_layer_default() {
        let layer = ToolCallLoggingLayer::default();
        assert_eq!(layer.level, Level::INFO);
    }

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

        // Ping request should pass through without tool call logging
        let req = RouterRequest {
            id: RequestId::Number(1),
            inner: McpRequest::Ping,
            extensions: Extensions::new(),
        };

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

    #[tokio::test]
    async fn test_tool_call_logging() {
        let tool = crate::ToolBuilder::new("test_tool")
            .description("A test tool")
            .handler(|_: serde_json::Value| async move { Ok(crate::CallToolResult::text("done")) })
            .build();

        let router = crate::McpRouter::new()
            .server_info("test", "1.0.0")
            .tool(tool);
        let layer = ToolCallLoggingLayer::new();
        let mut service = layer.layer(router);

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

        // The service should process the request and return a response.
        // The inner result may be an error (session not initialized) but
        // the logging layer should handle it either way.
        let result = Service::call(&mut service, req).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_tool_call_error_logging() {
        // Call a tool that doesn't exist to get an error response
        let router = crate::McpRouter::new().server_info("test", "1.0.0");
        let layer = ToolCallLoggingLayer::new();
        let mut service = layer.layer(router);

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

        let result = Service::call(&mut service, req).await;
        assert!(result.is_ok());
        // The response should be an error (tool not found)
        assert!(result.unwrap().inner.is_err());
    }

    #[tokio::test]
    async fn test_list_tools_passthrough() {
        use crate::protocol::ListToolsParams;

        let router = crate::McpRouter::new().server_info("test", "1.0.0");
        let layer = ToolCallLoggingLayer::new();
        let mut service = layer.layer(router);

        // ListTools should pass through without tool call logging
        let req = RouterRequest {
            id: RequestId::Number(1),
            inner: McpRequest::ListTools(ListToolsParams {
                cursor: None,
                meta: None,
            }),
            extensions: Extensions::new(),
        };

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

    #[tokio::test]
    async fn test_tool_call_success_response() {
        let tool = crate::ToolBuilder::new("add")
            .description("Add numbers")
            .handler(|_: serde_json::Value| async move { Ok(crate::CallToolResult::text("42")) })
            .build();

        let mut router = crate::McpRouter::new()
            .server_info("test", "1.0.0")
            .tool(tool);

        // Manually initialize the session so tool calls work
        use crate::router::RouterRequest;
        use tower_service::Service;

        let init_req = RouterRequest {
            id: RequestId::Number(0),
            inner: McpRequest::Initialize(crate::protocol::InitializeParams {
                protocol_version: "2025-11-25".to_string(),
                capabilities: crate::protocol::ClientCapabilities::default(),
                client_info: crate::protocol::Implementation {
                    name: "test".to_string(),
                    version: "1.0".to_string(),
                    ..Default::default()
                },
                meta: None,
            }),
            extensions: Extensions::new(),
        };
        let _ = Service::call(&mut router, init_req).await;

        // Now send initialized notification to transition session state
        // (handled internally by the router)

        let layer = ToolCallLoggingLayer::new();
        let mut service = layer.layer(router);

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

        let result = Service::call(&mut service, req).await;
        assert!(result.is_ok());
        let response = result.unwrap();
        // After initialization, tool calls should succeed
        assert!(response.inner.is_ok());
    }

    #[tokio::test]
    async fn test_resource_read_passthrough() {
        use crate::protocol::ReadResourceParams;

        let router = crate::McpRouter::new().server_info("test", "1.0.0");
        let layer = ToolCallLoggingLayer::new();
        let mut service = layer.layer(router);

        let req = RouterRequest {
            id: RequestId::Number(1),
            inner: McpRequest::ReadResource(ReadResourceParams {
                uri: "file:///test".to_string(),
                meta: None,
            }),
            extensions: Extensions::new(),
        };

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

    #[test]
    fn test_layer_copy() {
        let layer = ToolCallLoggingLayer::new().level(Level::DEBUG);
        let copied = layer; // Copy, not clone
        assert_eq!(copied.level, Level::DEBUG);
        // Original is still usable (Copy)
        assert_eq!(layer.level, Level::DEBUG);
    }
}