mcpr-core 0.4.70

Core types, traits, protocol, and proxy engine for mcpr crates
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
//! Pipeline driver — the engine that runs middleware chains, the
//! router, and the transport.
//!
//! See `PIPELINE.md` §Layers. A short explicit loop that
//! owns an ordered `Vec<Box<dyn …>>` for each chain. No tower, no
//! service combinators.

use std::sync::OnceLock;
use std::time::Instant;

use async_trait::async_trait;

use super::middleware::{Flow, RequestMiddleware, ResponseMiddleware};
use super::values::{Context, Request, Response, Route, StageTiming};

/// `true` if `MCPR_STAGE_TIMING` is set to `1` or `true`. Checked once
/// per process and cached — the hot path pays one `OnceLock` load
/// (~1ns) per middleware dispatch.
pub fn stage_timing_enabled() -> bool {
    static ENABLED: OnceLock<bool> = OnceLock::new();
    *ENABLED.get_or_init(|| {
        std::env::var("MCPR_STAGE_TIMING")
            .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
            .unwrap_or(false)
    })
}

/// RAII timer — start one at the top of a block, get a
/// [`StageTiming`] pushed onto `sink` when the guard drops. Honors
/// [`stage_timing_enabled`] so disabled builds skip the push.
/// Handles early returns / `?` / panics because `Drop` always runs.
///
/// Used by non-middleware sites (transport sub-stages, intake parse).
/// Middlewares themselves are wrapped by the driver — their bodies
/// never construct a `StageGuard`.
pub struct StageGuard<'a> {
    name: &'static str,
    start: Instant,
    sink: &'a mut Vec<StageTiming>,
    enabled: bool,
}

impl<'a> StageGuard<'a> {
    pub fn start(name: &'static str, sink: &'a mut Vec<StageTiming>) -> Self {
        Self {
            name,
            start: Instant::now(),
            sink,
            enabled: stage_timing_enabled(),
        }
    }
}

impl Drop for StageGuard<'_> {
    fn drop(&mut self) {
        if self.enabled {
            self.sink.push(StageTiming {
                name: self.name,
                elapsed_us: self.start.elapsed().as_micros() as u64,
            });
        }
    }
}

/// Pure function: decide where a request is headed. No I/O.
pub trait Router: Send + Sync {
    fn route(&self, req: &Request, cx: &Context) -> Route;
}

/// The one layer that touches the network. Reqwest errors become
/// `Response::Upstream502`. Takes `&mut Context` so the transport can
/// write per-stage timings (`upstream_us`, `buffer_us`, `sse_unwrap_us`,
/// `json_parse_us`) onto `cx.working`.
#[async_trait]
pub trait Transport: Send + Sync {
    async fn dispatch(&self, req: Request, route: Route, cx: &mut Context) -> Response;
}

pub struct Pipeline<R: Router, T: Transport> {
    request_chain: Vec<Box<dyn RequestMiddleware>>,
    response_chain: Vec<Box<dyn ResponseMiddleware>>,
    router: R,
    transport: T,
}

impl<R: Router, T: Transport> Pipeline<R, T> {
    pub fn new(
        request_chain: Vec<Box<dyn RequestMiddleware>>,
        response_chain: Vec<Box<dyn ResponseMiddleware>>,
        router: R,
        transport: T,
    ) -> Self {
        // Registration logging is handled by `build_default_pipeline`,
        // which owns construction ordering and is the single site where
        // operator-visible chain composition needs to be reported.
        Self {
            request_chain,
            response_chain,
            router,
            transport,
        }
    }

    pub fn request_chain_names(&self) -> Vec<&'static str> {
        self.request_chain.iter().map(|mw| mw.name()).collect()
    }

    pub fn response_chain_names(&self) -> Vec<&'static str> {
        self.response_chain.iter().map(|mw| mw.name()).collect()
    }

    pub async fn run(&self, req: Request, cx: &mut Context) -> Response {
        let resp = match self.run_request_chain(req, cx).await {
            Ok(req) => {
                let route = self.router.route(&req, cx);
                self.transport.dispatch(req, route, cx).await
            }
            Err(short) => short,
        };
        self.run_response_chain(resp, cx).await
    }

    async fn run_request_chain(
        &self,
        mut req: Request,
        cx: &mut Context,
    ) -> Result<Request, Response> {
        let enabled = stage_timing_enabled();
        for mw in &self.request_chain {
            let started = enabled.then(Instant::now);
            let flow = mw.on_request(req, cx).await;
            if let Some(t) = started {
                cx.working.timings.push(StageTiming {
                    name: mw.name(),
                    elapsed_us: t.elapsed().as_micros() as u64,
                });
            }
            match flow {
                Flow::Continue(r) => req = r,
                Flow::ShortCircuit(r) => return Err(r),
            }
        }
        Ok(req)
    }

    async fn run_response_chain(&self, mut resp: Response, cx: &mut Context) -> Response {
        let enabled = stage_timing_enabled();
        for mw in &self.response_chain {
            let started = enabled.then(Instant::now);
            resp = mw.on_response(resp, cx).await;
            if let Some(t) = started {
                cx.working.timings.push(StageTiming {
                    name: mw.name(),
                    elapsed_us: t.elapsed().as_micros() as u64,
                });
            }
        }
        resp
    }
}

