turul-http-mcp-server 0.3.33

HTTP transport layer for Model Context Protocol (MCP) servers
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
//! Middleware stack execution

use super::{DispatcherResult, McpMiddleware, MiddlewareError, RequestContext, SessionInjection};
use std::sync::Arc;
use turul_mcp_session_storage::SessionView;

/// Ordered collection of middleware with execution logic
///
/// The stack executes middleware in two phases:
///
/// 1. **Before dispatch**: Middleware execute in registration order
///    - First error stops the chain
///    - Session injections accumulate across all middleware
///
/// 2. **After dispatch**: Middleware execute in reverse registration order
///    - Allows proper cleanup/finalization
///    - Errors replace the result
///
/// # Examples
///
/// ```rust,no_run
/// use turul_http_mcp_server::middleware::{MiddlewareStack, McpMiddleware, RequestContext, SessionInjection, MiddlewareError};
/// use turul_mcp_session_storage::SessionView;
/// use async_trait::async_trait;
/// use std::sync::Arc;
///
/// struct LoggingMiddleware;
///
/// #[async_trait]
/// impl McpMiddleware for LoggingMiddleware {
///     async fn before_dispatch(
///         &self,
///         ctx: &mut RequestContext<'_>,
///         _session: Option<&dyn SessionView>,
///         _injection: &mut SessionInjection,
///     ) -> Result<(), MiddlewareError> {
///         println!("Request: {}", ctx.method());
///         Ok(())
///     }
/// }
///
/// # async fn example() {
/// let mut stack = MiddlewareStack::new();
/// stack.push(Arc::new(LoggingMiddleware));
///
/// assert_eq!(stack.len(), 1);
/// # }
/// ```
#[derive(Default, Clone)]
pub struct MiddlewareStack {
    middleware: Vec<Arc<dyn McpMiddleware>>,
}

impl MiddlewareStack {
    /// Create an empty middleware stack
    pub fn new() -> Self {
        Self::default()
    }

    /// Add middleware to the end of the stack
    ///
    /// # Parameters
    ///
    /// - `middleware`: Middleware implementation (must be Arc-wrapped for sharing)
    ///
    /// # Execution Order
    ///
    /// - Before dispatch: First added executes first
    /// - After dispatch: First added executes last (reverse order)
    pub fn push(&mut self, middleware: Arc<dyn McpMiddleware>) {
        self.middleware.push(middleware);
    }

    /// Get the number of middleware in the stack
    pub fn len(&self) -> usize {
        self.middleware.len()
    }

    /// Check if the stack is empty
    pub fn is_empty(&self) -> bool {
        self.middleware.is_empty()
    }

    /// Check if any middleware in the stack runs before session creation
    pub fn has_pre_session_middleware(&self) -> bool {
        self.middleware.iter().any(|m| m.runs_before_session())
    }

    /// Execute only pre-session middleware (those with `runs_before_session() == true`)
    ///
    /// Called by the transport layer before session lookup/creation.
    /// Session is always `None` in this phase.
    pub async fn execute_before_session(
        &self,
        ctx: &mut RequestContext<'_>,
    ) -> Result<(), MiddlewareError> {
        for middleware in &self.middleware {
            if middleware.runs_before_session() {
                let mut injection = SessionInjection::new();
                middleware
                    .before_dispatch(ctx, None, &mut injection)
                    .await?;
                // Pre-session injections are intentionally discarded —
                // session doesn't exist yet. Use ctx.extensions instead.
            }
        }
        Ok(())
    }

    /// Execute all middleware before dispatch
    ///
    /// # Parameters
    ///
    /// - `ctx`: Mutable request context
    /// - `session`: Optional read-only session view
    ///   - `None` for `initialize` (session doesn't exist yet)
    ///   - `Some(session)` for all other methods
    ///
    /// # Returns
    ///
    /// - `Ok(SessionInjection)`: All middleware succeeded, contains accumulated injections
    /// - `Err(MiddlewareError)`: First middleware that failed
    ///
    /// # Execution
    ///
    /// 1. Execute each middleware in registration order
    /// 2. Accumulate session injections from all middleware
    /// 3. Stop on first error
    pub async fn execute_before(
        &self,
        ctx: &mut RequestContext<'_>,
        session: Option<&dyn SessionView>,
    ) -> Result<SessionInjection, MiddlewareError> {
        let mut combined_injection = SessionInjection::new();

        for middleware in &self.middleware {
            // Skip pre-session middleware — they already ran in execute_before_session()
            if middleware.runs_before_session() {
                continue;
            }

            let mut injection = SessionInjection::new();
            middleware
                .before_dispatch(ctx, session, &mut injection)
                .await?;

            // Accumulate injections (later middleware can override earlier ones)
            for (key, value) in injection.state() {
                combined_injection.set_state(key.clone(), value.clone());
            }
            for (key, value) in injection.metadata() {
                combined_injection.set_metadata(key.clone(), value.clone());
            }
        }

        Ok(combined_injection)
    }

