1use std::{borrow::Cow, collections::BTreeMap, fmt, sync::Arc, time::Duration};
7
8use base64::{Engine as _, engine::general_purpose::STANDARD};
9use rmcp::{
10 ErrorData, RoleServer, ServerHandler,
11 model::{
12 DiscoverResult, Implementation, ListResourceTemplatesResult, ListResourcesResult,
13 PaginatedRequestParams, ProtocolVersion, ReadResourceRequestParams, ReadResourceResponse,
14 ReadResourceResult, Resource, ResourceContents, ResourceTemplate, ResourcesCapability,
15 ServerCapabilities, ServerConfig,
16 },
17 service::RequestContext,
18};
19use serde_json::Value;
20use stateknot_core::{BoxFuture, Digest};
21use thiserror::Error;
22use tokio_util::sync::CancellationToken;
23
24use crate::{
25 McpServerApplicationOptions, McpServerCacheScope, McpServerInputRequired, McpServerPrincipal,
26 mcp_server_principal,
27 mcp_server_tool::{append_digest_part, validate_inbound_mrtr},
28};
29
30const MEBIBYTE: usize = 1024 * 1024;
31const MAX_URI_BYTES: usize = 4096;
32const MAX_NAME_BYTES: usize = 512;
33const MAX_DISPLAY_BYTES: usize = 16 * 1024;
34const MAX_SCOPE_COUNT: usize = 128;
35const MAX_SCOPE_BYTES: usize = 256;
36const MAX_CONTENTS: usize = 256;
37const MAX_TEXT_BYTES: usize = 4 * MEBIBYTE;
38const MAX_BINARY_BYTES: usize = 12 * MEBIBYTE;
39const MAX_RESULT_BYTES: usize = 32 * MEBIBYTE;
40
41#[derive(Clone, Debug)]
43pub struct McpServerResourceDefinition {
44 uri: Arc<str>,
45 name: Arc<str>,
46 title: Option<Arc<str>>,
47 description: Option<Arc<str>>,
48 mime_type: Option<Arc<str>>,
49 size: Option<u64>,
50 required_scopes: Arc<[Box<str>]>,
51}
52
53impl McpServerResourceDefinition {
54 pub fn new(
56 uri: impl Into<String>,
57 name: impl Into<String>,
58 ) -> Result<Self, McpServerResourceDefinitionError> {
59 let uri = uri.into();
60 let name = name.into();
61 validate_uri(&uri)?;
62 validate_name(&name)?;
63 Ok(Self {
64 uri: Arc::from(uri),
65 name: Arc::from(name),
66 title: None,
67 description: None,
68 mime_type: None,
69 size: None,
70 required_scopes: Arc::from([]),
71 })
72 }
73
74 pub fn with_title(
76 mut self,
77 value: impl Into<String>,
78 ) -> Result<Self, McpServerResourceDefinitionError> {
79 self.title = Some(Arc::from(validate_display(value.into())?));
80 Ok(self)
81 }
82
83 pub fn with_description(
85 mut self,
86 value: impl Into<String>,
87 ) -> Result<Self, McpServerResourceDefinitionError> {
88 self.description = Some(Arc::from(validate_display(value.into())?));
89 Ok(self)
90 }
91
92 pub fn with_mime_type(
94 mut self,
95 value: impl Into<String>,
96 ) -> Result<Self, McpServerResourceDefinitionError> {
97 self.mime_type = Some(Arc::from(validate_mime(value.into())?));
98 Ok(self)
99 }
100
101 #[must_use]
103 pub const fn with_size(mut self, value: u64) -> Self {
104 self.size = Some(value);
105 self
106 }
107
108 pub fn with_required_scopes(
110 mut self,
111 scopes: impl IntoIterator<Item = impl Into<String>>,
112 ) -> Result<Self, McpServerResourceDefinitionError> {
113 self.required_scopes = validate_scopes(scopes)?;
114 Ok(self)
115 }
116
117 #[must_use]
119 pub fn uri(&self) -> &str {
120 &self.uri
121 }
122
123 #[must_use]
125 pub fn name(&self) -> &str {
126 &self.name
127 }
128
129 pub fn required_scopes(&self) -> impl ExactSizeIterator<Item = &str> {
131 self.required_scopes.iter().map(AsRef::as_ref)
132 }
133
134 fn to_protocol(&self) -> Resource {
135 let mut resource = Resource::new(self.uri.to_string(), self.name.to_string());
136 resource.title = self.title.as_deref().map(str::to_owned);
137 resource.description = self.description.as_deref().map(str::to_owned);
138 resource.mime_type = self.mime_type.as_deref().map(str::to_owned);
139 resource.size = self.size;
140 resource
141 }
142}
143
144#[derive(Clone, Debug)]
146pub struct McpServerResourceTemplateDefinition {
147 uri_template: Arc<str>,
148 name: Arc<str>,
149 title: Option<Arc<str>>,
150 description: Option<Arc<str>>,
151 mime_type: Option<Arc<str>>,
152 required_scopes: Arc<[Box<str>]>,
153}
154
155impl McpServerResourceTemplateDefinition {
156 pub fn new(
158 uri_template: impl Into<String>,
159 name: impl Into<String>,
160 ) -> Result<Self, McpServerResourceDefinitionError> {
161 let uri_template = uri_template.into();
162 let name = name.into();
163 validate_uri_template(&uri_template)?;
164 validate_name(&name)?;
165 Ok(Self {
166 uri_template: Arc::from(uri_template),
167 name: Arc::from(name),
168 title: None,
169 description: None,
170 mime_type: None,
171 required_scopes: Arc::from([]),
172 })
173 }
174
175 pub fn with_title(
177 mut self,
178 value: impl Into<String>,
179 ) -> Result<Self, McpServerResourceDefinitionError> {
180 self.title = Some(Arc::from(validate_display(value.into())?));
181 Ok(self)
182 }
183
184 pub fn with_description(
186 mut self,
187 value: impl Into<String>,
188 ) -> Result<Self, McpServerResourceDefinitionError> {
189 self.description = Some(Arc::from(validate_display(value.into())?));
190 Ok(self)
191 }
192
193 pub fn with_mime_type(
195 mut self,
196 value: impl Into<String>,
197 ) -> Result<Self, McpServerResourceDefinitionError> {
198 self.mime_type = Some(Arc::from(validate_mime(value.into())?));
199 Ok(self)
200 }
201
202 pub fn with_required_scopes(
204 mut self,
205 scopes: impl IntoIterator<Item = impl Into<String>>,
206 ) -> Result<Self, McpServerResourceDefinitionError> {
207 self.required_scopes = validate_scopes(scopes)?;
208 Ok(self)
209 }
210
211 #[must_use]
213 pub fn uri_template(&self) -> &str {
214 &self.uri_template
215 }
216
217 pub fn required_scopes(&self) -> impl ExactSizeIterator<Item = &str> {
219 self.required_scopes.iter().map(AsRef::as_ref)
220 }
221
222 fn to_protocol(&self) -> ResourceTemplate {
223 let mut template =
224 ResourceTemplate::new(self.uri_template.to_string(), self.name.to_string());
225 template.title = self.title.as_deref().map(str::to_owned);
226 template.description = self.description.as_deref().map(str::to_owned);
227 template.mime_type = self.mime_type.as_deref().map(str::to_owned);
228 template
229 }
230}
231
232#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
234#[non_exhaustive]
235pub enum McpServerResourceDefinitionError {
236 #[error("invalid MCP resource URI")]
238 InvalidUri,
239 #[error("invalid MCP resource URI template")]
241 InvalidUriTemplate,
242 #[error("invalid MCP resource name")]
244 InvalidName,
245 #[error("invalid MCP resource display text")]
247 InvalidDisplayText,
248 #[error("invalid MCP resource MIME type")]
250 InvalidMimeType,
251 #[error("too many required MCP resource scopes")]
253 TooManyScopes,
254 #[error("invalid required MCP resource scope")]
256 InvalidScope,
257 #[error("duplicate required MCP resource scope")]
259 DuplicateScope,
260}
261
262fn validate_uri(value: &str) -> Result<(), McpServerResourceDefinitionError> {
263 if value.is_empty()
264 || value.len() > MAX_URI_BYTES
265 || value.chars().any(char::is_control)
266 || value
267 .parse::<http::Uri>()
268 .map_or(true, |uri| uri.scheme().is_none())
269 {
270 return Err(McpServerResourceDefinitionError::InvalidUri);
271 }
272 Ok(())
273}
274
275fn validate_uri_template(value: &str) -> Result<(), McpServerResourceDefinitionError> {
276 if value.is_empty()
277 || value.len() > MAX_URI_BYTES
278 || value.chars().any(char::is_control)
279 || !value.contains('{')
280 {
281 return Err(McpServerResourceDefinitionError::InvalidUriTemplate);
282 }
283 let prefix = value.split('{').next().unwrap_or_default();
284 if prefix
285 .parse::<http::Uri>()
286 .map_or(true, |uri| uri.scheme().is_none())
287 {
288 return Err(McpServerResourceDefinitionError::InvalidUriTemplate);
289 }
290 let mut inside = false;
291 let mut expression_len = 0_usize;
292 for character in value.chars() {
293 match character {
294 '{' if !inside => {
295 inside = true;
296 expression_len = 0;
297 }
298 '}' if inside && expression_len > 0 => inside = false,
299 '{' | '}' => return Err(McpServerResourceDefinitionError::InvalidUriTemplate),
300 _ if inside => {
301 if !(character.is_ascii_alphanumeric()
302 || matches!(
303 character,
304 '_' | '.' | ',' | ':' | '*' | '+' | '#' | '/' | ';' | '?' | '&' | '%'
305 ))
306 {
307 return Err(McpServerResourceDefinitionError::InvalidUriTemplate);
308 }
309 expression_len += 1;
310 }
311 _ => {}
312 }
313 }
314 if inside {
315 return Err(McpServerResourceDefinitionError::InvalidUriTemplate);
316 }
317 Ok(())
318}
319
320fn validate_name(value: &str) -> Result<(), McpServerResourceDefinitionError> {
321 if value.is_empty()
322 || value.len() > MAX_NAME_BYTES
323 || value.trim() != value
324 || value.chars().any(char::is_control)
325 {
326 return Err(McpServerResourceDefinitionError::InvalidName);
327 }
328 Ok(())
329}
330
331fn validate_display(value: String) -> Result<String, McpServerResourceDefinitionError> {
332 if value.is_empty()
333 || value.len() > MAX_DISPLAY_BYTES
334 || value.trim() != value
335 || value.chars().any(char::is_control)
336 {
337 return Err(McpServerResourceDefinitionError::InvalidDisplayText);
338 }
339 Ok(value)
340}
341
342fn validate_mime(value: String) -> Result<String, McpServerResourceDefinitionError> {
343 if value.len() > 255 || value.trim() != value || value.parse::<mime::Mime>().is_err() {
344 return Err(McpServerResourceDefinitionError::InvalidMimeType);
345 }
346 Ok(value)
347}
348
349fn validate_scopes(
350 scopes: impl IntoIterator<Item = impl Into<String>>,
351) -> Result<Arc<[Box<str>]>, McpServerResourceDefinitionError> {
352 let mut scopes = scopes.into_iter().map(Into::into).collect::<Vec<_>>();
353 if scopes.len() > MAX_SCOPE_COUNT {
354 return Err(McpServerResourceDefinitionError::TooManyScopes);
355 }
356 if scopes.iter().any(|scope| {
357 scope.is_empty()
358 || scope.len() > MAX_SCOPE_BYTES
359 || scope
360 .bytes()
361 .any(|byte| !matches!(byte, b'!' | b'#'..=b'[' | b']'..=b'~'))
362 }) {
363 return Err(McpServerResourceDefinitionError::InvalidScope);
364 }
365 scopes.sort_unstable();
366 if scopes.windows(2).any(|pair| pair[0] == pair[1]) {
367 return Err(McpServerResourceDefinitionError::DuplicateScope);
368 }
369 Ok(scopes
370 .into_iter()
371 .map(String::into_boxed_str)
372 .collect::<Vec<_>>()
373 .into())
374}
375
376#[derive(Clone, Copy, Debug, Eq, PartialEq)]
378pub struct McpServerResourceCatalogLimits {
379 maximum_resources: usize,
380 maximum_templates: usize,
381}
382
383impl McpServerResourceCatalogLimits {
384 pub const HARD_MAXIMUM_ENTRIES: usize = 4096;
386
387 pub const fn new(
389 maximum_resources: usize,
390 maximum_templates: usize,
391 ) -> Result<Self, McpServerResourceCatalogLimitsError> {
392 if maximum_resources == 0 || maximum_templates == 0 {
393 return Err(McpServerResourceCatalogLimitsError::ZeroLimit);
394 }
395 if maximum_resources > Self::HARD_MAXIMUM_ENTRIES
396 || maximum_templates > Self::HARD_MAXIMUM_ENTRIES
397 {
398 return Err(McpServerResourceCatalogLimitsError::AboveHardMaximum);
399 }
400 Ok(Self {
401 maximum_resources,
402 maximum_templates,
403 })
404 }
405}
406
407impl Default for McpServerResourceCatalogLimits {
408 fn default() -> Self {
409 Self {
410 maximum_resources: 1024,
411 maximum_templates: 1024,
412 }
413 }
414}
415
416#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
418#[non_exhaustive]
419pub enum McpServerResourceCatalogLimitsError {
420 #[error("MCP resource catalog limits must be positive")]
422 ZeroLimit,
423 #[error("MCP resource catalog limit exceeds the hard maximum")]
425 AboveHardMaximum,
426}
427
428#[derive(Debug)]
430pub struct McpServerResourceCatalogBuilder {
431 limits: McpServerResourceCatalogLimits,
432 resources: BTreeMap<String, McpServerResourceDefinition>,
433 templates: BTreeMap<String, McpServerResourceTemplateDefinition>,
434}
435
436impl McpServerResourceCatalogBuilder {
437 #[must_use]
439 pub fn new(limits: McpServerResourceCatalogLimits) -> Self {
440 Self {
441 limits,
442 resources: BTreeMap::new(),
443 templates: BTreeMap::new(),
444 }
445 }
446
447 pub fn register_resource(
449 &mut self,
450 definition: McpServerResourceDefinition,
451 ) -> Result<(), McpServerResourceCatalogError> {
452 if self.resources.len() == self.limits.maximum_resources {
453 return Err(McpServerResourceCatalogError::TooManyResources);
454 }
455 if self.resources.contains_key(definition.uri()) {
456 return Err(McpServerResourceCatalogError::DuplicateResource);
457 }
458 self.resources
459 .insert(definition.uri().to_owned(), definition);
460 Ok(())
461 }
462
463 pub fn register_template(
465 &mut self,
466 definition: McpServerResourceTemplateDefinition,
467 ) -> Result<(), McpServerResourceCatalogError> {
468 if self.templates.len() == self.limits.maximum_templates {
469 return Err(McpServerResourceCatalogError::TooManyTemplates);
470 }
471 if self.templates.contains_key(definition.uri_template()) {
472 return Err(McpServerResourceCatalogError::DuplicateTemplate);
473 }
474 self.templates
475 .insert(definition.uri_template().to_owned(), definition);
476 Ok(())
477 }
478
479 pub fn build(self) -> Result<McpServerResourceCatalog, McpServerResourceCatalogError> {
481 if self.resources.is_empty() && self.templates.is_empty() {
482 return Err(McpServerResourceCatalogError::Empty);
483 }
484 let mut digest_material = Vec::new();
485 for definition in self.resources.values() {
486 append_digest_part(&mut digest_material, definition.uri().as_bytes());
487 append_digest_part(&mut digest_material, definition.name().as_bytes());
488 }
489 for definition in self.templates.values() {
490 append_digest_part(&mut digest_material, definition.uri_template().as_bytes());
491 }
492 let digest = Digest::sha256(digest_material).to_string();
493 Ok(McpServerResourceCatalog {
494 inner: Arc::new(McpServerResourceCatalogInner {
495 resources: self.resources,
496 templates: self.templates,
497 digest: Arc::from(
498 digest
499 .strip_prefix("sha256:")
500 .expect("StateKnot SHA-256 digest has stable prefix"),
501 ),
502 }),
503 })
504 }
505}
506
507impl Default for McpServerResourceCatalogBuilder {
508 fn default() -> Self {
509 Self::new(McpServerResourceCatalogLimits::default())
510 }
511}
512
513#[derive(Clone)]
515pub struct McpServerResourceCatalog {
516 inner: Arc<McpServerResourceCatalogInner>,
517}
518
519struct McpServerResourceCatalogInner {
520 resources: BTreeMap<String, McpServerResourceDefinition>,
521 templates: BTreeMap<String, McpServerResourceTemplateDefinition>,
522 digest: Arc<str>,
523}
524
525impl McpServerResourceCatalog {
526 #[must_use]
528 pub fn get(&self, uri: &str) -> Option<&McpServerResourceDefinition> {
529 self.inner.resources.get(uri)
530 }
531
532 #[must_use]
534 pub fn resource_count(&self) -> usize {
535 self.inner.resources.len()
536 }
537
538 #[must_use]
540 pub fn template_count(&self) -> usize {
541 self.inner.templates.len()
542 }
543
544 fn contains_scoped_entries(&self) -> bool {
545 self.inner
546 .resources
547 .values()
548 .any(|value| !value.required_scopes.is_empty())
549 || self
550 .inner
551 .templates
552 .values()
553 .any(|value| !value.required_scopes.is_empty())
554 }
555}
556
557impl fmt::Debug for McpServerResourceCatalog {
558 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
559 formatter
560 .debug_struct("McpServerResourceCatalog")
561 .field("resources", &self.resource_count())
562 .field("templates", &self.template_count())
563 .field("catalog_digest", &self.inner.digest)
564 .finish()
565 }
566}
567
568#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
570#[non_exhaustive]
571pub enum McpServerResourceCatalogError {
572 #[error("MCP resource catalog is empty")]
574 Empty,
575 #[error("duplicate MCP resource URI")]
577 DuplicateResource,
578 #[error("duplicate MCP resource template")]
580 DuplicateTemplate,
581 #[error("too many MCP resources")]
583 TooManyResources,
584 #[error("too many MCP resource templates")]
586 TooManyTemplates,
587}
588
589#[derive(Clone, Debug)]
591pub struct McpServerResourceContent {
592 inner: ResourceContents,
593 wire_bytes: usize,
594}
595
596impl McpServerResourceContent {
597 pub fn text(
599 uri: impl Into<String>,
600 mime_type: Option<impl Into<String>>,
601 text: impl Into<String>,
602 ) -> Result<Self, McpServerResourceContentError> {
603 let uri = uri.into();
604 let text = text.into();
605 validate_content_uri(&uri)?;
606 if text.len() > MAX_TEXT_BYTES {
607 return Err(McpServerResourceContentError::TooLarge);
608 }
609 let mime_type = mime_type
610 .map(Into::into)
611 .map(validate_content_mime)
612 .transpose()?;
613 Self::from_protocol(ResourceContents::TextResourceContents {
614 uri,
615 mime_type,
616 text,
617 meta: None,
618 })
619 }
620
621 pub fn blob(
623 uri: impl Into<String>,
624 mime_type: Option<impl Into<String>>,
625 bytes: impl AsRef<[u8]>,
626 ) -> Result<Self, McpServerResourceContentError> {
627 let uri = uri.into();
628 validate_content_uri(&uri)?;
629 let bytes = bytes.as_ref();
630 if bytes.len() > MAX_BINARY_BYTES {
631 return Err(McpServerResourceContentError::TooLarge);
632 }
633 let mime_type = mime_type
634 .map(Into::into)
635 .map(validate_content_mime)
636 .transpose()?;
637 Self::from_protocol(ResourceContents::BlobResourceContents {
638 uri,
639 mime_type,
640 blob: STANDARD.encode(bytes),
641 meta: None,
642 })
643 }
644
645 pub fn try_from_protocol_json(value: Value) -> Result<Self, McpServerResourceContentError> {
647 if canonical_len(&value).map_or(true, |bytes| bytes > MAX_RESULT_BYTES) {
648 return Err(McpServerResourceContentError::TooLarge);
649 }
650 let inner =
651 serde_json::from_value(value).map_err(|_| McpServerResourceContentError::Invalid)?;
652 Self::from_protocol(inner)
653 }
654
655 fn from_protocol(inner: ResourceContents) -> Result<Self, McpServerResourceContentError> {
656 match &inner {
657 ResourceContents::TextResourceContents {
658 uri,
659 mime_type,
660 text,
661 ..
662 } => {
663 validate_content_uri(uri)?;
664 if text.len() > MAX_TEXT_BYTES {
665 return Err(McpServerResourceContentError::TooLarge);
666 }
667 if let Some(mime_type) = mime_type {
668 validate_content_mime(mime_type.clone())?;
669 }
670 }
671 ResourceContents::BlobResourceContents {
672 uri,
673 mime_type,
674 blob,
675 ..
676 } => {
677 validate_content_uri(uri)?;
678 if let Some(mime_type) = mime_type {
679 validate_content_mime(mime_type.clone())?;
680 }
681 let decoded = STANDARD
682 .decode(blob)
683 .map_err(|_| McpServerResourceContentError::Invalid)?;
684 if decoded.len() > MAX_BINARY_BYTES {
685 return Err(McpServerResourceContentError::TooLarge);
686 }
687 }
688 _ => return Err(McpServerResourceContentError::Invalid),
689 }
690 let value =
691 serde_json::to_value(&inner).map_err(|_| McpServerResourceContentError::Invalid)?;
692 let wire_bytes =
693 canonical_len(&value).map_err(|_| McpServerResourceContentError::Invalid)?;
694 Ok(Self { inner, wire_bytes })
695 }
696}
697
698#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
700#[non_exhaustive]
701pub enum McpServerResourceContentError {
702 #[error("invalid MCP resource content")]
704 Invalid,
705 #[error("MCP resource content is too large")]
707 TooLarge,
708}
709
710fn validate_content_uri(value: &str) -> Result<(), McpServerResourceContentError> {
711 validate_uri(value).map_err(|_| McpServerResourceContentError::Invalid)
712}
713
714fn validate_content_mime(value: String) -> Result<String, McpServerResourceContentError> {
715 validate_mime(value).map_err(|_| McpServerResourceContentError::Invalid)
716}
717
718#[derive(Clone, Debug)]
720pub struct McpServerResourceResult {
721 contents: Arc<[McpServerResourceContent]>,
722 ttl_ms: u64,
723 cache_scope: McpServerCacheScope,
724}
725
726impl McpServerResourceResult {
727 pub fn new(
729 contents: impl IntoIterator<Item = McpServerResourceContent>,
730 cache_ttl: Duration,
731 cache_scope: McpServerCacheScope,
732 ) -> Result<Self, McpServerResourceResultError> {
733 let contents = contents.into_iter().collect::<Vec<_>>();
734 if contents.is_empty() {
735 return Err(McpServerResourceResultError::Empty);
736 }
737 if contents.len() > MAX_CONTENTS {
738 return Err(McpServerResourceResultError::TooManyContents);
739 }
740 if contents
741 .iter()
742 .try_fold(0_usize, |total, item| total.checked_add(item.wire_bytes))
743 .is_none_or(|total| total > MAX_RESULT_BYTES)
744 {
745 return Err(McpServerResourceResultError::TooLarge);
746 }
747 if cache_ttl > McpServerApplicationOptions::HARD_MAXIMUM_CACHE_TTL {
748 return Err(McpServerResourceResultError::InvalidCacheTtl);
749 }
750 let ttl_ms = u64::try_from(cache_ttl.as_millis())
751 .map_err(|_| McpServerResourceResultError::InvalidCacheTtl)?;
752 Ok(Self {
753 contents: contents.into(),
754 ttl_ms,
755 cache_scope,
756 })
757 }
758
759 fn into_protocol(self) -> ReadResourceResult {
760 ReadResourceResult::new(
761 self.contents
762 .iter()
763 .map(|value| value.inner.clone())
764 .collect(),
765 )
766 .with_ttl_ms(self.ttl_ms)
767 .with_cache_scope(self.cache_scope.into())
768 }
769}
770
771#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
773#[non_exhaustive]
774pub enum McpServerResourceResultError {
775 #[error("MCP resource result is empty")]
777 Empty,
778 #[error("too many MCP resource contents")]
780 TooManyContents,
781 #[error("MCP resource result is too large")]
783 TooLarge,
784 #[error("invalid MCP resource cache TTL")]
786 InvalidCacheTtl,
787}
788
789#[derive(Clone, Debug)]
791#[non_exhaustive]
792pub enum McpServerResourceOutcome {
793 Complete(McpServerResourceResult),
795 InputRequired(McpServerInputRequired),
797}
798
799impl From<McpServerResourceResult> for McpServerResourceOutcome {
800 fn from(value: McpServerResourceResult) -> Self {
801 Self::Complete(value)
802 }
803}
804
805impl From<McpServerInputRequired> for McpServerResourceOutcome {
806 fn from(value: McpServerInputRequired) -> Self {
807 Self::InputRequired(value)
808 }
809}
810
811#[derive(Clone, Debug)]
813pub struct McpServerResourceRead {
814 uri: Arc<str>,
815 input_responses: Arc<BTreeMap<String, Value>>,
816 request_state: Option<Arc<str>>,
817}
818
819impl McpServerResourceRead {
820 #[must_use]
822 pub fn uri(&self) -> &str {
823 &self.uri
824 }
825
826 #[must_use]
828 pub fn input_responses(&self) -> &BTreeMap<String, Value> {
829 &self.input_responses
830 }
831
832 #[must_use]
834 pub fn request_state(&self) -> Option<&str> {
835 self.request_state.as_deref()
836 }
837}
838
839#[derive(Clone, Debug)]
841pub struct McpServerResourceContext {
842 principal: McpServerPrincipal,
843 client_capabilities: Arc<Value>,
844 cancellation: CancellationToken,
845 request_state_binding: Arc<[u8]>,
846}
847
848impl McpServerResourceContext {
849 #[must_use]
851 pub const fn principal(&self) -> &McpServerPrincipal {
852 &self.principal
853 }
854
855 #[must_use]
857 pub fn client_capabilities(&self) -> &Value {
858 &self.client_capabilities
859 }
860
861 #[must_use]
863 pub fn request_state_binding(&self) -> &[u8] {
864 &self.request_state_binding
865 }
866
867 #[must_use]
869 pub fn is_cancelled(&self) -> bool {
870 self.cancellation.is_cancelled()
871 }
872
873 pub async fn cancelled(&self) {
875 self.cancellation.cancelled().await;
876 }
877}
878
879pub trait McpServerResourceReader: Send + Sync + 'static {
881 fn read(
883 &self,
884 request: McpServerResourceRead,
885 context: McpServerResourceContext,
886 ) -> BoxFuture<'_, Result<McpServerResourceOutcome, McpServerResourceReaderError>>;
887}
888
889#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
891#[non_exhaustive]
892pub enum McpServerResourceReaderError {
893 #[error("MCP resource was not found")]
895 NotFound,
896 #[error("MCP resource dependency is unavailable")]
898 Unavailable,
899 #[error("MCP resource read failed internally")]
901 Internal,
902 #[error("MCP resource read was cancelled")]
904 Cancelled,
905}
906
907#[derive(Clone, Debug)]
909pub struct McpServerResourceAuthorizationRequest {
910 principal: McpServerPrincipal,
911 request: McpServerResourceRead,
912 exact_definition: Option<McpServerResourceDefinition>,
913}
914
915impl McpServerResourceAuthorizationRequest {
916 #[must_use]
918 pub const fn principal(&self) -> &McpServerPrincipal {
919 &self.principal
920 }
921
922 #[must_use]
924 pub const fn request(&self) -> &McpServerResourceRead {
925 &self.request
926 }
927
928 #[must_use]
930 pub const fn exact_definition(&self) -> Option<&McpServerResourceDefinition> {
931 self.exact_definition.as_ref()
932 }
933}
934
935pub trait McpServerResourceAuthorization: Send + Sync + 'static {
937 fn authorize(
939 &self,
940 request: McpServerResourceAuthorizationRequest,
941 ) -> BoxFuture<'_, Result<(), McpServerResourceAuthorizationError>>;
942}
943
944#[derive(Clone, Copy, Debug, Default)]
946pub struct AllowMcpServerResourceAuthorization;
947
948impl McpServerResourceAuthorization for AllowMcpServerResourceAuthorization {
949 fn authorize(
950 &self,
951 _request: McpServerResourceAuthorizationRequest,
952 ) -> BoxFuture<'_, Result<(), McpServerResourceAuthorizationError>> {
953 Box::pin(async { Ok(()) })
954 }
955}
956
957#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
959#[non_exhaustive]
960pub enum McpServerResourceAuthorizationError {
961 #[error("MCP resource read is forbidden")]
963 Forbidden,
964 #[error("MCP resource authorization is unavailable")]
966 Unavailable,
967}
968
969#[derive(Clone)]
972pub struct McpServerResourceService {
973 catalog: McpServerResourceCatalog,
974 options: McpServerApplicationOptions,
975 reader: Arc<dyn McpServerResourceReader>,
976 authorization: Arc<dyn McpServerResourceAuthorization>,
977}
978
979impl McpServerResourceService {
980 pub fn new<R, A>(
982 catalog: McpServerResourceCatalog,
983 options: McpServerApplicationOptions,
984 reader: R,
985 authorization: A,
986 ) -> Result<Self, McpServerResourceServiceBuildError>
987 where
988 R: McpServerResourceReader,
989 A: McpServerResourceAuthorization,
990 {
991 Self::with_shared(catalog, options, Arc::new(reader), Arc::new(authorization))
992 }
993
994 pub fn with_shared(
996 catalog: McpServerResourceCatalog,
997 options: McpServerApplicationOptions,
998 reader: Arc<dyn McpServerResourceReader>,
999 authorization: Arc<dyn McpServerResourceAuthorization>,
1000 ) -> Result<Self, McpServerResourceServiceBuildError> {
1001 if catalog.contains_scoped_entries()
1002 && matches!(options.cache_scope, McpServerCacheScope::Public)
1003 {
1004 return Err(McpServerResourceServiceBuildError::PublicCacheWithScopedEntries);
1005 }
1006 Ok(Self {
1007 catalog,
1008 options,
1009 reader,
1010 authorization,
1011 })
1012 }
1013
1014 pub(crate) fn contains_resource(&self, uri: &str) -> bool {
1015 self.catalog.get(uri).is_some()
1016 }
1017
1018 fn scope_tag(&self, principal: &McpServerPrincipal) -> String {
1019 if matches!(self.options.cache_scope, McpServerCacheScope::Public) {
1020 return "public".to_owned();
1021 }
1022 let mut material = principal.subject().as_bytes().to_vec();
1023 for scope in principal.scopes() {
1024 append_digest_part(&mut material, scope.as_bytes());
1025 }
1026 digest_hex(material)
1027 }
1028
1029 fn page_cursor(&self, kind: &str, scope: &str, offset: usize) -> String {
1030 format!(
1031 "v1.{kind}.{}.{}.{}",
1032 self.catalog.inner.digest, scope, offset
1033 )
1034 }
1035
1036 fn parse_cursor(&self, cursor: &str, kind: &str, scope: &str) -> Result<usize, ErrorData> {
1037 if cursor.len() > 224 {
1038 return Err(invalid_cursor());
1039 }
1040 let mut parts = cursor.split('.');
1041 let valid = parts.next() == Some("v1")
1042 && parts.next() == Some(kind)
1043 && parts.next() == Some(self.catalog.inner.digest.as_ref())
1044 && parts.next() == Some(scope);
1045 let offset = parts.next().and_then(|value| value.parse().ok());
1046 if !valid || offset.is_none() || parts.next().is_some() {
1047 return Err(invalid_cursor());
1048 }
1049 Ok(offset.expect("validated cursor offset exists"))
1050 }
1051
1052 fn resources_page(
1053 &self,
1054 principal: &McpServerPrincipal,
1055 cursor: Option<&str>,
1056 ) -> Result<(Vec<Resource>, Option<String>), ErrorData> {
1057 let scope = self.scope_tag(principal);
1058 let visible = self
1059 .catalog
1060 .inner
1061 .resources
1062 .values()
1063 .filter(|definition| {
1064 definition
1065 .required_scopes()
1066 .all(|required| principal.has_scope(required))
1067 })
1068 .collect::<Vec<_>>();
1069 let start = cursor.map_or(Ok(0), |value| self.parse_cursor(value, "resources", &scope))?;
1070 if start > visible.len() {
1071 return Err(invalid_cursor());
1072 }
1073 let end = start
1074 .saturating_add(self.options.page_size)
1075 .min(visible.len());
1076 let values = visible[start..end]
1077 .iter()
1078 .map(|value| value.to_protocol())
1079 .collect();
1080 let next = (end < visible.len()).then(|| self.page_cursor("resources", &scope, end));
1081 Ok((values, next))
1082 }
1083
1084 fn templates_page(
1085 &self,
1086 principal: &McpServerPrincipal,
1087 cursor: Option<&str>,
1088 ) -> Result<(Vec<ResourceTemplate>, Option<String>), ErrorData> {
1089 let scope = self.scope_tag(principal);
1090 let visible = self
1091 .catalog
1092 .inner
1093 .templates
1094 .values()
1095 .filter(|definition| {
1096 definition
1097 .required_scopes()
1098 .all(|required| principal.has_scope(required))
1099 })
1100 .collect::<Vec<_>>();
1101 let start = cursor.map_or(Ok(0), |value| self.parse_cursor(value, "templates", &scope))?;
1102 if start > visible.len() {
1103 return Err(invalid_cursor());
1104 }
1105 let end = start
1106 .saturating_add(self.options.page_size)
1107 .min(visible.len());
1108 let values = visible[start..end]
1109 .iter()
1110 .map(|value| value.to_protocol())
1111 .collect();
1112 let next = (end < visible.len()).then(|| self.page_cursor("templates", &scope, end));
1113 Ok((values, next))
1114 }
1115
1116 async fn dispatch(
1117 &self,
1118 request: ReadResourceRequestParams,
1119 context: RequestContext<RoleServer>,
1120 ) -> Result<ReadResourceResponse, ErrorData> {
1121 validate_uri(&request.uri).map_err(|_| resource_not_found())?;
1122 let principal = mcp_server_principal(&context)
1123 .cloned()
1124 .ok_or_else(|| ErrorData::internal_error("MCP server boundary is missing", None))?;
1125 let exact = self.catalog.get(&request.uri).cloned();
1126 if exact.as_ref().is_some_and(|definition| {
1127 definition
1128 .required_scopes()
1129 .any(|scope| !principal.has_scope(scope))
1130 }) {
1131 return Err(resource_not_found());
1132 }
1133 let input_responses = request.input_responses.unwrap_or_default();
1134 validate_inbound_mrtr(&input_responses, request.request_state.as_deref())?;
1135 let read = McpServerResourceRead {
1136 uri: Arc::from(request.uri),
1137 input_responses: Arc::new(input_responses),
1138 request_state: request.request_state.map(Arc::from),
1139 };
1140 let authorization = McpServerResourceAuthorizationRequest {
1141 principal: principal.clone(),
1142 request: read.clone(),
1143 exact_definition: exact,
1144 };
1145 match self.authorization.authorize(authorization).await {
1146 Ok(()) => {}
1147 Err(McpServerResourceAuthorizationError::Forbidden) => {
1148 return Err(resource_not_found());
1149 }
1150 Err(McpServerResourceAuthorizationError::Unavailable) => {
1151 return Err(ErrorData::internal_error(
1152 "MCP resource authorization is unavailable",
1153 None,
1154 ));
1155 }
1156 }
1157 let execution_context = resource_context(&context, principal, read.uri())?;
1158 match self.reader.read(read, execution_context).await {
1159 Ok(McpServerResourceOutcome::Complete(result)) => Ok(result.into_protocol().into()),
1160 Ok(McpServerResourceOutcome::InputRequired(result)) => {
1161 Ok(result.into_protocol().into())
1162 }
1163 Err(McpServerResourceReaderError::NotFound) => Err(resource_not_found()),
1164 Err(McpServerResourceReaderError::Unavailable) => Err(ErrorData::internal_error(
1165 "MCP resource dependency is unavailable",
1166 None,
1167 )),
1168 Err(McpServerResourceReaderError::Internal) => {
1169 Err(ErrorData::internal_error("MCP resource read failed", None))
1170 }
1171 Err(McpServerResourceReaderError::Cancelled) => Err(ErrorData::internal_error(
1172 "MCP resource read was cancelled",
1173 None,
1174 )),
1175 }
1176 }
1177}
1178
1179impl fmt::Debug for McpServerResourceService {
1180 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1181 formatter
1182 .debug_struct("McpServerResourceService")
1183 .field("catalog", &self.catalog)
1184 .field("options", &self.options)
1185 .field("reader", &"[READER]")
1186 .field("authorization", &"[POLICY]")
1187 .finish_non_exhaustive()
1188 }
1189}
1190
1191impl ServerHandler for McpServerResourceService {
1192 fn supported_protocol_versions(&self) -> Cow<'static, [ProtocolVersion]> {
1193 Cow::Borrowed(&[ProtocolVersion::V_2026_07_28])
1194 }
1195
1196 fn get_info(&self) -> ServerConfig {
1197 let mut capabilities = ServerCapabilities::default();
1198 capabilities.resources = Some(ResourcesCapability::default());
1199 let mut info = ServerConfig::new(capabilities).with_server_info(Implementation::new(
1200 self.options.server_name.to_string(),
1201 self.options.server_version.to_string(),
1202 ));
1203 if let Some(instructions) = &self.options.instructions {
1204 info = info.with_instructions(instructions.to_string());
1205 }
1206 info
1207 }
1208
1209 async fn discover(
1210 &self,
1211 _context: RequestContext<RoleServer>,
1212 ) -> Result<DiscoverResult, ErrorData> {
1213 Ok(
1214 DiscoverResult::from_server_info(vec![ProtocolVersion::V_2026_07_28], self.get_info())
1215 .with_ttl_ms(self.options.cache_ttl_ms)
1216 .with_cache_scope(self.options.cache_scope.into()),
1217 )
1218 }
1219
1220 async fn list_resources(
1221 &self,
1222 request: Option<PaginatedRequestParams>,
1223 context: RequestContext<RoleServer>,
1224 ) -> Result<ListResourcesResult, ErrorData> {
1225 let principal = mcp_server_principal(&context)
1226 .ok_or_else(|| ErrorData::internal_error("MCP server boundary is missing", None))?;
1227 let (resources, next_cursor) = self.resources_page(
1228 principal,
1229 request.as_ref().and_then(|value| value.cursor.as_deref()),
1230 )?;
1231 let mut result = ListResourcesResult::with_all_items(resources)
1232 .with_ttl_ms(self.options.cache_ttl_ms)
1233 .with_cache_scope(self.options.cache_scope.into());
1234 result.next_cursor = next_cursor;
1235 Ok(result)
1236 }
1237
1238 async fn list_resource_templates(
1239 &self,
1240 request: Option<PaginatedRequestParams>,
1241 context: RequestContext<RoleServer>,
1242 ) -> Result<ListResourceTemplatesResult, ErrorData> {
1243 let principal = mcp_server_principal(&context)
1244 .ok_or_else(|| ErrorData::internal_error("MCP server boundary is missing", None))?;
1245 let (templates, next_cursor) = self.templates_page(
1246 principal,
1247 request.as_ref().and_then(|value| value.cursor.as_deref()),
1248 )?;
1249 let mut result = ListResourceTemplatesResult::with_all_items(templates)
1250 .with_ttl_ms(self.options.cache_ttl_ms)
1251 .with_cache_scope(self.options.cache_scope.into());
1252 result.next_cursor = next_cursor;
1253 Ok(result)
1254 }
1255
1256 async fn read_resource(
1257 &self,
1258 request: ReadResourceRequestParams,
1259 context: RequestContext<RoleServer>,
1260 ) -> Result<ReadResourceResponse, ErrorData> {
1261 self.dispatch(request, context).await
1262 }
1263}
1264
1265#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
1267#[non_exhaustive]
1268pub enum McpServerResourceServiceBuildError {
1269 #[error("scope-restricted MCP resources require a private catalog cache")]
1271 PublicCacheWithScopedEntries,
1272}
1273
1274fn resource_context(
1275 context: &RequestContext<RoleServer>,
1276 principal: McpServerPrincipal,
1277 uri: &str,
1278) -> Result<McpServerResourceContext, ErrorData> {
1279 let capabilities = serde_json::to_value(context.client_capabilities().unwrap_or_default())
1280 .map_err(|_| ErrorData::internal_error("Failed to retain client capabilities", None))?;
1281 let mut binding = b"stateknot/mcp-server/request-state/resource/v1".to_vec();
1282 append_digest_part(&mut binding, principal.subject().as_bytes());
1283 append_digest_part(&mut binding, uri.as_bytes());
1284 Ok(McpServerResourceContext {
1285 principal,
1286 client_capabilities: Arc::new(capabilities),
1287 cancellation: context.ct.clone(),
1288 request_state_binding: Digest::sha256(binding).as_bytes().to_vec().into(),
1289 })
1290}
1291
1292fn digest_hex(value: impl AsRef<[u8]>) -> String {
1293 let digest = Digest::sha256(value).to_string();
1294 digest
1295 .strip_prefix("sha256:")
1296 .expect("StateKnot SHA-256 digest has stable prefix")
1297 .to_owned()
1298}
1299
1300fn invalid_cursor() -> ErrorData {
1301 ErrorData::invalid_params("Invalid resource catalog cursor", None)
1302}
1303
1304fn resource_not_found() -> ErrorData {
1305 ErrorData::resource_not_found("Resource not found or unavailable", None)
1306}
1307
1308fn canonical_len(value: &Value) -> Result<usize, serde_json::Error> {
1309 serde_json_canonicalizer::to_vec(value).map(|bytes| bytes.len())
1310}
1311
1312#[cfg(test)]
1313mod tests {
1314 use std::sync::atomic::{AtomicUsize, Ordering};
1315
1316 use bytes::Bytes;
1317 use http::{Request, StatusCode};
1318 use http_body_util::{BodyExt as _, Full};
1319 use serde_json::json;
1320 use tower_service::Service as _;
1321
1322 use super::*;
1323 use crate::{McpServerAuthentication, McpServerHttpOptions, McpServerHttpService};
1324
1325 #[derive(Clone)]
1326 struct StaticReader {
1327 calls: Arc<AtomicUsize>,
1328 }
1329
1330 impl McpServerResourceReader for StaticReader {
1331 fn read(
1332 &self,
1333 request: McpServerResourceRead,
1334 execution_context: McpServerResourceContext,
1335 ) -> BoxFuture<'_, Result<McpServerResourceOutcome, McpServerResourceReaderError>> {
1336 self.calls.fetch_add(1, Ordering::SeqCst);
1337 let uri = request.uri().to_owned();
1338 let subject = execution_context.principal().subject().to_owned();
1339 Box::pin(async move {
1340 let item = McpServerResourceContent::text(
1341 uri,
1342 Some("text/plain"),
1343 format!("hello {subject}"),
1344 )
1345 .map_err(|_| McpServerResourceReaderError::Internal)?;
1346 McpServerResourceResult::new(
1347 [item],
1348 Duration::from_secs(60),
1349 McpServerCacheScope::Private,
1350 )
1351 .map(Into::into)
1352 .map_err(|_| McpServerResourceReaderError::Internal)
1353 })
1354 }
1355 }
1356
1357 fn service(calls: &Arc<AtomicUsize>) -> McpServerHttpService<McpServerResourceService> {
1358 let mut builder = McpServerResourceCatalogBuilder::default();
1359 builder
1360 .register_resource(McpServerResourceDefinition::new("test://alpha", "Alpha").unwrap())
1361 .unwrap();
1362 builder
1363 .register_template(
1364 McpServerResourceTemplateDefinition::new("test://items/{id}", "Item").unwrap(),
1365 )
1366 .unwrap();
1367 let options = McpServerApplicationOptions::new(
1368 "stateknot-resource-test",
1369 "0.0.0",
1370 1,
1371 Duration::from_secs(60),
1372 McpServerCacheScope::Private,
1373 )
1374 .unwrap();
1375 let handler = McpServerResourceService::new(
1376 builder.build().unwrap(),
1377 options,
1378 StaticReader {
1379 calls: calls.clone(),
1380 },
1381 AllowMcpServerResourceAuthorization,
1382 )
1383 .unwrap();
1384 McpServerHttpService::new(
1385 handler,
1386 McpServerHttpOptions::loopback(32125).unwrap(),
1387 McpServerAuthentication::anonymous_loopback(),
1388 )
1389 .unwrap()
1390 }
1391
1392 fn request(method: &str, mut params: Value) -> Request<Full<Bytes>> {
1393 let name = params.get("uri").and_then(Value::as_str).map(str::to_owned);
1394 params.as_object_mut().unwrap().insert(
1395 "_meta".to_owned(),
1396 json!({
1397 "io.modelcontextprotocol/protocolVersion": "2026-07-28",
1398 "io.modelcontextprotocol/clientInfo": { "name": "test", "version": "0" },
1399 "io.modelcontextprotocol/clientCapabilities": {}
1400 }),
1401 );
1402 let body = serde_json::to_vec(&json!({
1403 "jsonrpc": "2.0", "id": 1, "method": method, "params": params
1404 }))
1405 .unwrap();
1406 let mut builder = Request::builder()
1407 .method("POST")
1408 .uri("http://127.0.0.1:32125/mcp")
1409 .header("host", "127.0.0.1:32125")
1410 .header("origin", "http://127.0.0.1:32125")
1411 .header("content-type", "application/json")
1412 .header("accept", "application/json, text/event-stream")
1413 .header("mcp-protocol-version", "2026-07-28")
1414 .header("mcp-method", method);
1415 if let Some(name) = name {
1416 builder = builder.header("mcp-name", name);
1417 }
1418 builder.body(Full::new(Bytes::from(body))).unwrap()
1419 }
1420
1421 async fn invoke(
1422 service: &mut McpServerHttpService<McpServerResourceService>,
1423 method: &str,
1424 params: Value,
1425 ) -> (StatusCode, Value) {
1426 let response = service.call(request(method, params)).await.unwrap();
1427 let status = response.status();
1428 let bytes = response.into_body().collect().await.unwrap().to_bytes();
1429 (status, serde_json::from_slice(&bytes).unwrap())
1430 }
1431
1432 #[test]
1433 fn catalog_rejects_duplicates_and_malformed_templates() {
1434 assert!(matches!(
1435 McpServerResourceTemplateDefinition::new("relative/{id}", "bad"),
1436 Err(McpServerResourceDefinitionError::InvalidUriTemplate)
1437 ));
1438 let mut builder = McpServerResourceCatalogBuilder::default();
1439 let resource = McpServerResourceDefinition::new("test://same", "Same").unwrap();
1440 builder.register_resource(resource.clone()).unwrap();
1441 assert!(matches!(
1442 builder.register_resource(resource),
1443 Err(McpServerResourceCatalogError::DuplicateResource)
1444 ));
1445 }
1446
1447 #[tokio::test]
1448 async fn resource_catalog_and_reads_pass_through_the_http_boundary() {
1449 let calls = Arc::new(AtomicUsize::new(0));
1450 let mut service = service(&calls);
1451 let (status, listed) = invoke(&mut service, "resources/list", json!({})).await;
1452 assert_eq!(status, StatusCode::OK);
1453 assert_eq!(
1454 listed.pointer("/result/resources/0/uri"),
1455 Some(&json!("test://alpha"))
1456 );
1457 let (status, read) = invoke(
1458 &mut service,
1459 "resources/read",
1460 json!({ "uri": "test://alpha" }),
1461 )
1462 .await;
1463 assert_eq!(status, StatusCode::OK);
1464 assert_eq!(
1465 read.pointer("/result/contents/0/text"),
1466 Some(&json!("hello anonymous"))
1467 );
1468 assert_eq!(calls.load(Ordering::SeqCst), 1);
1469 }
1470}