#[cfg(test)]
#[allow(non_snake_case)]
mod tests {
    use std::sync::{Arc, Mutex};

    use axum::http::{HeaderMap, StatusCode};
    use serde_json::json;

    use super::*;
    use crate::protocol::jsonrpc::JsonRpcEnvelope;
    use crate::protocol::mcp::{ClientKind, ClientMethod, McpMessage, MessageKind, ToolsMethod};
    use crate::proxy::pipeline::middleware::{Flow, RequestMiddleware, ResponseMiddleware};
    use crate::proxy::pipeline::middlewares::test_support::{test_context, test_proxy_state};
    use crate::proxy::pipeline::values::{
        BufferPolicy, Envelope, McpRequest, McpTransport, Request, Response, Route,
    };

    // ── Fakes ────────────────────────────────────────────────

    enum FakeReqAction {
        Continue,
        AnnotateTag(&'static str),
        ShortCircuit(&'static str),
    }

    struct FakeReqMw {
        name: &'static str,
        action: FakeReqAction,
    }

    #[async_trait]
    impl RequestMiddleware for FakeReqMw {
        fn name(&self) -> &'static str {
            self.name
        }
        async fn on_request(&self, req: Request, cx: &mut Context) -> Flow {
            match &self.action {
                FakeReqAction::Continue => Flow::Continue(req),
                FakeReqAction::AnnotateTag(t) => {
                    cx.working.tags.push(t);
                    Flow::Continue(req)
                }
                FakeReqAction::ShortCircuit(reason) => Flow::ShortCircuit(Response::Upstream502 {
                    reason: (*reason).to_owned(),
                }),
            }
        }
    }

    struct FakeRespMw {
        name: &'static str,
        annotate: &'static str,
    }

    #[async_trait]
    impl ResponseMiddleware for FakeRespMw {
        fn name(&self) -> &'static str {
            self.name
        }
        async fn on_response(&self, resp: Response, cx: &mut Context) -> Response {
            cx.working.tags.push(self.annotate);
            resp
        }
    }

    struct FakeRouter {
        route: Mutex<Option<Route>>,
        calls: Arc<Mutex<u32>>,
    }

    impl Router for FakeRouter {
        fn route(&self, _req: &Request, _cx: &Context) -> Route {
            *self.calls.lock().unwrap() += 1;
            self.route
                .lock()
                .unwrap()
                .take()
                .expect("FakeRouter called more than once")
        }
    }

    struct FakeTransport {
        response: Mutex<Option<Response>>,
        calls: Arc<Mutex<u32>>,
    }

    #[async_trait]
    impl Transport for FakeTransport {
        async fn dispatch(&self, _req: Request, _route: Route, _cx: &mut Context) -> Response {
            *self.calls.lock().unwrap() += 1;
            self.response
                .lock()
                .unwrap()
                .take()
                .expect("FakeTransport called more than once")
        }
    }

    // ── Harness ─────────────────────────────────────────────

