hyperlane_plugin_mcp/impl.rs
1use super::*;
2
3/// Formatting / debug-printing for [`McpError`].
4impl Display for McpError {
5 /// Formats the [`McpError`] via the supplied formatter.
6 ///
7 /// # Arguments
8 ///
9 /// - `&mut Formatter<'_>` - The formatter receiving the formatted output.
10 ///
11 /// # Returns
12 ///
13 /// - `fmt::Result` - A `fmt::Result` value.
14 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
15 match self {
16 Self::InvalidParams(msg) | Self::NotFound(msg) | Self::Internal(msg) => {
17 f.write_str(msg)
18 }
19 }
20 }
21}
22
23/// Implements [`Error`] for [`McpError`].
24impl Error for McpError {}
25
26/// Zero-allocation Serde [`Visitor`] borrowing strings directly from raw JSON slices.
27impl<'de> Visitor<'de> for McpBorrowStrVisitor {
28 type Value = McpBorrowStr<'de>;
29
30 /// Describes the expected JSON string value.
31 ///
32 /// # Arguments
33 ///
34 /// - `&mut Formatter<'_>` - Output formatter.
35 ///
36 /// # Returns
37 ///
38 /// - `fmt::Result` - Formatting outcome.
39 fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
40 formatter.write_str(EXPECTING_MCP_FIELD)
41 }
42
43 /// Borrows an unescaped string slice directly from the request bytes without allocating.
44 ///
45 /// # Arguments
46 ///
47 /// - `&'de str` - Borrowed JSON string.
48 ///
49 /// # Returns
50 ///
51 /// - `Result<Self::Value, E>` - Borrowed string wrapper.
52 #[inline]
53 fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
54 where
55 E: de::Error,
56 {
57 Ok(McpBorrowStr(Cow::Borrowed(v)))
58 }
59
60 /// Clones a transient unescaped string slice when borrowing is unavailable.
61 ///
62 /// # Arguments
63 ///
64 /// - `&str` - Transient JSON string.
65 ///
66 /// # Returns
67 ///
68 /// - `Result<Self::Value, E>` - Owned string wrapper.
69 #[inline]
70 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
71 where
72 E: de::Error,
73 {
74 Ok(McpBorrowStr(Cow::Owned(v.to_owned())))
75 }
76
77 /// Moves an already-owned string without re-allocating.
78 ///
79 /// # Arguments
80 ///
81 /// - `String` - Owned JSON string.
82 ///
83 /// # Returns
84 ///
85 /// - `Result<Self::Value, E>` - Owned string wrapper.
86 #[inline]
87 fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
88 where
89 E: de::Error,
90 {
91 Ok(McpBorrowStr(Cow::Owned(v)))
92 }
93}
94
95/// Implements [`Deserialize`] for [`McpBorrowStr`].
96impl<'de> Deserialize<'de> for McpBorrowStr<'de> {
97 /// Deserializes a JSON string borrowing directly when unescaped.
98 ///
99 /// # Arguments
100 ///
101 /// - `D` - Serde deserializer.
102 ///
103 /// # Returns
104 ///
105 /// - `Result<Self, D::Error>` - Borrowed or owned string wrapper.
106 #[inline]
107 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
108 where
109 D: Deserializer<'de>,
110 {
111 deserializer.deserialize_str(McpBorrowStrVisitor)
112 }
113}
114
115/// Permissive zero-allocation Serde [`Visitor`] returning `Some` for strings and draining non-strings into `None`.
116impl<'de> Visitor<'de> for McpOptBorrowStrVisitor {
117 type Value = McpOptBorrowStr<'de>;
118
119 /// Describes expected JSON values.
120 ///
121 /// # Arguments
122 ///
123 /// - `&mut Formatter<'_>` - Output formatter.
124 ///
125 /// # Returns
126 ///
127 /// - `fmt::Result` - Formatting outcome.
128 fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
129 formatter.write_str(EXPECTING_MCP_PARAMS)
130 }
131
132 /// Borrows an unescaped JSON string directly from the input slice.
133 ///
134 /// # Arguments
135 ///
136 /// - `&'de str` - Borrowed JSON string.
137 ///
138 /// # Returns
139 ///
140 /// - `Result<Self::Value, E>` - `Some` borrowed string wrapper.
141 #[inline]
142 fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
143 where
144 E: de::Error,
145 {
146 Ok(McpOptBorrowStr(Some(Cow::Borrowed(v))))
147 }
148
149 /// Clones a transient unescaped JSON string slice.
150 ///
151 /// # Arguments
152 ///
153 /// - `&str` - Transient JSON string.
154 ///
155 /// # Returns
156 ///
157 /// - `Result<Self::Value, E>` - `Some` owned string wrapper.
158 #[inline]
159 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
160 where
161 E: de::Error,
162 {
163 Ok(McpOptBorrowStr(Some(Cow::Owned(v.to_owned()))))
164 }
165
166 /// Takes ownership of an already-allocated JSON string.
167 ///
168 /// # Arguments
169 ///
170 /// - `String` - Owned JSON string.
171 ///
172 /// # Returns
173 ///
174 /// - `Result<Self::Value, E>` - `Some` owned string wrapper.
175 #[inline]
176 fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
177 where
178 E: de::Error,
179 {
180 Ok(McpOptBorrowStr(Some(Cow::Owned(v))))
181 }
182
183 /// Discards a JSON `null` value as `None`.
184 ///
185 /// # Returns
186 ///
187 /// - `Result<Self::Value, E>` - `None` wrapper.
188 #[inline]
189 fn visit_unit<E>(self) -> Result<Self::Value, E>
190 where
191 E: de::Error,
192 {
193 Ok(McpOptBorrowStr(None))
194 }
195
196 /// Discards a JSON boolean value as `None`.
197 ///
198 /// # Arguments
199 ///
200 /// - `bool` - Ignored boolean value.
201 ///
202 /// # Returns
203 ///
204 /// - `Result<Self::Value, E>` - `None` wrapper.
205 #[inline]
206 fn visit_bool<E>(self, _: bool) -> Result<Self::Value, E>
207 where
208 E: de::Error,
209 {
210 Ok(McpOptBorrowStr(None))
211 }
212
213 /// Discards a signed integer JSON value as `None`.
214 ///
215 /// # Arguments
216 ///
217 /// - `i64` - Ignored signed integer value.
218 ///
219 /// # Returns
220 ///
221 /// - `Result<Self::Value, E>` - `None` wrapper.
222 #[inline]
223 fn visit_i64<E>(self, _: i64) -> Result<Self::Value, E>
224 where
225 E: de::Error,
226 {
227 Ok(McpOptBorrowStr(None))
228 }
229
230 /// Discards an unsigned integer JSON value as `None`.
231 ///
232 /// # Arguments
233 ///
234 /// - `u64` - Ignored unsigned integer value.
235 ///
236 /// # Returns
237 ///
238 /// - `Result<Self::Value, E>` - `None` wrapper.
239 #[inline]
240 fn visit_u64<E>(self, _: u64) -> Result<Self::Value, E>
241 where
242 E: de::Error,
243 {
244 Ok(McpOptBorrowStr(None))
245 }
246
247 /// Discards a floating-point JSON value as `None`.
248 ///
249 /// # Arguments
250 ///
251 /// - `f64` - Ignored floating-point value.
252 ///
253 /// # Returns
254 ///
255 /// - `Result<Self::Value, E>` - `None` wrapper.
256 #[inline]
257 fn visit_f64<E>(self, _: f64) -> Result<Self::Value, E>
258 where
259 E: de::Error,
260 {
261 Ok(McpOptBorrowStr(None))
262 }
263
264 /// Drains a JSON array without allocating and returns `None`.
265 ///
266 /// # Arguments
267 ///
268 /// - `A` - Sequence access iterator.
269 ///
270 /// # Returns
271 ///
272 /// - `Result<Self::Value, A::Error>` - `None` wrapper.
273 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
274 where
275 A: SeqAccess<'de>,
276 {
277 while seq.next_element::<IgnoredAny>()?.is_some() {}
278 Ok(McpOptBorrowStr(None))
279 }
280
281 /// Drains a JSON object without allocating and returns `None`.
282 ///
283 /// # Arguments
284 ///
285 /// - `A` - Map access iterator.
286 ///
287 /// # Returns
288 ///
289 /// - `Result<Self::Value, A::Error>` - `None` wrapper.
290 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
291 where
292 A: MapAccess<'de>,
293 {
294 while map.next_entry::<IgnoredAny, IgnoredAny>()?.is_some() {}
295 Ok(McpOptBorrowStr(None))
296 }
297}
298
299/// Implements [`Deserialize`] for [`McpOptBorrowStr`].
300impl<'de> Deserialize<'de> for McpOptBorrowStr<'de> {
301 /// Deserializes any JSON value into `Some(str)` when a string or `None` otherwise.
302 ///
303 /// # Arguments
304 ///
305 /// - `D` - Serde deserializer.
306 ///
307 /// # Returns
308 ///
309 /// - `Result<Self, D::Error>` - Permissive string wrapper.
310 #[inline]
311 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
312 where
313 D: Deserializer<'de>,
314 {
315 deserializer.deserialize_any(McpOptBorrowStrVisitor)
316 }
317}
318
319/// Zero-allocation Serde [`Visitor`] decoding JSON-RPC 2.0 request field names.
320impl<'de> Visitor<'de> for McpRpcFieldVisitor {
321 type Value = McpRpcField;
322
323 /// Describes expected JSON-RPC field keys.
324 ///
325 /// # Arguments
326 ///
327 /// - `&mut Formatter<'_>` - Output formatter.
328 ///
329 /// # Returns
330 ///
331 /// - `fmt::Result` - Formatting outcome.
332 fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
333 formatter.write_str(EXPECTING_MCP_FIELD)
334 }
335
336 /// Matches JSON-RPC field names without allocating.
337 ///
338 /// # Arguments
339 ///
340 /// - `&str` - Decoded field name.
341 ///
342 /// # Returns
343 ///
344 /// - `Result<Self::Value, E>` - Matched field discriminator.
345 #[inline]
346 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
347 where
348 E: de::Error,
349 {
350 Ok(match v {
351 KEY_JSONRPC => McpRpcField::JsonRpc,
352 KEY_METHOD => McpRpcField::Method,
353 KEY_ID => McpRpcField::Id,
354 KEY_PARAMS => McpRpcField::Params,
355 _ => McpRpcField::Ignore,
356 })
357 }
358}
359
360/// Implements [`Deserialize`] for [`McpRpcField`].
361impl<'de> Deserialize<'de> for McpRpcField {
362 /// Deserializes a JSON-RPC request field identifier without allocation.
363 ///
364 /// # Arguments
365 ///
366 /// - `D` - Serde deserializer.
367 ///
368 /// # Returns
369 ///
370 /// - `Result<Self, D::Error>` - Matched field variant.
371 #[inline]
372 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
373 where
374 D: Deserializer<'de>,
375 {
376 deserializer.deserialize_identifier(McpRpcFieldVisitor)
377 }
378}
379
380/// Zero-allocation Serde [`Visitor`] decoding JSON-RPC 2.0 correlation ids.
381impl<'de> Visitor<'de> for McpRpcIdVisitor {
382 type Value = McpRpcId<'de>;
383
384 /// Describes expected correlation id values.
385 ///
386 /// # Arguments
387 ///
388 /// - `&mut Formatter<'_>` - Output formatter.
389 ///
390 /// # Returns
391 ///
392 /// - `fmt::Result` - Formatting outcome.
393 fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
394 formatter.write_str(EXPECTING_MCP_ID)
395 }
396
397 /// Decodes `null` correlation ids.
398 ///
399 /// # Returns
400 ///
401 /// - `Result<Self::Value, E>` - [`McpRpcId::Null`].
402 #[inline]
403 fn visit_unit<E>(self) -> Result<Self::Value, E>
404 where
405 E: de::Error,
406 {
407 Ok(McpRpcId::Null)
408 }
409
410 /// Decodes unsigned integer correlation ids without allocation.
411 ///
412 /// # Arguments
413 ///
414 /// - `u64` - Unsigned integer id.
415 ///
416 /// # Returns
417 ///
418 /// - `Result<Self::Value, E>` - [`McpRpcId::U64`].
419 #[inline]
420 fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
421 where
422 E: de::Error,
423 {
424 Ok(McpRpcId::U64(v))
425 }
426
427 /// Decodes signed integer correlation ids without allocation.
428 ///
429 /// # Arguments
430 ///
431 /// - `i64` - Signed integer id.
432 ///
433 /// # Returns
434 ///
435 /// - `Result<Self::Value, E>` - [`McpRpcId::I64`].
436 #[inline]
437 fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
438 where
439 E: de::Error,
440 {
441 Ok(McpRpcId::I64(v))
442 }
443
444 /// Borrows an unescaped string correlation id directly from request bytes.
445 ///
446 /// # Arguments
447 ///
448 /// - `&'de str` - Borrowed string id.
449 ///
450 /// # Returns
451 ///
452 /// - `Result<Self::Value, E>` - [`McpRpcId::Str`].
453 #[inline]
454 fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
455 where
456 E: de::Error,
457 {
458 Ok(McpRpcId::Str(Cow::Borrowed(v)))
459 }
460
461 /// Clones a transient string correlation id.
462 ///
463 /// # Arguments
464 ///
465 /// - `&str` - Transient string id.
466 ///
467 /// # Returns
468 ///
469 /// - `Result<Self::Value, E>` - [`McpRpcId::Str`].
470 #[inline]
471 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
472 where
473 E: de::Error,
474 {
475 Ok(McpRpcId::Str(Cow::Owned(v.to_owned())))
476 }
477
478 /// Takes ownership of an already-allocated string correlation id.
479 ///
480 /// # Arguments
481 ///
482 /// - `String` - Owned string id.
483 ///
484 /// # Returns
485 ///
486 /// - `Result<Self::Value, E>` - [`McpRpcId::Str`].
487 #[inline]
488 fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
489 where
490 E: de::Error,
491 {
492 Ok(McpRpcId::Str(Cow::Owned(v)))
493 }
494
495 /// Decodes boolean correlation ids into fallback [`Value`].
496 ///
497 /// # Arguments
498 ///
499 /// - `bool` - Boolean value.
500 ///
501 /// # Returns
502 ///
503 /// - `Result<Self::Value, E>` - [`McpRpcId::Other`].
504 fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
505 where
506 E: de::Error,
507 {
508 Ok(McpRpcId::Other(Value::Bool(v)))
509 }
510
511 /// Decodes floating-point correlation ids into fallback [`Value`].
512 ///
513 /// # Arguments
514 ///
515 /// - `f64` - Floating-point value.
516 ///
517 /// # Returns
518 ///
519 /// - `Result<Self::Value, E>` - [`McpRpcId::Other`] or [`McpRpcId::Null`].
520 fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>
521 where
522 E: de::Error,
523 {
524 Ok(Number::from_f64(v).map_or(McpRpcId::Null, |n: Number| {
525 McpRpcId::Other(Value::Number(n))
526 }))
527 }
528}
529
530/// Implements [`Deserialize`] for [`McpRpcId`].
531impl<'de> Deserialize<'de> for McpRpcId<'de> {
532 /// Deserializes a JSON-RPC correlation id without allocating for common integer/string/null ids.
533 ///
534 /// # Arguments
535 ///
536 /// - `D` - Serde deserializer.
537 ///
538 /// # Returns
539 ///
540 /// - `Result<Self, D::Error>` - Parsed correlation id.
541 #[inline]
542 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
543 where
544 D: Deserializer<'de>,
545 {
546 deserializer.deserialize_any(McpRpcIdVisitor)
547 }
548}
549
550/// Zero-allocation Serde [`Visitor`] for `tools/call` and `prompts/get` parameter field names.
551impl<'de> Visitor<'de> for McpNamedParamsFieldVisitor {
552 type Value = McpNamedParamsField;
553
554 /// Describes expected parameter field names.
555 ///
556 /// # Arguments
557 ///
558 /// - `&mut Formatter<'_>` - Output formatter.
559 ///
560 /// # Returns
561 ///
562 /// - `fmt::Result` - Formatting outcome.
563 fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
564 formatter.write_str(EXPECTING_MCP_FIELD)
565 }
566
567 /// Matches `"name"` and `"arguments"` parameter keys without allocation.
568 ///
569 /// # Arguments
570 ///
571 /// - `&str` - Parameter key name.
572 ///
573 /// # Returns
574 ///
575 /// - `Result<Self::Value, E>` - Matched field variant.
576 #[inline]
577 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
578 where
579 E: de::Error,
580 {
581 Ok(match v {
582 KEY_NAME => McpNamedParamsField::Name,
583 KEY_ARGUMENTS => McpNamedParamsField::Arguments,
584 _ => McpNamedParamsField::Ignore,
585 })
586 }
587}
588
589/// Implements [`Deserialize`] for [`McpNamedParamsField`].
590impl<'de> Deserialize<'de> for McpNamedParamsField {
591 /// Deserializes a named-call parameter field identifier.
592 ///
593 /// # Arguments
594 ///
595 /// - `D` - Serde deserializer.
596 ///
597 /// # Returns
598 ///
599 /// - `Result<Self, D::Error>` - Field variant.
600 #[inline]
601 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
602 where
603 D: Deserializer<'de>,
604 {
605 deserializer.deserialize_identifier(McpNamedParamsFieldVisitor)
606 }
607}
608
609/// Zero-allocation Serde [`Visitor`] decoding `tools/call` / `prompts/get` params directly.
610impl<'de> Visitor<'de> for McpNamedParamsVisitor {
611 type Value = McpNamedParamsSeed<'de>;
612
613 /// Describes expected parameter JSON values.
614 ///
615 /// # Arguments
616 ///
617 /// - `&mut Formatter<'_>` - Output formatter.
618 ///
619 /// # Returns
620 ///
621 /// - `fmt::Result` - Formatting outcome.
622 fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
623 formatter.write_str(EXPECTING_MCP_PARAMS)
624 }
625
626 /// Extracts `"name"` and `"arguments"` directly from a JSON object without building an outer `Map`.
627 ///
628 /// # Arguments
629 ///
630 /// - `A` - Serde map access iterator.
631 ///
632 /// # Returns
633 ///
634 /// - `Result<Self::Value, A::Error>` - Decoded named parameters.
635 #[inline]
636 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
637 where
638 A: MapAccess<'de>,
639 {
640 let mut name: Option<Cow<'de, str>> = None;
641 let mut arguments: Option<Value> = None;
642 while let Some(field) = map.next_key::<McpNamedParamsField>()? {
643 match field {
644 McpNamedParamsField::Name => {
645 let val: McpOptBorrowStr<'de> = map.next_value()?;
646 name = val.0;
647 }
648 McpNamedParamsField::Arguments => {
649 arguments = Some(map.next_value()?);
650 }
651 McpNamedParamsField::Ignore => {
652 let _: IgnoredAny = map.next_value()?;
653 }
654 }
655 }
656 Ok(McpNamedParamsSeed(McpParsedParams::Named {
657 name,
658 arguments,
659 }))
660 }
661
662 /// Marks `null` params as invalid object params.
663 ///
664 /// # Returns
665 ///
666 /// - `Result<Self::Value, E>` - [`McpParsedParams::Invalid`].
667 fn visit_unit<E>(self) -> Result<Self::Value, E>
668 where
669 E: de::Error,
670 {
671 Ok(McpNamedParamsSeed(McpParsedParams::Invalid))
672 }
673
674 /// Marks boolean params as invalid object params.
675 ///
676 /// # Arguments
677 ///
678 /// - `bool` - Ignored value.
679 ///
680 /// # Returns
681 ///
682 /// - `Result<Self::Value, E>` - [`McpParsedParams::Invalid`].
683 fn visit_bool<E>(self, _: bool) -> Result<Self::Value, E>
684 where
685 E: de::Error,
686 {
687 Ok(McpNamedParamsSeed(McpParsedParams::Invalid))
688 }
689
690 /// Marks signed integer params as invalid object params.
691 ///
692 /// # Arguments
693 ///
694 /// - `i64` - Ignored value.
695 ///
696 /// # Returns
697 ///
698 /// - `Result<Self::Value, E>` - [`McpParsedParams::Invalid`].
699 fn visit_i64<E>(self, _: i64) -> Result<Self::Value, E>
700 where
701 E: de::Error,
702 {
703 Ok(McpNamedParamsSeed(McpParsedParams::Invalid))
704 }
705
706 /// Marks unsigned integer params as invalid object params.
707 ///
708 /// # Arguments
709 ///
710 /// - `u64` - Ignored value.
711 ///
712 /// # Returns
713 ///
714 /// - `Result<Self::Value, E>` - [`McpParsedParams::Invalid`].
715 fn visit_u64<E>(self, _: u64) -> Result<Self::Value, E>
716 where
717 E: de::Error,
718 {
719 Ok(McpNamedParamsSeed(McpParsedParams::Invalid))
720 }
721
722 /// Marks float params as invalid object params.
723 ///
724 /// # Arguments
725 ///
726 /// - `f64` - Ignored value.
727 ///
728 /// # Returns
729 ///
730 /// - `Result<Self::Value, E>` - [`McpParsedParams::Invalid`].
731 fn visit_f64<E>(self, _: f64) -> Result<Self::Value, E>
732 where
733 E: de::Error,
734 {
735 Ok(McpNamedParamsSeed(McpParsedParams::Invalid))
736 }
737
738 /// Marks string params as invalid object params.
739 ///
740 /// # Arguments
741 ///
742 /// - `&str` - Ignored value.
743 ///
744 /// # Returns
745 ///
746 /// - `Result<Self::Value, E>` - [`McpParsedParams::Invalid`].
747 fn visit_str<E>(self, _: &str) -> Result<Self::Value, E>
748 where
749 E: de::Error,
750 {
751 Ok(McpNamedParamsSeed(McpParsedParams::Invalid))
752 }
753
754 /// Drains and marks array params as invalid object params.
755 ///
756 /// # Arguments
757 ///
758 /// - `A` - Sequence access iterator.
759 ///
760 /// # Returns
761 ///
762 /// - `Result<Self::Value, A::Error>` - [`McpParsedParams::Invalid`].
763 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
764 where
765 A: SeqAccess<'de>,
766 {
767 while seq.next_element::<IgnoredAny>()?.is_some() {}
768 Ok(McpNamedParamsSeed(McpParsedParams::Invalid))
769 }
770}
771
772/// Implements [`Deserialize`] for [`McpNamedParamsSeed`].
773impl<'de> Deserialize<'de> for McpNamedParamsSeed<'de> {
774 /// Deserializes named call params directly via [`McpNamedParamsVisitor`].
775 ///
776 /// # Arguments
777 ///
778 /// - `D` - Serde deserializer.
779 ///
780 /// # Returns
781 ///
782 /// - `Result<Self, D::Error>` - Parsed params wrapper.
783 #[inline]
784 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
785 where
786 D: Deserializer<'de>,
787 {
788 deserializer.deserialize_any(McpNamedParamsVisitor)
789 }
790}
791
792/// Zero-allocation Serde [`Visitor`] for `resources/read` parameter field names.
793impl<'de> Visitor<'de> for McpUriParamsFieldVisitor {
794 type Value = McpUriParamsField;
795
796 /// Describes expected resource parameter field names.
797 ///
798 /// # Arguments
799 ///
800 /// - `&mut Formatter<'_>` - Output formatter.
801 ///
802 /// # Returns
803 ///
804 /// - `fmt::Result` - Formatting outcome.
805 fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
806 formatter.write_str(EXPECTING_MCP_FIELD)
807 }
808
809 /// Matches `"uri"` without allocation.
810 ///
811 /// # Arguments
812 ///
813 /// - `&str` - Field key name.
814 ///
815 /// # Returns
816 ///
817 /// - `Result<Self::Value, E>` - Matched field variant.
818 #[inline]
819 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
820 where
821 E: de::Error,
822 {
823 Ok(if v == KEY_URI {
824 McpUriParamsField::Uri
825 } else {
826 McpUriParamsField::Ignore
827 })
828 }
829}
830
831/// Implements [`Deserialize`] for [`McpUriParamsField`].
832impl<'de> Deserialize<'de> for McpUriParamsField {
833 /// Deserializes a resource-read parameter field identifier.
834 ///
835 /// # Arguments
836 ///
837 /// - `D` - Serde deserializer.
838 ///
839 /// # Returns
840 ///
841 /// - `Result<Self, D::Error>` - Field variant.
842 #[inline]
843 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
844 where
845 D: Deserializer<'de>,
846 {
847 deserializer.deserialize_identifier(McpUriParamsFieldVisitor)
848 }
849}
850
851/// Zero-allocation Serde [`Visitor`] decoding `resources/read` params directly.
852impl<'de> Visitor<'de> for McpUriParamsVisitor {
853 type Value = McpUriParamsSeed<'de>;
854
855 /// Describes expected resource parameter JSON values.
856 ///
857 /// # Arguments
858 ///
859 /// - `&mut Formatter<'_>` - Output formatter.
860 ///
861 /// # Returns
862 ///
863 /// - `fmt::Result` - Formatting outcome.
864 fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
865 formatter.write_str(EXPECTING_MCP_PARAMS)
866 }
867
868 /// Extracts `"uri"` directly without allocating an outer `serde_json::Map`.
869 ///
870 /// # Arguments
871 ///
872 /// - `A` - Serde map access iterator.
873 ///
874 /// # Returns
875 ///
876 /// - `Result<Self::Value, A::Error>` - Decoded resource URI parameters.
877 #[inline]
878 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
879 where
880 A: MapAccess<'de>,
881 {
882 let mut uri: Option<String> = None;
883 while let Some(field) = map.next_key::<McpUriParamsField>()? {
884 match field {
885 McpUriParamsField::Uri => {
886 let val: McpOptBorrowStr<'de> = map.next_value()?;
887 uri = val.0.map(Cow::into_owned);
888 }
889 McpUriParamsField::Ignore => {
890 let _: IgnoredAny = map.next_value()?;
891 }
892 }
893 }
894 Ok(McpUriParamsSeed(McpParsedParams::Uri { uri }))
895 }
896
897 /// Marks `null` params as invalid object params.
898 ///
899 /// # Returns
900 ///
901 /// - `Result<Self::Value, E>` - [`McpParsedParams::Invalid`].
902 fn visit_unit<E>(self) -> Result<Self::Value, E>
903 where
904 E: de::Error,
905 {
906 Ok(McpUriParamsSeed(McpParsedParams::Invalid))
907 }
908
909 /// Marks boolean params as invalid object params.
910 ///
911 /// # Arguments
912 ///
913 /// - `bool` - Ignored value.
914 ///
915 /// # Returns
916 ///
917 /// - `Result<Self::Value, E>` - [`McpParsedParams::Invalid`].
918 fn visit_bool<E>(self, _: bool) -> Result<Self::Value, E>
919 where
920 E: de::Error,
921 {
922 Ok(McpUriParamsSeed(McpParsedParams::Invalid))
923 }
924
925 /// Marks signed integer params as invalid object params.
926 ///
927 /// # Arguments
928 ///
929 /// - `i64` - Ignored value.
930 ///
931 /// # Returns
932 ///
933 /// - `Result<Self::Value, E>` - [`McpParsedParams::Invalid`].
934 fn visit_i64<E>(self, _: i64) -> Result<Self::Value, E>
935 where
936 E: de::Error,
937 {
938 Ok(McpUriParamsSeed(McpParsedParams::Invalid))
939 }
940
941 /// Marks unsigned integer params as invalid object params.
942 ///
943 /// # Arguments
944 ///
945 /// - `u64` - Ignored value.
946 ///
947 /// # Returns
948 ///
949 /// - `Result<Self::Value, E>` - [`McpParsedParams::Invalid`].
950 fn visit_u64<E>(self, _: u64) -> Result<Self::Value, E>
951 where
952 E: de::Error,
953 {
954 Ok(McpUriParamsSeed(McpParsedParams::Invalid))
955 }
956
957 /// Marks float params as invalid object params.
958 ///
959 /// # Arguments
960 ///
961 /// - `f64` - Ignored value.
962 ///
963 /// # Returns
964 ///
965 /// - `Result<Self::Value, E>` - [`McpParsedParams::Invalid`].
966 fn visit_f64<E>(self, _: f64) -> Result<Self::Value, E>
967 where
968 E: de::Error,
969 {
970 Ok(McpUriParamsSeed(McpParsedParams::Invalid))
971 }
972
973 /// Marks string params as invalid object params.
974 ///
975 /// # Arguments
976 ///
977 /// - `&str` - Ignored value.
978 ///
979 /// # Returns
980 ///
981 /// - `Result<Self::Value, E>` - [`McpParsedParams::Invalid`].
982 fn visit_str<E>(self, _: &str) -> Result<Self::Value, E>
983 where
984 E: de::Error,
985 {
986 Ok(McpUriParamsSeed(McpParsedParams::Invalid))
987 }
988
989 /// Drains and marks array params as invalid object params.
990 ///
991 /// # Arguments
992 ///
993 /// - `A` - Sequence access iterator.
994 ///
995 /// # Returns
996 ///
997 /// - `Result<Self::Value, A::Error>` - [`McpParsedParams::Invalid`].
998 fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
999 where
1000 A: SeqAccess<'de>,
1001 {
1002 while seq.next_element::<IgnoredAny>()?.is_some() {}
1003 Ok(McpUriParamsSeed(McpParsedParams::Invalid))
1004 }
1005}
1006
1007/// Implements [`Deserialize`] for [`McpUriParamsSeed`].
1008impl<'de> Deserialize<'de> for McpUriParamsSeed<'de> {
1009 /// Deserializes resource-read params directly via [`McpUriParamsVisitor`].
1010 ///
1011 /// # Arguments
1012 ///
1013 /// - `D` - Serde deserializer.
1014 ///
1015 /// # Returns
1016 ///
1017 /// - `Result<Self, D::Error>` - Parsed params wrapper.
1018 #[inline]
1019 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1020 where
1021 D: Deserializer<'de>,
1022 {
1023 deserializer.deserialize_any(McpUriParamsVisitor)
1024 }
1025}
1026
1027/// Single-pass zero-allocation Serde [`Visitor`] for [`McpRpcRequest`].
1028impl<'de> Visitor<'de> for McpRpcRequestVisitor {
1029 type Value = McpRpcRequest<'de>;
1030
1031 /// Describes expected JSON-RPC 2.0 request objects.
1032 ///
1033 /// # Arguments
1034 ///
1035 /// - `&mut Formatter<'_>` - Output formatter.
1036 ///
1037 /// # Returns
1038 ///
1039 /// - `fmt::Result` - Formatting outcome.
1040 fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
1041 formatter.write_str(EXPECTING_MCP_REQUEST)
1042 }
1043
1044 /// Decodes a JSON-RPC 2.0 envelope skipping or directly decoding `"params"` based on `"method"`.
1045 ///
1046 /// # Arguments
1047 ///
1048 /// - `A` - Serde map access iterator.
1049 ///
1050 /// # Returns
1051 ///
1052 /// - `Result<Self::Value, A::Error>` - Decoded [`McpRpcRequest`].
1053 #[inline]
1054 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1055 where
1056 A: MapAccess<'de>,
1057 {
1058 let mut jsonrpc: Option<Cow<'de, str>> = None;
1059 let mut method: Option<Cow<'de, str>> = None;
1060 let mut id: Option<McpRpcId<'de>> = None;
1061 let mut params: McpParsedParams<'de> = McpParsedParams::None;
1062 while let Some(field) = map.next_key::<McpRpcField>()? {
1063 match field {
1064 McpRpcField::JsonRpc => {
1065 let val: Option<McpBorrowStr<'de>> = map.next_value()?;
1066 jsonrpc = val.map(|s: McpBorrowStr<'de>| s.0);
1067 }
1068 McpRpcField::Method => {
1069 let val: Option<McpBorrowStr<'de>> = map.next_value()?;
1070 method = val.map(|s: McpBorrowStr<'de>| s.0);
1071 }
1072 McpRpcField::Id => {
1073 id = Some(map.next_value()?);
1074 }
1075 McpRpcField::Params => {
1076 params = match method.as_deref() {
1077 Some(
1078 METHOD_INITIALIZE
1079 | METHOD_PING
1080 | METHOD_TOOLS_LIST
1081 | METHOD_RESOURCES_LIST
1082 | METHOD_PROMPTS_LIST
1083 | METHOD_NOTIF_INITIALIZED,
1084 ) => {
1085 let _: IgnoredAny = map.next_value()?;
1086 McpParsedParams::None
1087 }
1088 Some(METHOD_TOOLS_CALL | METHOD_PROMPTS_GET) => {
1089 let seed: McpNamedParamsSeed<'de> = map.next_value()?;
1090 seed.0
1091 }
1092 Some(METHOD_RESOURCES_READ) => {
1093 let seed: McpUriParamsSeed<'de> = map.next_value()?;
1094 seed.0
1095 }
1096 _ => McpParsedParams::Raw(map.next_value()?),
1097 };
1098 }
1099 McpRpcField::Ignore => {
1100 let _: IgnoredAny = map.next_value()?;
1101 }
1102 }
1103 }
1104 Ok(McpRpcRequest {
1105 jsonrpc,
1106 method,
1107 id,
1108 params,
1109 })
1110 }
1111}
1112
1113/// Implements [`Deserialize`] for [`McpRpcRequest`].
1114impl<'de> Deserialize<'de> for McpRpcRequest<'de> {
1115 /// Deserializes a JSON-RPC 2.0 request envelope directly via [`McpRpcRequestVisitor`].
1116 ///
1117 /// # Arguments
1118 ///
1119 /// - `D` - Serde deserializer.
1120 ///
1121 /// # Returns
1122 ///
1123 /// - `Result<Self, D::Error>` - Decoded request envelope.
1124 #[inline]
1125 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1126 where
1127 D: Deserializer<'de>,
1128 {
1129 deserializer.deserialize_map(McpRpcRequestVisitor)
1130 }
1131}
1132
1133/// Default construction for [`McpServerConfig`].
1134impl Default for McpServerConfig {
1135 /// Constructs a default [`McpServerConfig`] value.
1136 fn default() -> Self {
1137 Self {
1138 name: DEFAULT_MCP_SERVER_NAME.to_owned(),
1139 version: DEFAULT_MCP_SERVER_VERSION.to_owned(),
1140 protocol_version: DEFAULT_MCP_PROTOCOL_VERSION.to_owned(),
1141 endpoint: DEFAULT_MCP_ENDPOINT.to_owned(),
1142 allowed_origins: Vec::new(),
1143 max_sessions: DEFAULT_MCP_MAX_SESSIONS,
1144 max_body_size: DEFAULT_MCP_MAX_BODY_SIZE,
1145 session_ttl_ms: DEFAULT_MCP_SESSION_TTL_MS,
1146 }
1147 }
1148}
1149
1150/// Inherent fluent builders for [`McpServerConfig`].
1151impl McpServerConfig {
1152 /// Returns a configuration with the given advertised server name.
1153 ///
1154 /// # Arguments
1155 ///
1156 /// - `N` - Server name convertible into `String`.
1157 ///
1158 /// # Returns
1159 ///
1160 /// - `Self` - Updated configuration.
1161 pub fn with_name<N>(mut self, name: N) -> Self
1162 where
1163 N: Into<String>,
1164 {
1165 self.set_name(name.into());
1166 self
1167 }
1168
1169 /// Returns a configuration with the given advertised server version.
1170 ///
1171 /// # Arguments
1172 ///
1173 /// - `V` - Version string convertible into `String`.
1174 ///
1175 /// # Returns
1176 ///
1177 /// - `Self` - Updated configuration.
1178 pub fn with_version<V>(mut self, version: V) -> Self
1179 where
1180 V: Into<String>,
1181 {
1182 self.set_version(version.into());
1183 self
1184 }
1185
1186 /// Returns a configuration with the given MCP endpoint path.
1187 ///
1188 /// # Arguments
1189 ///
1190 /// - `E` - Endpoint path convertible into `String`.
1191 ///
1192 /// # Returns
1193 ///
1194 /// - `Self` - Updated configuration.
1195 pub fn with_endpoint<E>(mut self, endpoint: E) -> Self
1196 where
1197 E: Into<String>,
1198 {
1199 self.set_endpoint(endpoint.into());
1200 self
1201 }
1202
1203 /// Returns a configuration with the given allowed `Origin` allowlist.
1204 ///
1205 /// # Arguments
1206 ///
1207 /// - `Vec<String>` - Allowed `Origin` header values.
1208 ///
1209 /// # Returns
1210 ///
1211 /// - `Self` - Updated configuration.
1212 pub fn with_allowed_origins(mut self, allowed_origins: Vec<String>) -> Self {
1213 self.set_allowed_origins(allowed_origins);
1214 self
1215 }
1216
1217 /// Returns a configuration with the given maximum concurrent session count.
1218 ///
1219 /// # Arguments
1220 ///
1221 /// - `usize` - Maximum tracked concurrent sessions.
1222 ///
1223 /// # Returns
1224 ///
1225 /// - `Self` - Updated configuration.
1226 pub fn with_max_sessions(mut self, max_sessions: usize) -> Self {
1227 self.set_max_sessions(max_sessions);
1228 self
1229 }
1230
1231 /// Returns a configuration with the given maximum incoming body size in bytes.
1232 ///
1233 /// # Arguments
1234 ///
1235 /// - `usize` - Maximum request body bytes.
1236 ///
1237 /// # Returns
1238 ///
1239 /// - `Self` - Updated configuration.
1240 pub fn with_max_body_size(mut self, max_body_size: usize) -> Self {
1241 self.set_max_body_size(max_body_size);
1242 self
1243 }
1244
1245 /// Returns a configuration with the given session idle TTL in milliseconds (`0` disables expiration).
1246 ///
1247 /// # Arguments
1248 ///
1249 /// - `u64` - Session TTL in milliseconds.
1250 ///
1251 /// # Returns
1252 ///
1253 /// - `Self` - Updated configuration.
1254 pub fn with_session_ttl_ms(mut self, session_ttl_ms: u64) -> Self {
1255 self.set_session_ttl_ms(session_ttl_ms);
1256 self
1257 }
1258}
1259
1260/// Inherent implementation of [`McpToolResult`].
1261impl McpToolResult {
1262 /// Creates a plain-text MCP tool result block.
1263 ///
1264 /// # Arguments
1265 ///
1266 /// - `T` - Text content convertible into `String`.
1267 ///
1268 /// # Returns
1269 ///
1270 /// - `Self` - Non-error text tool result.
1271 pub fn text<T>(text: T) -> Self
1272 where
1273 T: Into<String>,
1274 {
1275 Self {
1276 content: vec![mcp_text_content(text.into())],
1277 is_error: false,
1278 }
1279 }
1280
1281 /// Creates an error-flagged text MCP tool result block.
1282 ///
1283 /// # Arguments
1284 ///
1285 /// - `T` - Error message convertible into `String`.
1286 ///
1287 /// # Returns
1288 ///
1289 /// - `Self` - Tool result with `is_error == true`.
1290 pub fn error_text<T>(text: T) -> Self
1291 where
1292 T: Into<String>,
1293 {
1294 Self {
1295 content: vec![mcp_text_content(text.into())],
1296 is_error: true,
1297 }
1298 }
1299}
1300
1301/// Default construction for [`McpRegistry`].
1302impl Default for McpRegistry {
1303 /// Constructs a default [`McpRegistry`] value.
1304 fn default() -> Self {
1305 Self::new()
1306 }
1307}
1308
1309/// Inherent implementation of [`McpRegistry`].
1310impl McpRegistry {
1311 /// Creates an empty [`McpRegistry`] with a sharded session table.
1312 ///
1313 /// # Returns
1314 ///
1315 /// - `Self` - Ready MCP registry.
1316 pub fn new() -> Self {
1317 let shards: Arc<[McpSessionShard; MCP_SESSION_SHARD_COUNT]> =
1318 Arc::new(from_fn(|_: usize| McpSessionShard {
1319 map: RwLock::new(hash_map_xx_hash3_64()),
1320 }));
1321 Self {
1322 tools: hash_map_xx_hash3_64(),
1323 resources: hash_map_xx_hash3_64(),
1324 prompts: hash_map_xx_hash3_64(),
1325 tools_list_cache: Arc::new(OnceLock::new()),
1326 resources_list_cache: Arc::new(OnceLock::new()),
1327 prompts_list_cache: Arc::new(OnceLock::new()),
1328 session_shards: shards,
1329 session_count: Arc::new(AtomicUsize::new(0)),
1330 next_session_seq: Arc::new(AtomicU64::new(1)),
1331 session_seed: mcp_random_seed(),
1332 epoch: Instant::now(),
1333 }
1334 }
1335
1336 /// Registers an MCP tool and its async handler.
1337 ///
1338 /// # Arguments
1339 ///
1340 /// - `McpTool` - Tool metadata and JSON input schema.
1341 /// - `F` - Async handler invoked on `tools/call`.
1342 ///
1343 /// # Returns
1344 ///
1345 /// - `&mut Self` - This registry for fluent chaining.
1346 pub fn register_tool<F, Fut>(&mut self, meta: McpTool, handler: F) -> &mut Self
1347 where
1348 F: Fn(Value) -> Fut + Send + Sync + 'static,
1349 Fut: Future<Output = Result<McpToolResult, McpError>> + Send + 'static,
1350 {
1351 let Self {
1352 tools,
1353 tools_list_cache,
1354 ..
1355 } = self;
1356 let key: String = meta.get_name().clone();
1357 let boxed: McpToolHandler = Arc::new(move |args: Value| Box::pin(handler(args)));
1358 tools.insert(
1359 key,
1360 RegisteredTool {
1361 meta,
1362 handler: boxed,
1363 },
1364 );
1365 *tools_list_cache = Arc::new(OnceLock::new());
1366 self
1367 }
1368
1369 /// Registers an MCP resource and its async content reader.
1370 ///
1371 /// # Arguments
1372 ///
1373 /// - `McpResource` - Resource metadata.
1374 /// - `F` - Async handler invoked on `resources/read`.
1375 ///
1376 /// # Returns
1377 ///
1378 /// - `&mut Self` - This registry for fluent chaining.
1379 pub fn register_resource<F, Fut>(&mut self, meta: McpResource, handler: F) -> &mut Self
1380 where
1381 F: Fn(String) -> Fut + Send + Sync + 'static,
1382 Fut: Future<Output = Result<McpResourceContent, McpError>> + Send + 'static,
1383 {
1384 let Self {
1385 resources,
1386 resources_list_cache,
1387 ..
1388 } = self;
1389 let key: String = meta.get_uri().clone();
1390 let boxed: McpResourceHandler = Arc::new(move |uri: String| Box::pin(handler(uri)));
1391 resources.insert(
1392 key,
1393 RegisteredResource {
1394 meta,
1395 handler: boxed,
1396 },
1397 );
1398 *resources_list_cache = Arc::new(OnceLock::new());
1399 self
1400 }
1401
1402 /// Registers an MCP prompt template and its async renderer.
1403 ///
1404 /// # Arguments
1405 ///
1406 /// - `McpPrompt` - Prompt metadata and declared arguments.
1407 /// - `F` - Async handler invoked on `prompts/get`.
1408 ///
1409 /// # Returns
1410 ///
1411 /// - `&mut Self` - This registry for fluent chaining.
1412 pub fn register_prompt<F, Fut>(&mut self, meta: McpPrompt, handler: F) -> &mut Self
1413 where
1414 F: Fn(Value) -> Fut + Send + Sync + 'static,
1415 Fut: Future<Output = Result<Value, McpError>> + Send + 'static,
1416 {
1417 let Self {
1418 prompts,
1419 prompts_list_cache,
1420 ..
1421 } = self;
1422 let key: String = meta.get_name().clone();
1423 let boxed: McpPromptHandler = Arc::new(move |args: Value| Box::pin(handler(args)));
1424 prompts.insert(
1425 key,
1426 RegisteredPrompt {
1427 meta,
1428 handler: boxed,
1429 },
1430 );
1431 *prompts_list_cache = Arc::new(OnceLock::new());
1432 self
1433 }
1434
1435 /// Removes an active session identifier on `DELETE` teardown.
1436 ///
1437 /// # Arguments
1438 ///
1439 /// - `&str` - Session identifier from `Mcp-Session-Id`.
1440 ///
1441 /// # Returns
1442 ///
1443 /// - `bool` - `true` if the session existed and was terminated.
1444 #[inline]
1445 pub fn close_session(&self, session_id: &str) -> bool {
1446 let Self {
1447 session_shards,
1448 session_count,
1449 ..
1450 } = self;
1451 if session_count.load(Ordering::Relaxed) == 0 {
1452 return false;
1453 }
1454 let Some(key) = parse_mcp_session_key(session_id) else {
1455 return false;
1456 };
1457 let shard_idx: usize = mcp_session_shard_index(key);
1458 let removed: bool = session_shards[shard_idx]
1459 .map
1460 .write()
1461 .map(
1462 |mut map: RwLockWriteGuard<'_, HashMapXxHash3_64<u128, Instant>>| {
1463 map.remove(&key).is_some()
1464 },
1465 )
1466 .unwrap_or(false);
1467 if removed {
1468 session_count.fetch_sub(1, Ordering::Relaxed);
1469 }
1470 removed
1471 }
1472
1473 /// Returns the number of currently active MCP sessions in `O(1)` time without locking.
1474 ///
1475 /// # Returns
1476 ///
1477 /// - `usize` - Count of live sessions.
1478 #[inline(always)]
1479 pub fn session_count(&self) -> usize {
1480 let Self { session_count, .. } = self;
1481 session_count.load(Ordering::Relaxed)
1482 }
1483
1484 /// Evicts all sessions whose elapsed lifetime exceeds `ttl_ms`.
1485 ///
1486 /// # Arguments
1487 ///
1488 /// - `u64` - Session TTL in milliseconds (`0` disables expiration).
1489 ///
1490 /// # Returns
1491 ///
1492 /// - `usize` - Number of expired sessions removed.
1493 pub fn purge_expired_sessions(&self, ttl_ms: u64) -> usize {
1494 let Self {
1495 session_shards,
1496 session_count,
1497 ..
1498 } = self;
1499 if ttl_ms == 0 || session_count.load(Ordering::Relaxed) == 0 {
1500 return 0;
1501 }
1502 let ttl: Duration = Duration::from_millis(ttl_ms);
1503 let now: Instant = Instant::now();
1504 let mut evicted: usize = 0;
1505 for shard in session_shards.iter() {
1506 if let Ok(mut map) = shard.map.write() {
1507 if map.is_empty() {
1508 continue;
1509 }
1510 let before: usize = map.len();
1511 map.retain(|_: &u128, seen: &mut Instant| now.duration_since(*seen) <= ttl);
1512 evicted += before.saturating_sub(map.len());
1513 }
1514 }
1515 if evicted > 0 {
1516 session_count.fetch_sub(evicted, Ordering::Relaxed);
1517 }
1518 evicted
1519 }
1520
1521 /// Allocates and stores one new session id within `max_sessions`, reclaiming expired ones first.
1522 ///
1523 /// # Arguments
1524 ///
1525 /// - `usize` - Maximum allowed concurrent sessions.
1526 /// - `u64` - Session TTL in milliseconds (`0` disables expiration).
1527 ///
1528 /// # Returns
1529 ///
1530 /// - `Option<String>` - Newly created session identifier, or `None` when at capacity.
1531 fn create_session(&self, max_sessions: usize, ttl_ms: u64) -> Option<String> {
1532 let Self {
1533 session_shards,
1534 session_count,
1535 next_session_seq,
1536 session_seed,
1537 epoch,
1538 ..
1539 } = self;
1540 if session_count.load(Ordering::Relaxed) >= max_sessions && ttl_ms > 0 {
1541 let _: usize = self.purge_expired_sessions(ttl_ms);
1542 }
1543 let mut observed: usize = session_count.load(Ordering::Relaxed);
1544 loop {
1545 if observed >= max_sessions {
1546 return None;
1547 }
1548 match session_count.compare_exchange_weak(
1549 observed,
1550 observed + 1,
1551 Ordering::Relaxed,
1552 Ordering::Relaxed,
1553 ) {
1554 Ok(_) => break,
1555 Err(actual) => observed = actual,
1556 }
1557 }
1558 let seq: u64 = next_session_seq.fetch_add(1, Ordering::Relaxed);
1559 let now: Instant = Instant::now();
1560 let elapsed: Duration = now.saturating_duration_since(*epoch);
1561 let nanos: u64 = elapsed
1562 .as_secs()
1563 .wrapping_mul(1_000_000_000)
1564 .wrapping_add(u64::from(elapsed.subsec_nanos()));
1565 let (key, id): (u128, String) = mint_mcp_session_id(*session_seed, seq, nanos);
1566 let shard_idx: usize = mcp_session_shard_index(key);
1567 let Ok(mut map) = session_shards[shard_idx].map.write() else {
1568 session_count.fetch_sub(1, Ordering::Relaxed);
1569 return None;
1570 };
1571 map.insert(key, now);
1572 Some(id)
1573 }
1574
1575 /// Checks whether `session_id` is active and unexpired in this registry.
1576 ///
1577 /// # Arguments
1578 ///
1579 /// - `&str` - Session identifier to verify.
1580 /// - `u64` - Session TTL in milliseconds (`0` disables expiration).
1581 ///
1582 /// # Returns
1583 ///
1584 /// - `bool` - `true` when active and unexpired.
1585 #[inline]
1586 fn has_session(&self, session_id: &str, ttl_ms: u64) -> bool {
1587 let Self {
1588 session_shards,
1589 session_count,
1590 ..
1591 } = self;
1592 if session_count.load(Ordering::Relaxed) == 0 {
1593 return false;
1594 }
1595 let Some(key) = parse_mcp_session_key(session_id) else {
1596 return false;
1597 };
1598 let shard_idx: usize = mcp_session_shard_index(key);
1599 let seen_opt: Option<Instant> = session_shards[shard_idx].map.read().ok().and_then(
1600 |map: RwLockReadGuard<'_, HashMapXxHash3_64<u128, Instant>>| map.get(&key).copied(),
1601 );
1602 let Some(seen) = seen_opt else {
1603 return false;
1604 };
1605 if ttl_ms == 0 {
1606 return true;
1607 }
1608 let ttl: Duration = Duration::from_millis(ttl_ms);
1609 if Instant::now().duration_since(seen) <= ttl {
1610 return true;
1611 }
1612 if let Ok(mut map) = session_shards[shard_idx].map.write()
1613 && map.remove(&key).is_some()
1614 {
1615 session_count.fetch_sub(1, Ordering::Relaxed);
1616 }
1617 false
1618 }
1619
1620 /// Dispatches one raw MCP JSON-RPC 2.0 request body with session enforcement.
1621 ///
1622 /// # Arguments
1623 ///
1624 /// - `&[u8]` - Incoming JSON request bytes.
1625 /// - `Option<&str>` - Optional `Mcp-Session-Id` header value.
1626 /// - `&McpServerConfig` - Server metadata and session caps.
1627 ///
1628 /// # Returns
1629 ///
1630 /// - `McpDispatchOutcome` - Serialized JSON response, `202 Accepted`, or session error.
1631 pub async fn handle_json_bytes(
1632 &self,
1633 raw: &[u8],
1634 session_id: Option<&str>,
1635 config: &McpServerConfig,
1636 ) -> McpDispatchOutcome {
1637 let Self {
1638 tools,
1639 resources,
1640 prompts,
1641 tools_list_cache,
1642 resources_list_cache,
1643 prompts_list_cache,
1644 ..
1645 } = self;
1646 let parsed: McpRpcRequest<'_> = match from_slice(raw) {
1647 Ok(req) => req,
1648 Err(err) => {
1649 let code: i64 = if err.is_data() {
1650 MCP_ERR_INVALID_REQUEST
1651 } else {
1652 MCP_ERR_PARSE
1653 };
1654 let msg: &str = if err.is_data() {
1655 MSG_MCP_INVALID_REQUEST
1656 } else {
1657 MSG_MCP_PARSE_ERROR
1658 };
1659 return McpDispatchOutcome::Response {
1660 body: mcp_json_error(&McpRpcId::Null, code, msg),
1661 new_session_id: None,
1662 };
1663 }
1664 };
1665 let McpRpcRequest {
1666 jsonrpc,
1667 method: method_opt,
1668 id: id_opt,
1669 params,
1670 } = parsed;
1671 let version_ok: bool = jsonrpc.as_deref() == Some(MCP_JSONRPC_VERSION);
1672 let Some(method_cow) = method_opt else {
1673 let err_id: &McpRpcId<'_> = id_opt.as_ref().unwrap_or(&McpRpcId::Null);
1674 return McpDispatchOutcome::Response {
1675 body: mcp_json_error(err_id, MCP_ERR_INVALID_REQUEST, MSG_MCP_INVALID_REQUEST),
1676 new_session_id: None,
1677 };
1678 };
1679 let method: &str = method_cow.as_ref();
1680 if !version_ok {
1681 let err_id: &McpRpcId<'_> = id_opt.as_ref().unwrap_or(&McpRpcId::Null);
1682 return McpDispatchOutcome::Response {
1683 body: mcp_json_error(err_id, MCP_ERR_INVALID_REQUEST, MSG_MCP_INVALID_REQUEST),
1684 new_session_id: None,
1685 };
1686 }
1687 if method != METHOD_INITIALIZE
1688 && let Some(sid) = session_id
1689 && !self.has_session(sid, config.get_session_ttl_ms())
1690 {
1691 return McpDispatchOutcome::UnknownSession;
1692 }
1693 if method == METHOD_NOTIF_INITIALIZED {
1694 return McpDispatchOutcome::Accepted;
1695 }
1696 let Some(id) = id_opt else {
1697 return McpDispatchOutcome::Accepted;
1698 };
1699 match method {
1700 METHOD_INITIALIZE => {
1701 let Some(new_sid) =
1702 self.create_session(config.get_max_sessions(), config.get_session_ttl_ms())
1703 else {
1704 return McpDispatchOutcome::SessionLimitReached;
1705 };
1706 McpDispatchOutcome::Response {
1707 body: mcp_json_initialize(&id, config),
1708 new_session_id: Some(new_sid),
1709 }
1710 }
1711 METHOD_PING => McpDispatchOutcome::Response {
1712 body: mcp_json_ping(&id),
1713 new_session_id: None,
1714 },
1715 METHOD_TOOLS_LIST => {
1716 let cached: &[u8] = tools_list_cache.get_or_init(|| {
1717 let mut list: Vec<&McpTool> = Vec::with_capacity(tools.len());
1718 for item in tools.values() {
1719 list.push(&item.meta);
1720 }
1721 to_vec(&McpToolsListResult { tools: &list })
1722 .unwrap_or_default()
1723 .into_boxed_slice()
1724 });
1725 McpDispatchOutcome::Response {
1726 body: mcp_json_raw_result(&id, cached),
1727 new_session_id: None,
1728 }
1729 }
1730 METHOD_TOOLS_CALL => {
1731 let (name_cow, args_opt): (Cow<'_, str>, Option<Value>) = match params {
1732 McpParsedParams::Named {
1733 name: Some(name),
1734 arguments,
1735 } => (name, arguments),
1736 McpParsedParams::Raw(Value::Object(mut obj)) => {
1737 let Some(Value::String(name_owned)) = obj.remove(KEY_NAME) else {
1738 return McpDispatchOutcome::Response {
1739 body: mcp_json_error(
1740 &id,
1741 MCP_ERR_INVALID_PARAMS,
1742 MSG_MCP_INVALID_PARAMS,
1743 ),
1744 new_session_id: None,
1745 };
1746 };
1747 (Cow::Owned(name_owned), obj.remove(KEY_ARGUMENTS))
1748 }
1749 _ => {
1750 return McpDispatchOutcome::Response {
1751 body: mcp_json_error(
1752 &id,
1753 MCP_ERR_INVALID_PARAMS,
1754 MSG_MCP_INVALID_PARAMS,
1755 ),
1756 new_session_id: None,
1757 };
1758 }
1759 };
1760 let Some(entry) = tools.get(name_cow.as_ref()) else {
1761 return McpDispatchOutcome::Response {
1762 body: mcp_json_error(&id, MCP_ERR_METHOD_NOT_FOUND, MSG_MCP_UNKNOWN_TOOL),
1763 new_session_id: None,
1764 };
1765 };
1766 let args: Value = args_opt.unwrap_or_else(|| Value::Object(Map::new()));
1767 let body: Vec<u8> = match (entry.handler)(args).await {
1768 Ok(res) => mcp_json_success(&id, &res),
1769 Err(McpError::InvalidParams(msg)) => {
1770 mcp_json_error(&id, MCP_ERR_INVALID_PARAMS, &msg)
1771 }
1772 Err(McpError::NotFound(msg)) => {
1773 mcp_json_error(&id, MCP_ERR_METHOD_NOT_FOUND, &msg)
1774 }
1775 Err(McpError::Internal(msg)) => mcp_json_error(&id, MCP_ERR_INTERNAL, &msg),
1776 };
1777 McpDispatchOutcome::Response {
1778 body,
1779 new_session_id: None,
1780 }
1781 }
1782 METHOD_RESOURCES_LIST => {
1783 let cached: &[u8] = resources_list_cache.get_or_init(|| {
1784 let mut list: Vec<&McpResource> = Vec::with_capacity(resources.len());
1785 for item in resources.values() {
1786 list.push(&item.meta);
1787 }
1788 to_vec(&McpResourcesListResult { resources: &list })
1789 .unwrap_or_default()
1790 .into_boxed_slice()
1791 });
1792 McpDispatchOutcome::Response {
1793 body: mcp_json_raw_result(&id, cached),
1794 new_session_id: None,
1795 }
1796 }
1797 METHOD_RESOURCES_READ => {
1798 let uri_owned: String = match params {
1799 McpParsedParams::Uri { uri: Some(uri) } => uri,
1800 McpParsedParams::Raw(Value::Object(mut obj)) => {
1801 let Some(Value::String(uri)) = obj.remove(KEY_URI) else {
1802 return McpDispatchOutcome::Response {
1803 body: mcp_json_error(
1804 &id,
1805 MCP_ERR_INVALID_PARAMS,
1806 MSG_MCP_INVALID_PARAMS,
1807 ),
1808 new_session_id: None,
1809 };
1810 };
1811 uri
1812 }
1813 _ => {
1814 return McpDispatchOutcome::Response {
1815 body: mcp_json_error(
1816 &id,
1817 MCP_ERR_INVALID_PARAMS,
1818 MSG_MCP_INVALID_PARAMS,
1819 ),
1820 new_session_id: None,
1821 };
1822 }
1823 };
1824 let Some(entry) = resources.get(uri_owned.as_str()) else {
1825 return McpDispatchOutcome::Response {
1826 body: mcp_json_error(
1827 &id,
1828 MCP_ERR_METHOD_NOT_FOUND,
1829 MSG_MCP_UNKNOWN_RESOURCE,
1830 ),
1831 new_session_id: None,
1832 };
1833 };
1834 let body: Vec<u8> = match (entry.handler)(uri_owned).await {
1835 Ok(content) => mcp_json_success(
1836 &id,
1837 McpResourceReadResult {
1838 contents: [&content],
1839 },
1840 ),
1841 Err(McpError::InvalidParams(msg)) => {
1842 mcp_json_error(&id, MCP_ERR_INVALID_PARAMS, &msg)
1843 }
1844 Err(McpError::NotFound(msg)) => {
1845 mcp_json_error(&id, MCP_ERR_METHOD_NOT_FOUND, &msg)
1846 }
1847 Err(McpError::Internal(msg)) => mcp_json_error(&id, MCP_ERR_INTERNAL, &msg),
1848 };
1849 McpDispatchOutcome::Response {
1850 body,
1851 new_session_id: None,
1852 }
1853 }
1854 METHOD_PROMPTS_LIST => {
1855 let cached: &[u8] = prompts_list_cache.get_or_init(|| {
1856 let mut list: Vec<&McpPrompt> = Vec::with_capacity(prompts.len());
1857 for item in prompts.values() {
1858 list.push(&item.meta);
1859 }
1860 to_vec(&McpPromptsListResult { prompts: &list })
1861 .unwrap_or_default()
1862 .into_boxed_slice()
1863 });
1864 McpDispatchOutcome::Response {
1865 body: mcp_json_raw_result(&id, cached),
1866 new_session_id: None,
1867 }
1868 }
1869 METHOD_PROMPTS_GET => {
1870 let (name_cow, args_opt): (Cow<'_, str>, Option<Value>) = match params {
1871 McpParsedParams::Named {
1872 name: Some(name),
1873 arguments,
1874 } => (name, arguments),
1875 McpParsedParams::Raw(Value::Object(mut obj)) => {
1876 let Some(Value::String(name_owned)) = obj.remove(KEY_NAME) else {
1877 return McpDispatchOutcome::Response {
1878 body: mcp_json_error(
1879 &id,
1880 MCP_ERR_INVALID_PARAMS,
1881 MSG_MCP_INVALID_PARAMS,
1882 ),
1883 new_session_id: None,
1884 };
1885 };
1886 (Cow::Owned(name_owned), obj.remove(KEY_ARGUMENTS))
1887 }
1888 _ => {
1889 return McpDispatchOutcome::Response {
1890 body: mcp_json_error(
1891 &id,
1892 MCP_ERR_INVALID_PARAMS,
1893 MSG_MCP_INVALID_PARAMS,
1894 ),
1895 new_session_id: None,
1896 };
1897 }
1898 };
1899 let Some(entry) = prompts.get(name_cow.as_ref()) else {
1900 return McpDispatchOutcome::Response {
1901 body: mcp_json_error(&id, MCP_ERR_METHOD_NOT_FOUND, MSG_MCP_UNKNOWN_PROMPT),
1902 new_session_id: None,
1903 };
1904 };
1905 let args: Value = args_opt.unwrap_or_else(|| Value::Object(Map::new()));
1906 let body: Vec<u8> = match (entry.handler)(args).await {
1907 Ok(rendered) => mcp_json_success(&id, &rendered),
1908 Err(McpError::InvalidParams(msg)) => {
1909 mcp_json_error(&id, MCP_ERR_INVALID_PARAMS, &msg)
1910 }
1911 Err(McpError::NotFound(msg)) => {
1912 mcp_json_error(&id, MCP_ERR_METHOD_NOT_FOUND, &msg)
1913 }
1914 Err(McpError::Internal(msg)) => mcp_json_error(&id, MCP_ERR_INTERNAL, &msg),
1915 };
1916 McpDispatchOutcome::Response {
1917 body,
1918 new_session_id: None,
1919 }
1920 }
1921 _ => McpDispatchOutcome::Response {
1922 body: mcp_json_error(&id, MCP_ERR_METHOD_NOT_FOUND, MSG_MCP_METHOD_NOT_FOUND),
1923 new_session_id: None,
1924 },
1925 }
1926 }
1927}
1928
1929/// Inherent implementation of [`McpPlugin`].
1930impl McpPlugin {
1931 /// Initializes the global [`McpPlugin`] once with `config` and `registry`.
1932 ///
1933 /// # Arguments
1934 ///
1935 /// - `McpServerConfig` - MCP server settings and allowed origins.
1936 /// - `McpRegistry` - Tool, resource, and prompt registry.
1937 ///
1938 /// # Returns
1939 ///
1940 /// - `&'static Self` - Reference to the initialized global plugin.
1941 pub fn init(config: McpServerConfig, registry: McpRegistry) -> &'static Self {
1942 MCP_PLUGIN.get_or_init(|| Self { config, registry })
1943 }
1944
1945 /// Returns the initialized global [`McpPlugin`], if [`McpPlugin::init`] was called.
1946 ///
1947 /// # Returns
1948 ///
1949 /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
1950 #[inline(always)]
1951 pub fn get() -> Option<&'static Self> {
1952 MCP_PLUGIN.get()
1953 }
1954
1955 /// Returns the active [`McpServerConfig`].
1956 ///
1957 /// # Returns
1958 ///
1959 /// - `&McpServerConfig` - Active configuration.
1960 #[inline(always)]
1961 pub fn get_config(&self) -> &McpServerConfig {
1962 &self.config
1963 }
1964
1965 /// Returns the active [`McpRegistry`].
1966 ///
1967 /// # Returns
1968 ///
1969 /// - `&McpRegistry` - Registered tools, resources, prompts, and sessions.
1970 #[inline(always)]
1971 pub fn get_registry(&self) -> &McpRegistry {
1972 &self.registry
1973 }
1974}
1975
1976/// Implements [`ServerHook`] for [`McpHook`].
1977impl ServerHook for McpHook {
1978 /// Constructs a per-request [`McpHook`].
1979 ///
1980 /// # Arguments
1981 ///
1982 /// - `&mut Stream` - Connection stream.
1983 /// - `&mut Context` - Request context.
1984 ///
1985 /// # Returns
1986 ///
1987 /// - `Self` - Hook instance.
1988 #[inline(always)]
1989 async fn new(_: &mut Stream, _: &mut Context) -> Self {
1990 Self
1991 }
1992
1993 /// Handles MCP Streamable HTTP (`POST` and `DELETE`) requests on the configured endpoint.
1994 ///
1995 /// # Arguments
1996 ///
1997 /// - `Self` - Hook instance.
1998 /// - `&mut Stream` - Connection stream.
1999 /// - `&mut Context` - Request context.
2000 ///
2001 /// # Returns
2002 ///
2003 /// - `Status` - `Status::Continue` when unconfigured or path does not match; `Status::Reject` once answered.
2004 async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
2005 let Some(plugin) = McpPlugin::get() else {
2006 return Status::Continue;
2007 };
2008 let config: &McpServerConfig = plugin.get_config();
2009 let req: &Request = ctx.get_request();
2010 if req.get_path() != config.get_endpoint() {
2011 return Status::Continue;
2012 }
2013 let allowed_origins: &[String] = config.get_allowed_origins().as_slice();
2014 if !allowed_origins.is_empty()
2015 && !is_origin_allowed(request_header_back(req, ORIGIN), allowed_origins)
2016 {
2017 ctx.get_mut_response()
2018 .set_status_code(HttpStatus::Forbidden.code())
2019 .set_body(&[] as &[u8]);
2020 let wire: Vec<u8> = ctx.get_mut_response().build();
2021 let _: Result<(), ResponseError> = stream.try_send(&wire).await;
2022 return Status::Reject;
2023 }
2024 let session_id: Option<&str> = request_header_back(req, MCP_SESSION_ID_HEADER);
2025 if req.get_method().is_delete() {
2026 let closed: bool =
2027 session_id.is_some_and(|sid: &str| plugin.get_registry().close_session(sid));
2028 let code: usize = if closed {
2029 HttpStatus::NoContent.code()
2030 } else {
2031 HttpStatus::NotFound.code()
2032 };
2033 ctx.get_mut_response()
2034 .set_status_code(code)
2035 .set_body(&[] as &[u8]);
2036 let wire: Vec<u8> = ctx.get_mut_response().build();
2037 let _: Result<(), ResponseError> = stream.try_send(&wire).await;
2038 return Status::Reject;
2039 }
2040 if !req.get_method().is_post() {
2041 ctx.get_mut_response()
2042 .set_status_code(HttpStatus::MethodNotAllowed.code())
2043 .set_body(&[] as &[u8]);
2044 let wire: Vec<u8> = ctx.get_mut_response().build();
2045 let _: Result<(), ResponseError> = stream.try_send(&wire).await;
2046 return Status::Reject;
2047 }
2048 if req.get_body().len() > config.get_max_body_size() {
2049 ctx.get_mut_response()
2050 .set_status_code(HttpStatus::PayloadTooLarge.code())
2051 .set_body(&[] as &[u8]);
2052 let wire: Vec<u8> = ctx.get_mut_response().build();
2053 let _: Result<(), ResponseError> = stream.try_send(&wire).await;
2054 return Status::Reject;
2055 }
2056 let outcome: McpDispatchOutcome = plugin
2057 .get_registry()
2058 .handle_json_bytes(req.get_body(), session_id, config)
2059 .await;
2060 match outcome {
2061 McpDispatchOutcome::Response {
2062 body: resp_body,
2063 new_session_id,
2064 } => {
2065 ctx.get_mut_response()
2066 .set_status_code(HttpStatus::Ok.code())
2067 .set_header(CONTENT_TYPE, APPLICATION_JSON)
2068 .set_body(resp_body);
2069 if let Some(sid) = new_session_id {
2070 ctx.get_mut_response()
2071 .set_header(MCP_SESSION_ID_HEADER, sid);
2072 }
2073 }
2074 McpDispatchOutcome::Accepted => {
2075 ctx.get_mut_response()
2076 .set_status_code(HttpStatus::Accepted.code())
2077 .set_body(&[] as &[u8]);
2078 }
2079 McpDispatchOutcome::UnknownSession => {
2080 ctx.get_mut_response()
2081 .set_status_code(HttpStatus::NotFound.code())
2082 .set_body(&[] as &[u8]);
2083 }
2084 McpDispatchOutcome::SessionLimitReached => {
2085 ctx.get_mut_response()
2086 .set_status_code(HttpStatus::ServiceUnavailable.code())
2087 .set_header(CONTENT_TYPE, APPLICATION_JSON)
2088 .set_body(mcp_json_error(
2089 &McpRpcId::Null,
2090 MCP_ERR_INTERNAL,
2091 MSG_MCP_SESSION_LIMIT,
2092 ));
2093 }
2094 }
2095 let wire: Vec<u8> = ctx.get_mut_response().build();
2096 let _: Result<(), ResponseError> = stream.try_send(&wire).await;
2097 Status::Reject
2098 }
2099}