Skip to main content

turul_http_mcp_server/middleware/
stack.rs

1//! Middleware stack execution
2
3use super::{DispatcherResult, McpMiddleware, MiddlewareError, RequestContext, SessionInjection};
4use std::sync::Arc;
5use turul_mcp_session_storage::SessionView;
6
7/// Ordered collection of middleware with execution logic.
8///
9/// The stack executes middleware in two phases:
10///
11/// 1. **Before dispatch**: Middleware execute in registration order
12///    - First error stops the chain
13///    - Session injections accumulate across all middleware
14///
15/// 2. **After dispatch**: Middleware execute in reverse registration order
16///    - Allows proper cleanup/finalization
17///    - Errors replace the result
18///
19/// # Examples
20///
21/// ```rust,no_run
22/// use turul_http_mcp_server::middleware::{MiddlewareStack, McpMiddleware, RequestContext, SessionInjection, MiddlewareError};
23/// use turul_mcp_session_storage::SessionView;
24/// use async_trait::async_trait;
25/// use std::sync::Arc;
26///
27/// struct LoggingMiddleware;
28///
29/// #[async_trait]
30/// impl McpMiddleware for LoggingMiddleware {
31///     async fn before_dispatch(
32///         &self,
33///         ctx: &mut RequestContext<'_>,
34///         _session: Option<&dyn SessionView>,
35///         _injection: &mut SessionInjection,
36///     ) -> Result<(), MiddlewareError> {
37///         println!("Request: {}", ctx.method());
38///         Ok(())
39///     }
40/// }
41///
42/// # async fn example() {
43/// let mut stack = MiddlewareStack::new();
44/// stack.push(Arc::new(LoggingMiddleware));
45///
46/// assert_eq!(stack.len(), 1);
47/// # }
48/// ```
49#[derive(Default, Clone)]
50pub struct MiddlewareStack {
51    middleware: Vec<Arc<dyn McpMiddleware>>,
52}
53
54impl MiddlewareStack {
55    /// Creates an empty middleware stack.
56    pub fn new() -> Self {
57        Self::default()
58    }
59
60    /// Adds middleware to the end of the stack.
61    ///
62    /// # Parameters
63    ///
64    /// - `middleware`: Middleware implementation (must be Arc-wrapped for sharing)
65    ///
66    /// # Execution Order
67    ///
68    /// - Before dispatch: First added executes first
69    /// - After dispatch: First added executes last (reverse order)
70    pub fn push(&mut self, middleware: Arc<dyn McpMiddleware>) {
71        self.middleware.push(middleware);
72    }
73
74    /// Returns the number of middleware in the stack.
75    pub fn len(&self) -> usize {
76        self.middleware.len()
77    }
78
79    /// Returns whether the stack is empty.
80    pub fn is_empty(&self) -> bool {
81        self.middleware.is_empty()
82    }
83
84    /// Returns whether any middleware in the stack runs before session creation.
85    pub fn has_pre_session_middleware(&self) -> bool {
86        self.middleware.iter().any(|m| m.runs_before_session())
87    }
88
89    /// Executes only pre-session middleware (those with `runs_before_session() == true`).
90    ///
91    /// Called by the transport layer before session lookup/creation.
92    /// The session is always `None` in this phase.
93    pub async fn execute_before_session(
94        &self,
95        ctx: &mut RequestContext<'_>,
96    ) -> Result<(), MiddlewareError> {
97        for middleware in &self.middleware {
98            if middleware.runs_before_session() {
99                let mut injection = SessionInjection::new();
100                middleware
101                    .before_dispatch(ctx, None, &mut injection)
102                    .await?;
103                // Pre-session injections are intentionally discarded —
104                // session doesn't exist yet. Use ctx.extensions instead.
105            }
106        }
107        Ok(())
108    }
109
110    /// Executes all post-session middleware before dispatch.
111    ///
112    /// # Parameters
113    ///
114    /// - `ctx`: Mutable request context
115    /// - `session`: Optional read-only session view
116    ///   - `None` for `initialize` (session doesn't exist yet)
117    ///   - `Some(session)` for all other methods
118    ///
119    /// # Returns
120    ///
121    /// - `Ok(SessionInjection)`: All middleware succeeded, contains accumulated injections
122    /// - `Err(MiddlewareError)`: First middleware that failed
123    ///
124    /// # Execution
125    ///
126    /// 1. Execute each middleware in registration order
127    /// 2. Accumulate session injections from all middleware
128    /// 3. Stop on first error
129    pub async fn execute_before(
130        &self,
131        ctx: &mut RequestContext<'_>,
132        session: Option<&dyn SessionView>,
133    ) -> Result<SessionInjection, MiddlewareError> {
134        let mut combined_injection = SessionInjection::new();
135
136        for middleware in &self.middleware {
137            // Skip pre-session middleware — they already ran in execute_before_session()
138            if middleware.runs_before_session() {
139                continue;
140            }
141
142            let mut injection = SessionInjection::new();
143            middleware
144                .before_dispatch(ctx, session, &mut injection)
145                .await?;
146
147            // Accumulate injections (later middleware can override earlier ones)
148            for (key, value) in injection.state() {
149                combined_injection.set_state(key.clone(), value.clone());
150            }
151            for (key, value) in injection.metadata() {
152                combined_injection.set_metadata(key.clone(), value.clone());
153            }
154        }
155
156        Ok(combined_injection)
157    }
158
159    /// Executes all middleware after dispatch, in reverse registration order.
160    ///
161    /// # Parameters
162    ///
163    /// - `ctx`: Read-only request context
164    /// - `result`: Mutable dispatcher result
165    ///
166    /// # Returns
167    ///
168    /// - `Ok(())`: All middleware succeeded
169    /// - `Err(MiddlewareError)`: First middleware that failed
170    ///
171    /// # Execution
172    ///
173    /// 1. Execute each middleware in reverse registration order
174    /// 2. Stop on first error
175    /// 3. Allow middleware to modify result
176    pub async fn execute_after(
177        &self,
178        ctx: &RequestContext<'_>,
179        result: &mut DispatcherResult,
180    ) -> Result<(), MiddlewareError> {
181        for middleware in self.middleware.iter().rev() {
182            middleware.after_dispatch(ctx, result).await?;
183        }
184
185        Ok(())
186    }
187}
188
189#[cfg(test)]
190mod tests {
191    use super::*;
192    use async_trait::async_trait;
193    use serde_json::json;
194
195    struct CountingMiddleware {
196        id: String,
197        counter: Arc<std::sync::Mutex<Vec<String>>>,
198    }
199
200    #[async_trait]
201    impl McpMiddleware for CountingMiddleware {
202        async fn before_dispatch(
203            &self,
204            _ctx: &mut RequestContext<'_>,
205            _session: Option<&dyn SessionView>,
206            injection: &mut SessionInjection,
207        ) -> Result<(), MiddlewareError> {
208            self.counter
209                .lock()
210                .unwrap()
211                .push(format!("before_{}", self.id));
212            injection.set_state(&self.id, json!(true));
213            Ok(())
214        }
215
216        async fn after_dispatch(
217            &self,
218            _ctx: &RequestContext<'_>,
219            _result: &mut DispatcherResult,
220        ) -> Result<(), MiddlewareError> {
221            self.counter
222                .lock()
223                .unwrap()
224                .push(format!("after_{}", self.id));
225            Ok(())
226        }
227    }
228
229    struct ErrorMiddleware {
230        error_on_before: bool,
231    }
232
233    #[async_trait]
234    impl McpMiddleware for ErrorMiddleware {
235        async fn before_dispatch(
236            &self,
237            _ctx: &mut RequestContext<'_>,
238            _session: Option<&dyn SessionView>,
239            _injection: &mut SessionInjection,
240        ) -> Result<(), MiddlewareError> {
241            if self.error_on_before {
242                Err(MiddlewareError::unauthorized("Test error"))
243            } else {
244                Ok(())
245            }
246        }
247    }
248
249    #[tokio::test]
250    async fn test_middleware_execution_order() {
251        let counter = Arc::new(std::sync::Mutex::new(Vec::new()));
252        let mut stack = MiddlewareStack::new();
253
254        stack.push(Arc::new(CountingMiddleware {
255            id: "first".to_string(),
256            counter: counter.clone(),
257        }));
258        stack.push(Arc::new(CountingMiddleware {
259            id: "second".to_string(),
260            counter: counter.clone(),
261        }));
262
263        let mut ctx = RequestContext::new("test/method", None);
264
265        // Execute before (no session needed for this test)
266        let injection = stack.execute_before(&mut ctx, None).await.unwrap();
267        assert_eq!(injection.state().len(), 2);
268        assert!(injection.state().contains_key("first"));
269        assert!(injection.state().contains_key("second"));
270
271        // Execute after
272        let mut result = DispatcherResult::Success(json!({"ok": true}));
273        stack.execute_after(&ctx, &mut result).await.unwrap();
274
275        // Verify order: before in normal order, after in reverse
276        let log = counter.lock().unwrap();
277        assert_eq!(log[0], "before_first");
278        assert_eq!(log[1], "before_second");
279        assert_eq!(log[2], "after_second"); // Reverse order
280        assert_eq!(log[3], "after_first");
281    }
282
283    #[tokio::test]
284    async fn test_middleware_error_stops_chain() {
285        let counter = Arc::new(std::sync::Mutex::new(Vec::new()));
286        let mut stack = MiddlewareStack::new();
287
288        stack.push(Arc::new(CountingMiddleware {
289            id: "first".to_string(),
290            counter: counter.clone(),
291        }));
292        stack.push(Arc::new(ErrorMiddleware {
293            error_on_before: true,
294        }));
295        stack.push(Arc::new(CountingMiddleware {
296            id: "third".to_string(),
297            counter: counter.clone(),
298        }));
299
300        let mut ctx = RequestContext::new("test/method", None);
301
302        // Execute before - should fail at second middleware (no session needed)
303        let result = stack.execute_before(&mut ctx, None).await;
304        assert!(result.is_err());
305        assert_eq!(
306            result.unwrap_err(),
307            MiddlewareError::unauthorized("Test error")
308        );
309
310        // Verify only first middleware executed
311        let log = counter.lock().unwrap();
312        assert_eq!(log.len(), 1);
313        assert_eq!(log[0], "before_first");
314    }
315
316    /// Middleware that filters tools from the response.
317    struct ToolFilteringMiddleware;
318
319    #[async_trait]
320    impl McpMiddleware for ToolFilteringMiddleware {
321        async fn before_dispatch(
322            &self,
323            _ctx: &mut RequestContext<'_>,
324            _session: Option<&dyn SessionView>,
325            _injection: &mut SessionInjection,
326        ) -> Result<(), MiddlewareError> {
327            Ok(())
328        }
329
330        async fn after_dispatch(
331            &self,
332            _ctx: &RequestContext<'_>,
333            result: &mut DispatcherResult,
334        ) -> Result<(), MiddlewareError> {
335            if let DispatcherResult::Success(val) = result
336                && let Some(tools) = val.get_mut("tools")
337                && let Some(arr) = tools.as_array_mut()
338            {
339                arr.retain(|t| t["name"] != "secret_tool");
340            }
341            Ok(())
342        }
343    }
344
345    #[tokio::test]
346    async fn test_after_dispatch_success_mutation_visible() {
347        let mut stack = MiddlewareStack::new();
348        stack.push(Arc::new(ToolFilteringMiddleware));
349
350        let ctx = RequestContext::new("tools/list", None);
351        let mut result = DispatcherResult::Success(json!({
352            "tools": [
353                {"name": "public_tool"},
354                {"name": "secret_tool"},
355                {"name": "another_tool"}
356            ]
357        }));
358
359        stack.execute_after(&ctx, &mut result).await.unwrap();
360
361        let val = result.success().unwrap();
362        let tools = val["tools"].as_array().unwrap();
363        assert_eq!(tools.len(), 2);
364        assert!(tools.iter().all(|t| t["name"] != "secret_tool"));
365    }
366
367    #[tokio::test]
368    async fn test_after_dispatch_success_to_error_mutation_visible() {
369        struct RejectingMiddleware;
370
371        #[async_trait]
372        impl McpMiddleware for RejectingMiddleware {
373            async fn before_dispatch(
374                &self,
375                _ctx: &mut RequestContext<'_>,
376                _session: Option<&dyn SessionView>,
377                _injection: &mut SessionInjection,
378            ) -> Result<(), MiddlewareError> {
379                Ok(())
380            }
381
382            async fn after_dispatch(
383                &self,
384                _ctx: &RequestContext<'_>,
385                result: &mut DispatcherResult,
386            ) -> Result<(), MiddlewareError> {
387                if result.is_success() {
388                    *result = DispatcherResult::Error("rejected by policy".to_string());
389                }
390                Ok(())
391            }
392        }
393
394        let mut stack = MiddlewareStack::new();
395        stack.push(Arc::new(RejectingMiddleware));
396
397        let ctx = RequestContext::new("tools/list", None);
398        let mut result = DispatcherResult::Success(json!({"tools": []}));
399
400        stack.execute_after(&ctx, &mut result).await.unwrap();
401
402        assert!(result.is_error());
403        assert_eq!(result.error().unwrap(), "rejected by policy");
404    }
405
406    #[tokio::test]
407    async fn test_empty_stack() {
408        let stack = MiddlewareStack::new();
409        assert!(stack.is_empty());
410        assert_eq!(stack.len(), 0);
411
412        let mut ctx = RequestContext::new("test/method", None);
413
414        let injection = stack.execute_before(&mut ctx, None).await.unwrap();
415        assert!(injection.is_empty());
416
417        let mut result = DispatcherResult::Success(json!({"ok": true}));
418        stack.execute_after(&ctx, &mut result).await.unwrap();
419    }
420}