    fn stub_mcp_request() -> Request {
        let env =
            JsonRpcEnvelope::parse(br#"{"jsonrpc":"2.0","id":1,"method":"tools/list"}"#).unwrap();
        Request::Mcp(McpRequest {
            transport: McpTransport::StreamableHttpPost,
            envelope: env,
            kind: ClientKind::Request(ClientMethod::Tools(ToolsMethod::List)),
            headers: HeaderMap::new(),
            session_hint: None,
        })
    }

    fn stub_buffered_response() -> Response {
        let env =
            JsonRpcEnvelope::parse(br#"{"jsonrpc":"2.0","id":1,"result":{"tools":[]}}"#).unwrap();
        let message = McpMessage {
            envelope: env,
            kind: MessageKind::Server(crate::protocol::mcp::ServerKind::Result),
        };
        Response::McpBuffered {
            envelope: Envelope::Json,
            message,
            status: StatusCode::OK,
            headers: HeaderMap::new(),
        }
    }

    fn stub_route() -> Route {
        Route::McpStreamableHttp {
            upstream: "http://upstream.test/mcp".into(),
            method: ClientMethod::Tools(ToolsMethod::List),
            buffer_policy: BufferPolicy::Buffered { max: 4096 },
        }
    }

    // ── Tests ───────────────────────────────────────────────

    #[tokio::test]
    async fn run__empty_chain_returns_transport_response() {
        let proxy = test_proxy_state();
        let mut cx = test_context(proxy);
        let router_calls = Arc::new(Mutex::new(0));
        let transport_calls = Arc::new(Mutex::new(0));
        let pipeline = Pipeline::new(
            Vec::<Box<dyn RequestMiddleware>>::new(),
            Vec::<Box<dyn ResponseMiddleware>>::new(),
            FakeRouter {
                route: Mutex::new(Some(stub_route())),
                calls: router_calls.clone(),
            },
            FakeTransport {
                response: Mutex::new(Some(stub_buffered_response())),
                calls: transport_calls.clone(),
            },
        );

        let resp = pipeline.run(stub_mcp_request(), &mut cx).await;
        assert!(matches!(resp, Response::McpBuffered { .. }));
        assert_eq!(*router_calls.lock().unwrap(), 1);
        assert_eq!(*transport_calls.lock().unwrap(), 1);
    }

    #[tokio::test]
    async fn run__request_chain_fires_in_order() {
        let proxy = test_proxy_state();
        let mut cx = test_context(proxy);
        let pipeline = Pipeline::new(
            vec![
                Box::new(FakeReqMw {
                    name: "a",
                    action: FakeReqAction::AnnotateTag("tag-a"),
                }) as _,
                Box::new(FakeReqMw {
                    name: "b",
                    action: FakeReqAction::AnnotateTag("tag-b"),
                }) as _,
                Box::new(FakeReqMw {
                    name: "c",
                    action: FakeReqAction::AnnotateTag("tag-c"),
                }) as _,
            ],
            Vec::<Box<dyn ResponseMiddleware>>::new(),
            FakeRouter {
                route: Mutex::new(Some(stub_route())),
                calls: Arc::new(Mutex::new(0)),
            },
            FakeTransport {
                response: Mutex::new(Some(stub_buffered_response())),
                calls: Arc::new(Mutex::new(0)),
            },
        );
        pipeline.run(stub_mcp_request(), &mut cx).await;
        assert_eq!(cx.working.tags.as_slice(), &["tag-a", "tag-b", "tag-c"]);
    }

    #[tokio::test]
    async fn run__short_circuit_skips_router_transport_and_later_request_mws() {
        let proxy = test_proxy_state();
        let mut cx = test_context(proxy);
        let router_calls = Arc::new(Mutex::new(0));
        let transport_calls = Arc::new(Mutex::new(0));
        let pipeline = Pipeline::new(
            vec![
                Box::new(FakeReqMw {
                    name: "before",
                    action: FakeReqAction::AnnotateTag("before"),
                }) as _,
                Box::new(FakeReqMw {
                    name: "cut",
                    action: FakeReqAction::ShortCircuit("cut"),
                }) as _,
                Box::new(FakeReqMw {
                    name: "after",
                    action: FakeReqAction::AnnotateTag("after"),
                }) as _,
            ],
            Vec::<Box<dyn ResponseMiddleware>>::new(),
            FakeRouter {
                route: Mutex::new(Some(stub_route())),
                calls: router_calls.clone(),
            },
            FakeTransport {
                response: Mutex::new(Some(stub_buffered_response())),
                calls: transport_calls.clone(),
            },
        );

        let resp = pipeline.run(stub_mcp_request(), &mut cx).await;
        assert!(matches!(resp, Response::Upstream502 { .. }));
        assert_eq!(cx.working.tags.as_slice(), &["before"]);
        assert_eq!(*router_calls.lock().unwrap(), 0);
        assert_eq!(*transport_calls.lock().unwrap(), 0);
    }

    #[tokio::test]
    async fn run__response_chain_runs_after_short_circuit() {
        let proxy = test_proxy_state();
        let mut cx = test_context(proxy);
        let pipeline = Pipeline::new(
            vec![Box::new(FakeReqMw {
                name: "cut",
                action: FakeReqAction::ShortCircuit("x"),
            }) as _],
            vec![
                Box::new(FakeRespMw {
                    name: "r1",
                    annotate: "resp-1",
                }) as _,
                Box::new(FakeRespMw {
                    name: "r2",
                    annotate: "resp-2",
                }) as _,
            ],
            FakeRouter {
                route: Mutex::new(Some(stub_route())),
                calls: Arc::new(Mutex::new(0)),
            },
            FakeTransport {
                response: Mutex::new(Some(stub_buffered_response())),
                calls: Arc::new(Mutex::new(0)),
            },
        );

        pipeline.run(stub_mcp_request(), &mut cx).await;
        assert_eq!(cx.working.tags.as_slice(), &["resp-1", "resp-2"]);
    }

    #[tokio::test]
    async fn run__response_chain_folds_in_order() {
        let proxy = test_proxy_state();
        let mut cx = test_context(proxy);
        let pipeline = Pipeline::new(
            Vec::<Box<dyn RequestMiddleware>>::new(),
            vec![
                Box::new(FakeRespMw {
                    name: "r1",
                    annotate: "r1",
                }) as _,
                Box::new(FakeRespMw {
                    name: "r2",
                    annotate: "r2",
                }) as _,
                Box::new(FakeRespMw {
                    name: "r3",
                    annotate: "r3",
                }) as _,
            ],
            FakeRouter {
                route: Mutex::new(Some(stub_route())),
                calls: Arc::new(Mutex::new(0)),
            },
            FakeTransport {
                response: Mutex::new(Some(stub_buffered_response())),
                calls: Arc::new(Mutex::new(0)),
            },
        );
        pipeline.run(stub_mcp_request(), &mut cx).await;
        assert_eq!(cx.working.tags.as_slice(), &["r1", "r2", "r3"]);
    }

    #[tokio::test]
    async fn chain_names__reports_registered_middlewares() {
        let pipeline = Pipeline::new(
            vec![
                Box::new(FakeReqMw {
                    name: "session_touch",
                    action: FakeReqAction::Continue,
                }) as _,
                Box::new(FakeReqMw {
                    name: "client_info_inject",
                    action: FakeReqAction::Continue,
                }) as _,
            ],
            vec![
                Box::new(FakeRespMw {
                    name: "schema_ingest",
                    annotate: "",
                }) as _,
                Box::new(FakeRespMw {
                    name: "envelope_seal",
                    annotate: "",
                }) as _,
            ],
            FakeRouter {
                route: Mutex::new(Some(stub_route())),
                calls: Arc::new(Mutex::new(0)),
            },
            FakeTransport {
                response: Mutex::new(Some(stub_buffered_response())),
                calls: Arc::new(Mutex::new(0)),
            },
        );
        assert_eq!(
            pipeline.request_chain_names(),
            vec!["session_touch", "client_info_inject"],
        );
        assert_eq!(
            pipeline.response_chain_names(),
            vec!["schema_ingest", "envelope_seal"],
        );
    }

    // ── Smoke test — one request through a full stub chain ──

    #[tokio::test]
    async fn smoke__request_response_roundtrip_with_mutation() {
        let proxy = test_proxy_state();
        let mut cx = test_context(proxy);
        let pipeline = Pipeline::new(
            vec![Box::new(FakeReqMw {
                name: "tag",
                action: FakeReqAction::AnnotateTag("touched"),
            }) as _],
            vec![Box::new(FakeRespMw {
                name: "tag_resp",
                annotate: "sealed",
            }) as _],
            FakeRouter {
                route: Mutex::new(Some(stub_route())),
                calls: Arc::new(Mutex::new(0)),
            },
            FakeTransport {
                response: Mutex::new(Some(Response::McpBuffered {
                    envelope: Envelope::Json,
                    message: McpMessage {
                        envelope: JsonRpcEnvelope::parse(
                            br#"{"jsonrpc":"2.0","id":42,"result":{"tools":[]}}"#,
                        )
                        .unwrap(),
                        kind: MessageKind::Server(crate::protocol::mcp::ServerKind::Result),
                    },
                    status: StatusCode::OK,
                    headers: HeaderMap::new(),
                })),
                calls: Arc::new(Mutex::new(0)),
            },
        );

        let resp = pipeline.run(stub_mcp_request(), &mut cx).await;
        match resp {
            Response::McpBuffered {
                status, message, ..
            } => {
                assert_eq!(status, StatusCode::OK);
                let result: serde_json::Value = message
                    .envelope
                    .result_as()
                    .expect("result should deserialize");
                assert_eq!(result, json!({"tools": []}));
            }
            other => panic!("expected McpBuffered, got {other:?}"),
        }
        assert_eq!(cx.working.tags.as_slice(), &["touched", "sealed"]);
    }
}