    /// Execute all middleware after dispatch
    ///
    /// # Parameters
    ///
    /// - `ctx`: Read-only request context
    /// - `result`: Mutable dispatcher result
    ///
    /// # Returns
    ///
    /// - `Ok(())`: All middleware succeeded
    /// - `Err(MiddlewareError)`: First middleware that failed
    ///
    /// # Execution
    ///
    /// 1. Execute each middleware in reverse registration order
    /// 2. Stop on first error
    /// 3. Allow middleware to modify result
    pub async fn execute_after(
        &self,
        ctx: &RequestContext<'_>,
        result: &mut DispatcherResult,
    ) -> Result<(), MiddlewareError> {
        // Execute in reverse order
        for middleware in self.middleware.iter().rev() {
            middleware.after_dispatch(ctx, result).await?;
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use async_trait::async_trait;
    use serde_json::json;

    struct CountingMiddleware {
        id: String,
        counter: Arc<std::sync::Mutex<Vec<String>>>,
    }

    #[async_trait]
    impl McpMiddleware for CountingMiddleware {
        async fn before_dispatch(
            &self,
            _ctx: &mut RequestContext<'_>,
            _session: Option<&dyn SessionView>,
            injection: &mut SessionInjection,
        ) -> Result<(), MiddlewareError> {
            self.counter
                .lock()
                .unwrap()
                .push(format!("before_{}", self.id));
            injection.set_state(&self.id, json!(true));
            Ok(())
        }

        async fn after_dispatch(
            &self,
            _ctx: &RequestContext<'_>,
            _result: &mut DispatcherResult,
        ) -> Result<(), MiddlewareError> {
            self.counter
                .lock()
                .unwrap()
                .push(format!("after_{}", self.id));
            Ok(())
        }
    }

    struct ErrorMiddleware {
        error_on_before: bool,
    }

    #[async_trait]
    impl McpMiddleware for ErrorMiddleware {
        async fn before_dispatch(
            &self,
            _ctx: &mut RequestContext<'_>,
            _session: Option<&dyn SessionView>,
            _injection: &mut SessionInjection,
        ) -> Result<(), MiddlewareError> {
            if self.error_on_before {
                Err(MiddlewareError::unauthorized("Test error"))
            } else {
                Ok(())
            }
        }
    }

    #[tokio::test]
    async fn test_middleware_execution_order() {
        let counter = Arc::new(std::sync::Mutex::new(Vec::new()));
        let mut stack = MiddlewareStack::new();

        stack.push(Arc::new(CountingMiddleware {
            id: "first".to_string(),
            counter: counter.clone(),
        }));
        stack.push(Arc::new(CountingMiddleware {
            id: "second".to_string(),
            counter: counter.clone(),
        }));

        let mut ctx = RequestContext::new("test/method", None);

        // Execute before (no session needed for this test)
        let injection = stack.execute_before(&mut ctx, None).await.unwrap();
        assert_eq!(injection.state().len(), 2);
        assert!(injection.state().contains_key("first"));
        assert!(injection.state().contains_key("second"));

        // Execute after
        let mut result = DispatcherResult::Success(json!({"ok": true}));
        stack.execute_after(&ctx, &mut result).await.unwrap();

        // Verify order: before in normal order, after in reverse
        let log = counter.lock().unwrap();
        assert_eq!(log[0], "before_first");
        assert_eq!(log[1], "before_second");
        assert_eq!(log[2], "after_second"); // Reverse order
        assert_eq!(log[3], "after_first");
    }

    #[tokio::test]
    async fn test_middleware_error_stops_chain() {
        let counter = Arc::new(std::sync::Mutex::new(Vec::new()));
        let mut stack = MiddlewareStack::new();

        stack.push(Arc::new(CountingMiddleware {
            id: "first".to_string(),
            counter: counter.clone(),
        }));
        stack.push(Arc::new(ErrorMiddleware {
            error_on_before: true,
        }));
        stack.push(Arc::new(CountingMiddleware {
            id: "third".to_string(),
            counter: counter.clone(),
        }));

        let mut ctx = RequestContext::new("test/method", None);

        // Execute before - should fail at second middleware (no session needed)
        let result = stack.execute_before(&mut ctx, None).await;
        assert!(result.is_err());
        assert_eq!(
            result.unwrap_err(),
            MiddlewareError::unauthorized("Test error")
        );

        // Verify only first middleware executed
        let log = counter.lock().unwrap();
        assert_eq!(log.len(), 1);
        assert_eq!(log[0], "before_first");
    }

    /// Middleware that filters tools from the response
    struct ToolFilteringMiddleware;

    #[async_trait]
    impl McpMiddleware for ToolFilteringMiddleware {
        async fn before_dispatch(
            &self,
            _ctx: &mut RequestContext<'_>,
            _session: Option<&dyn SessionView>,
            _injection: &mut SessionInjection,
        ) -> Result<(), MiddlewareError> {
            Ok(())
        }

        async fn after_dispatch(
            &self,
            _ctx: &RequestContext<'_>,
            result: &mut DispatcherResult,
        ) -> Result<(), MiddlewareError> {
            if let DispatcherResult::Success(val) = result {
                if let Some(tools) = val.get_mut("tools") {
                    if let Some(arr) = tools.as_array_mut() {
                        arr.retain(|t| t["name"] != "secret_tool");
                    }
                }
            }
            Ok(())
        }
    }

    #[tokio::test]
    async fn test_after_dispatch_success_mutation_visible() {
        let mut stack = MiddlewareStack::new();
        stack.push(Arc::new(ToolFilteringMiddleware));

        let ctx = RequestContext::new("tools/list", None);
        let mut result = DispatcherResult::Success(json!({
            "tools": [
                {"name": "public_tool"},
                {"name": "secret_tool"},
                {"name": "another_tool"}
            ]
        }));

        stack.execute_after(&ctx, &mut result).await.unwrap();

        let val = result.success().unwrap();
        let tools = val["tools"].as_array().unwrap();
        assert_eq!(tools.len(), 2);
        assert!(tools.iter().all(|t| t["name"] != "secret_tool"));
    }

    #[tokio::test]
    async fn test_after_dispatch_success_to_error_mutation_visible() {
        struct RejectingMiddleware;

        #[async_trait]
        impl McpMiddleware for RejectingMiddleware {
            async fn before_dispatch(
                &self,
                _ctx: &mut RequestContext<'_>,
                _session: Option<&dyn SessionView>,
                _injection: &mut SessionInjection,
            ) -> Result<(), MiddlewareError> {
                Ok(())
            }

            async fn after_dispatch(
                &self,
                _ctx: &RequestContext<'_>,
                result: &mut DispatcherResult,
            ) -> Result<(), MiddlewareError> {
                if result.is_success() {
                    *result = DispatcherResult::Error("rejected by policy".to_string());
                }
                Ok(())
            }
        }

        let mut stack = MiddlewareStack::new();
        stack.push(Arc::new(RejectingMiddleware));

        let ctx = RequestContext::new("tools/list", None);
        let mut result = DispatcherResult::Success(json!({"tools": []}));

        stack.execute_after(&ctx, &mut result).await.unwrap();

        assert!(result.is_error());
        assert_eq!(result.error().unwrap(), "rejected by policy");
    }

    #[tokio::test]
    async fn test_empty_stack() {
        let stack = MiddlewareStack::new();
        assert!(stack.is_empty());
        assert_eq!(stack.len(), 0);

        let mut ctx = RequestContext::new("test/method", None);

        let injection = stack.execute_before(&mut ctx, None).await.unwrap();
        assert!(injection.is_empty());

        let mut result = DispatcherResult::Success(json!({"ok": true}));
        stack.execute_after(&ctx, &mut result).await.unwrap();
    }
}