1use std::{
12 borrow::Cow,
13 cell::Cell,
14 collections::{BTreeMap, BTreeSet},
15 fmt,
16 rc::Rc,
17 sync::Arc,
18};
19
20use base64::{Engine as _, engine::general_purpose::STANDARD};
21use rmcp::{
22 ErrorData, RoleServer, ServerHandler,
23 model::{
24 CustomRequest, CustomResult, DiscoverResult, ExtensionCapabilities, Implementation,
25 ListResourceTemplatesResult, ListResourcesResult, PaginatedRequestParams, ProtocolVersion,
26 ReadResourceRequestParams, ReadResourceResponse, ReadResourceResult, Resource,
27 ResourceContents, ResourcesCapability, ServerCapabilities, ServerConfig,
28 },
29 service::RequestContext,
30};
31use serde::{
32 Deserialize, Deserializer,
33 de::{self, DeserializeSeed, MapAccess, SeqAccess, Visitor},
34};
35use serde_json::{Map, Value, json};
36use stateknot_core::{BoxFuture, Digest};
37use thiserror::Error;
38
39use crate::{
40 McpServerApplicationOptions, McpServerCacheScope, McpServerPrincipal, mcp_server_principal,
41 mcp_server_tool::append_digest_part,
42};
43
44pub const MCP_SKILLS_EXTENSION_ID: &str = "io.modelcontextprotocol/skills";
46
47const SKILL_LIST_METHOD: &str = "skills/list";
48const SKILL_GET_METHOD: &str = "skills/get";
49const SKILL_DOCUMENT: &str = "SKILL.md";
50const MEBIBYTE: usize = 1024 * 1024;
51const MAX_URI_BYTES: usize = 4096;
52const MAX_RELATIVE_PATH_BYTES: usize = 4096;
53const MAX_FRONTMATTER_BYTES: usize = 64 * 1024;
54const MAX_SCOPE_COUNT: usize = 128;
55const MAX_SCOPE_BYTES: usize = 256;
56
57#[derive(Clone)]
59pub struct McpServerSkillFile {
60 relative_path: Arc<str>,
61 mime_type: Arc<str>,
62 bytes: Arc<[u8]>,
63 representation: McpServerSkillFileRepresentation,
64 digest: Arc<str>,
65}
66
67#[derive(Clone, Copy, Debug, Eq, PartialEq)]
68enum McpServerSkillFileRepresentation {
69 Text,
70 Binary,
71}
72
73impl McpServerSkillFile {
74 pub fn text(
76 relative_path: impl Into<String>,
77 mime_type: impl Into<String>,
78 text: impl Into<String>,
79 ) -> Result<Self, McpServerSkillFileError> {
80 let text = text.into();
81 Self::new(
82 relative_path.into(),
83 mime_type.into(),
84 Arc::<[u8]>::from(text.into_bytes()),
85 McpServerSkillFileRepresentation::Text,
86 )
87 }
88
89 pub fn binary(
91 relative_path: impl Into<String>,
92 mime_type: impl Into<String>,
93 bytes: impl Into<Vec<u8>>,
94 ) -> Result<Self, McpServerSkillFileError> {
95 Self::new(
96 relative_path.into(),
97 mime_type.into(),
98 Arc::<[u8]>::from(bytes.into()),
99 McpServerSkillFileRepresentation::Binary,
100 )
101 }
102
103 fn new(
104 relative_path: String,
105 mime_type: String,
106 bytes: Arc<[u8]>,
107 representation: McpServerSkillFileRepresentation,
108 ) -> Result<Self, McpServerSkillFileError> {
109 validate_relative_path(&relative_path)?;
110 if mime_type.is_empty()
111 || mime_type.len() > 255
112 || mime_type.trim() != mime_type
113 || mime_type.parse::<mime::Mime>().is_err()
114 {
115 return Err(McpServerSkillFileError::InvalidMimeType);
116 }
117 if bytes.len() > McpServerSkillDefinition::HARD_MAXIMUM_BYTES {
118 return Err(McpServerSkillFileError::TooLarge);
119 }
120 if matches!(representation, McpServerSkillFileRepresentation::Text)
121 && std::str::from_utf8(&bytes).is_err()
122 {
123 return Err(McpServerSkillFileError::InvalidUtf8);
124 }
125 let digest = Digest::sha256(&bytes).to_string();
126 Ok(Self {
127 relative_path: Arc::from(relative_path),
128 mime_type: Arc::from(mime_type),
129 bytes,
130 representation,
131 digest: Arc::from(digest),
132 })
133 }
134
135 #[must_use]
137 pub fn relative_path(&self) -> &str {
138 &self.relative_path
139 }
140
141 #[must_use]
143 pub fn mime_type(&self) -> &str {
144 &self.mime_type
145 }
146
147 #[must_use]
149 pub fn size(&self) -> usize {
150 self.bytes.len()
151 }
152
153 #[must_use]
155 pub fn digest(&self) -> &str {
156 &self.digest
157 }
158}
159
160impl fmt::Debug for McpServerSkillFile {
161 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
162 formatter
163 .debug_struct("McpServerSkillFile")
164 .field("relative_path", &self.relative_path)
165 .field("mime_type", &self.mime_type)
166 .field("size", &self.bytes.len())
167 .field("digest", &self.digest)
168 .finish_non_exhaustive()
169 }
170}
171
172#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
174#[non_exhaustive]
175pub enum McpServerSkillFileError {
176 #[error("invalid MCP Skill relative path")]
178 InvalidRelativePath,
179 #[error("invalid MCP Skill file MIME type")]
181 InvalidMimeType,
182 #[error("MCP Skill text file is not UTF-8")]
184 InvalidUtf8,
185 #[error("MCP Skill file is too large")]
187 TooLarge,
188}
189
190#[derive(Clone)]
192pub struct McpServerSkillDefinition {
193 uri: Arc<str>,
194 name: Arc<str>,
195 description: Arc<str>,
196 frontmatter: Arc<Map<String, Value>>,
197 files: Arc<BTreeMap<String, McpServerSkillFile>>,
198 required_scopes: Arc<[Box<str>]>,
199 total_bytes: usize,
200}
201
202impl McpServerSkillDefinition {
203 pub const HARD_MAXIMUM_FILES: usize = 512;
205 pub const HARD_MAXIMUM_BYTES: usize = 16 * MEBIBYTE;
207
208 pub fn new(
210 uri: impl Into<String>,
211 files: impl IntoIterator<Item = McpServerSkillFile>,
212 ) -> Result<Self, McpServerSkillDefinitionError> {
213 let uri = uri.into();
214 let uri_parent = validate_skill_uri(&uri)?;
215 let mut by_path = BTreeMap::new();
216 let mut total_bytes = 0_usize;
217 for file in files {
218 if by_path.len() == Self::HARD_MAXIMUM_FILES {
219 return Err(McpServerSkillDefinitionError::TooManyFiles);
220 }
221 total_bytes = total_bytes
222 .checked_add(file.bytes.len())
223 .ok_or(McpServerSkillDefinitionError::TooLarge)?;
224 if total_bytes > Self::HARD_MAXIMUM_BYTES {
225 return Err(McpServerSkillDefinitionError::TooLarge);
226 }
227 if by_path
228 .insert(file.relative_path.to_string(), file)
229 .is_some()
230 {
231 return Err(McpServerSkillDefinitionError::DuplicateFile);
232 }
233 }
234 if by_path.is_empty() {
235 return Err(McpServerSkillDefinitionError::Empty);
236 }
237 let skill_document = by_path
238 .get(SKILL_DOCUMENT)
239 .ok_or(McpServerSkillDefinitionError::MissingSkillDocument)?;
240 if !matches!(
241 skill_document.representation,
242 McpServerSkillFileRepresentation::Text
243 ) {
244 return Err(McpServerSkillDefinitionError::SkillDocumentNotText);
245 }
246 let text = std::str::from_utf8(&skill_document.bytes)
247 .map_err(|_| McpServerSkillDefinitionError::SkillDocumentNotText)?;
248 let frontmatter = parse_frontmatter(text)?;
249 validate_frontmatter(&frontmatter)?;
250 let name = frontmatter
251 .get("name")
252 .and_then(Value::as_str)
253 .expect("validated Skill frontmatter has a name");
254 if name != uri_parent {
255 return Err(McpServerSkillDefinitionError::NameUriMismatch);
256 }
257 let description = frontmatter
258 .get("description")
259 .and_then(Value::as_str)
260 .expect("validated Skill frontmatter has a description");
261 for relative_path in by_path.keys() {
262 resource_uri(&uri, relative_path)?;
263 }
264 Ok(Self {
265 uri: Arc::from(uri),
266 name: Arc::from(name),
267 description: Arc::from(description),
268 frontmatter: Arc::new(frontmatter),
269 files: Arc::new(by_path),
270 required_scopes: Arc::from([]),
271 total_bytes,
272 })
273 }
274
275 pub fn with_required_scopes(
277 mut self,
278 scopes: impl IntoIterator<Item = impl Into<String>>,
279 ) -> Result<Self, McpServerSkillDefinitionError> {
280 self.required_scopes = validate_scopes(scopes)?;
281 Ok(self)
282 }
283
284 #[must_use]
286 pub fn uri(&self) -> &str {
287 &self.uri
288 }
289
290 #[must_use]
292 pub fn name(&self) -> &str {
293 &self.name
294 }
295
296 #[must_use]
298 pub fn description(&self) -> &str {
299 &self.description
300 }
301
302 #[must_use]
304 pub fn frontmatter(&self) -> &Map<String, Value> {
305 &self.frontmatter
306 }
307
308 pub fn files(&self) -> impl ExactSizeIterator<Item = &McpServerSkillFile> {
310 self.files.values()
311 }
312
313 pub fn required_scopes(&self) -> impl ExactSizeIterator<Item = &str> {
315 self.required_scopes.iter().map(AsRef::as_ref)
316 }
317
318 fn has_required_scopes(&self, principal: &McpServerPrincipal) -> bool {
319 self.required_scopes()
320 .all(|scope| principal.has_scope(scope))
321 }
322
323 fn to_wire(&self) -> Value {
324 let resources = self
325 .files
326 .values()
327 .map(|file| {
328 json!({
329 "uri": resource_uri(&self.uri, file.relative_path())
330 .expect("validated Skill paths always produce valid URIs"),
331 "digest": file.digest(),
332 "size": file.size(),
333 })
334 })
335 .collect::<Vec<_>>();
336 json!({
337 "uri": self.uri(),
338 "frontmatter": self.frontmatter(),
339 "resources": resources,
340 })
341 }
342}
343
344impl fmt::Debug for McpServerSkillDefinition {
345 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
346 formatter
347 .debug_struct("McpServerSkillDefinition")
348 .field("uri", &self.uri)
349 .field("name", &self.name)
350 .field("files", &self.files.len())
351 .field("total_bytes", &self.total_bytes)
352 .field("required_scopes", &self.required_scopes)
353 .finish_non_exhaustive()
354 }
355}
356
357#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
359#[non_exhaustive]
360pub enum McpServerSkillDefinitionError {
361 #[error("invalid MCP Skill URI")]
363 InvalidUri,
364 #[error("MCP Skill has no files")]
366 Empty,
367 #[error("MCP Skill is missing SKILL.md")]
369 MissingSkillDocument,
370 #[error("MCP Skill SKILL.md is not text")]
372 SkillDocumentNotText,
373 #[error("duplicate MCP Skill file")]
375 DuplicateFile,
376 #[error("too many MCP Skill files")]
378 TooManyFiles,
379 #[error("MCP Skill exceeds the byte ceiling")]
381 TooLarge,
382 #[error("invalid MCP Skill frontmatter")]
384 InvalidFrontmatter,
385 #[error("invalid MCP Skill frontmatter field")]
387 InvalidFrontmatterField,
388 #[error("MCP Skill URI parent does not match its name")]
390 NameUriMismatch,
391 #[error("too many MCP Skill scopes")]
393 TooManyScopes,
394 #[error("invalid MCP Skill scope")]
396 InvalidScope,
397 #[error("duplicate MCP Skill scope")]
399 DuplicateScope,
400}
401
402#[derive(Clone, Copy, Debug, Eq, PartialEq)]
404pub struct McpServerSkillCatalogLimits {
405 skills: usize,
406 files: usize,
407 bytes: usize,
408}
409
410impl McpServerSkillCatalogLimits {
411 pub const HARD_MAXIMUM_SKILLS: usize = 4096;
413 pub const HARD_MAXIMUM_FILES: usize = 65_536;
415 pub const HARD_MAXIMUM_BYTES: usize = 1024 * MEBIBYTE;
417
418 pub const fn new(
420 maximum_skills: usize,
421 maximum_files: usize,
422 maximum_bytes: usize,
423 ) -> Result<Self, McpServerSkillCatalogLimitsError> {
424 if maximum_skills == 0 || maximum_files == 0 || maximum_bytes == 0 {
425 return Err(McpServerSkillCatalogLimitsError::ZeroLimit);
426 }
427 if maximum_skills > Self::HARD_MAXIMUM_SKILLS
428 || maximum_files > Self::HARD_MAXIMUM_FILES
429 || maximum_bytes > Self::HARD_MAXIMUM_BYTES
430 {
431 return Err(McpServerSkillCatalogLimitsError::AboveHardMaximum);
432 }
433 Ok(Self {
434 skills: maximum_skills,
435 files: maximum_files,
436 bytes: maximum_bytes,
437 })
438 }
439}
440
441impl Default for McpServerSkillCatalogLimits {
442 fn default() -> Self {
443 Self {
444 skills: 256,
445 files: 4096,
446 bytes: 64 * MEBIBYTE,
447 }
448 }
449}
450
451#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
453#[non_exhaustive]
454pub enum McpServerSkillCatalogLimitsError {
455 #[error("MCP Skill catalog limits must be positive")]
457 ZeroLimit,
458 #[error("MCP Skill catalog limit exceeds the hard maximum")]
460 AboveHardMaximum,
461}
462
463#[derive(Debug)]
465pub struct McpServerSkillCatalogBuilder {
466 limits: McpServerSkillCatalogLimits,
467 skills: BTreeMap<String, McpServerSkillDefinition>,
468 resource_uris: BTreeSet<String>,
469 total_files: usize,
470 total_bytes: usize,
471}
472
473impl McpServerSkillCatalogBuilder {
474 #[must_use]
476 pub fn new(limits: McpServerSkillCatalogLimits) -> Self {
477 Self {
478 limits,
479 skills: BTreeMap::new(),
480 resource_uris: BTreeSet::new(),
481 total_files: 0,
482 total_bytes: 0,
483 }
484 }
485
486 pub fn register(
488 &mut self,
489 definition: McpServerSkillDefinition,
490 ) -> Result<(), McpServerSkillCatalogError> {
491 if self.skills.len() == self.limits.skills {
492 return Err(McpServerSkillCatalogError::TooManySkills);
493 }
494 if self.skills.contains_key(definition.uri()) {
495 return Err(McpServerSkillCatalogError::DuplicateSkill);
496 }
497 let file_count = definition.files.len();
498 let next_files = self
499 .total_files
500 .checked_add(file_count)
501 .ok_or(McpServerSkillCatalogError::TooManyFiles)?;
502 if next_files > self.limits.files {
503 return Err(McpServerSkillCatalogError::TooManyFiles);
504 }
505 let next_bytes = self
506 .total_bytes
507 .checked_add(definition.total_bytes)
508 .ok_or(McpServerSkillCatalogError::TooLarge)?;
509 if next_bytes > self.limits.bytes {
510 return Err(McpServerSkillCatalogError::TooLarge);
511 }
512 let uris = definition
513 .files
514 .keys()
515 .map(|path| {
516 resource_uri(definition.uri(), path)
517 .expect("validated Skill paths always produce valid URIs")
518 })
519 .collect::<Vec<_>>();
520 if uris.iter().any(|uri| self.resource_uris.contains(uri)) {
521 return Err(McpServerSkillCatalogError::DuplicateResource);
522 }
523 self.resource_uris.extend(uris);
524 self.total_files = next_files;
525 self.total_bytes = next_bytes;
526 self.skills.insert(definition.uri().to_owned(), definition);
527 Ok(())
528 }
529
530 pub fn build(self) -> Result<McpServerSkillCatalog, McpServerSkillCatalogError> {
532 if self.skills.is_empty() {
533 return Err(McpServerSkillCatalogError::Empty);
534 }
535 let mut digest_material = b"stateknot/mcp-skills/catalog/v1".to_vec();
536 let mut resources = BTreeMap::new();
537 for definition in self.skills.values() {
538 append_digest_part(&mut digest_material, definition.uri().as_bytes());
539 for file in definition.files.values() {
540 let uri = resource_uri(definition.uri(), file.relative_path())
541 .expect("validated Skill paths always produce valid URIs");
542 append_digest_part(&mut digest_material, uri.as_bytes());
543 append_digest_part(&mut digest_material, file.digest().as_bytes());
544 resources.insert(
545 uri,
546 McpServerSkillResourceBinding {
547 skill_uri: definition.uri.clone(),
548 file: file.clone(),
549 },
550 );
551 }
552 }
553 let digest = digest_hex(digest_material);
554 Ok(McpServerSkillCatalog {
555 inner: Arc::new(McpServerSkillCatalogInner {
556 skills: self.skills,
557 resources,
558 digest: Arc::from(digest),
559 total_files: self.total_files,
560 total_bytes: self.total_bytes,
561 }),
562 })
563 }
564}
565
566impl Default for McpServerSkillCatalogBuilder {
567 fn default() -> Self {
568 Self::new(McpServerSkillCatalogLimits::default())
569 }
570}
571
572#[derive(Clone)]
574pub struct McpServerSkillCatalog {
575 inner: Arc<McpServerSkillCatalogInner>,
576}
577
578struct McpServerSkillCatalogInner {
579 skills: BTreeMap<String, McpServerSkillDefinition>,
580 resources: BTreeMap<String, McpServerSkillResourceBinding>,
581 digest: Arc<str>,
582 total_files: usize,
583 total_bytes: usize,
584}
585
586#[derive(Clone)]
587struct McpServerSkillResourceBinding {
588 skill_uri: Arc<str>,
589 file: McpServerSkillFile,
590}
591
592impl McpServerSkillCatalog {
593 #[must_use]
595 pub fn get(&self, uri: &str) -> Option<&McpServerSkillDefinition> {
596 self.inner.skills.get(uri)
597 }
598
599 #[must_use]
601 pub fn skill_count(&self) -> usize {
602 self.inner.skills.len()
603 }
604
605 #[must_use]
607 pub fn file_count(&self) -> usize {
608 self.inner.total_files
609 }
610
611 #[must_use]
613 pub fn byte_count(&self) -> usize {
614 self.inner.total_bytes
615 }
616
617 pub(crate) fn contains_resource(&self, uri: &str) -> bool {
618 self.inner.resources.contains_key(uri)
619 }
620
621 fn contains_scoped_skills(&self) -> bool {
622 self.inner
623 .skills
624 .values()
625 .any(|skill| !skill.required_scopes.is_empty())
626 }
627}
628
629impl fmt::Debug for McpServerSkillCatalog {
630 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
631 formatter
632 .debug_struct("McpServerSkillCatalog")
633 .field("skills", &self.skill_count())
634 .field("files", &self.file_count())
635 .field("bytes", &self.byte_count())
636 .field("catalog_digest", &self.inner.digest)
637 .finish()
638 }
639}
640
641#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
643#[non_exhaustive]
644pub enum McpServerSkillCatalogError {
645 #[error("MCP Skill catalog is empty")]
647 Empty,
648 #[error("duplicate MCP Skill URI")]
650 DuplicateSkill,
651 #[error("duplicate MCP Skill resource URI")]
653 DuplicateResource,
654 #[error("too many MCP Skills")]
656 TooManySkills,
657 #[error("too many MCP Skill files")]
659 TooManyFiles,
660 #[error("MCP Skill catalog is too large")]
662 TooLarge,
663}
664
665#[derive(Clone, Copy, Debug, Eq, PartialEq)]
667#[non_exhaustive]
668pub enum McpServerSkillOperation {
669 List,
671 Get,
673 Read,
675}
676
677#[derive(Clone, Debug)]
679pub struct McpServerSkillAuthorizationRequest {
680 principal: McpServerPrincipal,
681 operation: McpServerSkillOperation,
682 uri: Arc<str>,
683}
684
685impl McpServerSkillAuthorizationRequest {
686 #[must_use]
688 pub const fn principal(&self) -> &McpServerPrincipal {
689 &self.principal
690 }
691
692 #[must_use]
694 pub const fn operation(&self) -> McpServerSkillOperation {
695 self.operation
696 }
697
698 #[must_use]
700 pub fn uri(&self) -> &str {
701 &self.uri
702 }
703}
704
705pub trait McpServerSkillAuthorization: Send + Sync + 'static {
707 fn authorize(
709 &self,
710 request: McpServerSkillAuthorizationRequest,
711 ) -> BoxFuture<'_, Result<(), McpServerSkillAuthorizationError>>;
712
713 fn is_public_cache_safe(&self) -> bool {
719 false
720 }
721}
722
723#[derive(Clone, Copy, Debug, Default)]
725pub struct AllowMcpServerSkillAuthorization;
726
727impl McpServerSkillAuthorization for AllowMcpServerSkillAuthorization {
728 fn authorize(
729 &self,
730 _request: McpServerSkillAuthorizationRequest,
731 ) -> BoxFuture<'_, Result<(), McpServerSkillAuthorizationError>> {
732 Box::pin(async { Ok(()) })
733 }
734
735 fn is_public_cache_safe(&self) -> bool {
736 true
737 }
738}
739
740#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
742#[non_exhaustive]
743pub enum McpServerSkillAuthorizationError {
744 #[error("MCP Skill operation is forbidden")]
746 Forbidden,
747 #[error("MCP Skill authorization is unavailable")]
749 Unavailable,
750}
751
752#[derive(Clone)]
754pub struct McpServerSkillService {
755 catalog: McpServerSkillCatalog,
756 options: McpServerApplicationOptions,
757 authorization: Arc<dyn McpServerSkillAuthorization>,
758}
759
760impl McpServerSkillService {
761 pub fn new<A>(
763 catalog: McpServerSkillCatalog,
764 options: McpServerApplicationOptions,
765 authorization: A,
766 ) -> Result<Self, McpServerSkillServiceBuildError>
767 where
768 A: McpServerSkillAuthorization,
769 {
770 if matches!(options.cache_scope, McpServerCacheScope::Public) {
771 if catalog.contains_scoped_skills() {
772 return Err(McpServerSkillServiceBuildError::PublicCacheWithScopedSkills);
773 }
774 if !authorization.is_public_cache_safe() {
775 return Err(McpServerSkillServiceBuildError::PublicCacheWithDynamicPolicy);
776 }
777 }
778 Ok(Self {
779 catalog,
780 options,
781 authorization: Arc::new(authorization),
782 })
783 }
784
785 #[must_use]
787 pub const fn catalog(&self) -> &McpServerSkillCatalog {
788 &self.catalog
789 }
790
791 pub(crate) fn contains_resource(&self, uri: &str) -> bool {
792 self.catalog.contains_resource(uri)
793 }
794
795 pub(crate) fn resource_uris(&self) -> impl Iterator<Item = &str> {
796 self.catalog.inner.resources.keys().map(String::as_str)
797 }
798
799 pub(crate) fn capabilities() -> ServerCapabilities {
800 let mut capabilities = ServerCapabilities::default();
801 capabilities.resources = Some(ResourcesCapability::default());
802 let mut extensions = ExtensionCapabilities::new();
803 extensions.insert(MCP_SKILLS_EXTENSION_ID.to_owned(), Map::new());
804 capabilities.extensions = Some(extensions);
805 capabilities
806 }
807
808 fn scope_tag(&self, principal: &McpServerPrincipal) -> String {
809 if matches!(self.options.cache_scope, McpServerCacheScope::Public) {
810 return "public".to_owned();
811 }
812 let mut material = principal.subject().as_bytes().to_vec();
813 for scope in principal.scopes() {
814 append_digest_part(&mut material, scope.as_bytes());
815 }
816 digest_hex(material)
817 }
818
819 fn cursor(&self, kind: &str, scope: &str, offset: usize) -> String {
820 format!(
821 "v1.{kind}.{}.{}.{}",
822 self.catalog.inner.digest, scope, offset
823 )
824 }
825
826 fn parse_cursor(&self, value: &str, kind: &str, scope: &str) -> Result<usize, ErrorData> {
827 if value.len() > 224 {
828 return Err(invalid_cursor());
829 }
830 let mut parts = value.split('.');
831 let valid = parts.next() == Some("v1")
832 && parts.next() == Some(kind)
833 && parts.next() == Some(self.catalog.inner.digest.as_ref())
834 && parts.next() == Some(scope);
835 let offset = parts.next().and_then(|part| part.parse::<usize>().ok());
836 if !valid || offset.is_none() || parts.next().is_some() {
837 return Err(invalid_cursor());
838 }
839 Ok(offset.expect("validated Skill cursor offset exists"))
840 }
841
842 async fn authorized(
843 &self,
844 principal: &McpServerPrincipal,
845 operation: McpServerSkillOperation,
846 uri: &str,
847 ) -> Result<bool, ErrorData> {
848 let request = McpServerSkillAuthorizationRequest {
849 principal: principal.clone(),
850 operation,
851 uri: Arc::from(uri),
852 };
853 match self.authorization.authorize(request).await {
854 Ok(()) => Ok(true),
855 Err(McpServerSkillAuthorizationError::Forbidden) => Ok(false),
856 Err(McpServerSkillAuthorizationError::Unavailable) => Err(ErrorData::internal_error(
857 "MCP Skill authorization is unavailable",
858 None,
859 )),
860 }
861 }
862
863 async fn visible_skills(
864 &self,
865 principal: &McpServerPrincipal,
866 operation: McpServerSkillOperation,
867 ) -> Result<Vec<&McpServerSkillDefinition>, ErrorData> {
868 let mut visible = Vec::new();
869 for skill in self.catalog.inner.skills.values() {
870 if skill.has_required_scopes(principal)
871 && self.authorized(principal, operation, skill.uri()).await?
872 {
873 visible.push(skill);
874 }
875 }
876 Ok(visible)
877 }
878
879 async fn list_skills(
880 &self,
881 request: &CustomRequest,
882 context: &RequestContext<RoleServer>,
883 ) -> Result<CustomResult, ErrorData> {
884 let params = parse_list_params(request)?;
885 let principal = required_principal(context)?;
886 let scope = self.scope_tag(principal);
887 let visible = self
888 .visible_skills(principal, McpServerSkillOperation::List)
889 .await?;
890 let start = params
891 .cursor
892 .as_deref()
893 .map_or(Ok(0), |cursor| self.parse_cursor(cursor, "skills", &scope))?;
894 if start > visible.len() {
895 return Err(invalid_cursor());
896 }
897 let end = start
898 .saturating_add(self.options.page_size)
899 .min(visible.len());
900 let skills = visible[start..end]
901 .iter()
902 .map(|skill| skill.to_wire())
903 .collect::<Vec<_>>();
904 let next_cursor = (end < visible.len()).then(|| self.cursor("skills", &scope, end));
905 let mut result = Map::new();
906 result.insert("resultType".to_owned(), json!("complete"));
907 result.insert("skills".to_owned(), Value::Array(skills));
908 result.insert("ttlMs".to_owned(), json!(self.options.cache_ttl_ms));
909 result.insert("cacheScope".to_owned(), json!(self.cache_scope_name()));
910 if let Some(cursor) = next_cursor {
911 result.insert("nextCursor".to_owned(), Value::String(cursor));
912 }
913 Ok(CustomResult::new(Value::Object(result)))
914 }
915
916 async fn get_skill(
917 &self,
918 request: &CustomRequest,
919 context: &RequestContext<RoleServer>,
920 ) -> Result<CustomResult, ErrorData> {
921 let params = parse_get_params(request)?;
922 validate_absolute_uri(¶ms.uri).map_err(|_| skill_not_found())?;
923 let principal = required_principal(context)?;
924 if !self
925 .authorized(principal, McpServerSkillOperation::Get, ¶ms.uri)
926 .await?
927 {
928 return Err(skill_not_found());
929 }
930 let skill = self.catalog.get(¶ms.uri).ok_or_else(skill_not_found)?;
931 if !skill.has_required_scopes(principal) {
932 return Err(skill_not_found());
933 }
934 Ok(CustomResult::new(json!({
935 "resultType": "complete",
936 "skill": skill.to_wire(),
937 "ttlMs": self.options.cache_ttl_ms,
938 "cacheScope": self.cache_scope_name(),
939 })))
940 }
941
942 async fn list_skill_resources(
943 &self,
944 request: Option<&PaginatedRequestParams>,
945 context: &RequestContext<RoleServer>,
946 ) -> Result<ListResourcesResult, ErrorData> {
947 let principal = required_principal(context)?;
948 let visible_skills = self
949 .visible_skills(principal, McpServerSkillOperation::Read)
950 .await?
951 .into_iter()
952 .map(McpServerSkillDefinition::uri)
953 .collect::<BTreeSet<_>>();
954 let visible = self
955 .catalog
956 .inner
957 .resources
958 .iter()
959 .filter(|(_, binding)| visible_skills.contains(binding.skill_uri.as_ref()))
960 .collect::<Vec<_>>();
961 let scope = self.scope_tag(principal);
962 let start = request
963 .and_then(|params| params.cursor.as_deref())
964 .map_or(Ok(0), |cursor| {
965 self.parse_cursor(cursor, "resources", &scope)
966 })?;
967 if start > visible.len() {
968 return Err(invalid_cursor());
969 }
970 let end = start
971 .saturating_add(self.options.page_size)
972 .min(visible.len());
973 let resources = visible[start..end]
974 .iter()
975 .map(|(uri, binding)| {
976 let mut resource =
977 Resource::new((*uri).to_owned(), binding.file.relative_path().to_owned());
978 resource.mime_type = Some(binding.file.mime_type().to_owned());
979 resource.size = u64::try_from(binding.file.size()).ok();
980 resource
981 })
982 .collect();
983 let mut result = ListResourcesResult::with_all_items(resources)
984 .with_ttl_ms(self.options.cache_ttl_ms)
985 .with_cache_scope(self.options.cache_scope.into());
986 result.next_cursor = (end < visible.len()).then(|| self.cursor("resources", &scope, end));
987 Ok(result)
988 }
989
990 async fn read_skill_resource(
991 &self,
992 request: ReadResourceRequestParams,
993 context: &RequestContext<RoleServer>,
994 ) -> Result<ReadResourceResponse, ErrorData> {
995 validate_absolute_uri(&request.uri).map_err(|_| resource_not_found())?;
996 if request.input_responses.is_some() || request.request_state.is_some() {
997 return Err(ErrorData::invalid_params(
998 "MCP Skill files do not accept request state or input responses",
999 None,
1000 ));
1001 }
1002 let principal = required_principal(context)?;
1003 if !self
1004 .authorized(principal, McpServerSkillOperation::Read, &request.uri)
1005 .await?
1006 {
1007 return Err(resource_not_found());
1008 }
1009 let binding = self
1010 .catalog
1011 .inner
1012 .resources
1013 .get(&request.uri)
1014 .ok_or_else(resource_not_found)?;
1015 let skill = self
1016 .catalog
1017 .get(&binding.skill_uri)
1018 .expect("resource bindings always reference a frozen Skill");
1019 if !skill.has_required_scopes(principal) {
1020 return Err(resource_not_found());
1021 }
1022 let resource_content = match binding.file.representation {
1023 McpServerSkillFileRepresentation::Text => ResourceContents::TextResourceContents {
1024 uri: request.uri,
1025 mime_type: Some(binding.file.mime_type().to_owned()),
1026 text: std::str::from_utf8(&binding.file.bytes)
1027 .expect("text Skill files are validated UTF-8")
1028 .to_owned(),
1029 meta: None,
1030 },
1031 McpServerSkillFileRepresentation::Binary => ResourceContents::BlobResourceContents {
1032 uri: request.uri,
1033 mime_type: Some(binding.file.mime_type().to_owned()),
1034 blob: STANDARD.encode(&binding.file.bytes),
1035 meta: None,
1036 },
1037 };
1038 Ok(ReadResourceResult::new(vec![resource_content])
1039 .with_ttl_ms(self.options.cache_ttl_ms)
1040 .with_cache_scope(self.options.cache_scope.into())
1041 .into())
1042 }
1043
1044 fn cache_scope_name(&self) -> &'static str {
1045 match self.options.cache_scope {
1046 McpServerCacheScope::Public => "public",
1047 McpServerCacheScope::Private => "private",
1048 }
1049 }
1050
1051 pub(crate) async fn dispatch_custom(
1052 &self,
1053 request: CustomRequest,
1054 context: RequestContext<RoleServer>,
1055 ) -> Result<CustomResult, ErrorData> {
1056 match request.method.as_str() {
1057 SKILL_LIST_METHOD => self.list_skills(&request, &context).await,
1058 SKILL_GET_METHOD => self.get_skill(&request, &context).await,
1059 _ => Err(ErrorData::new(
1060 rmcp::model::ErrorCode::METHOD_NOT_FOUND,
1061 request.method,
1062 None,
1063 )),
1064 }
1065 }
1066
1067 pub(crate) async fn dispatch_read(
1068 &self,
1069 request: ReadResourceRequestParams,
1070 context: RequestContext<RoleServer>,
1071 ) -> Result<ReadResourceResponse, ErrorData> {
1072 self.read_skill_resource(request, &context).await
1073 }
1074}
1075
1076impl fmt::Debug for McpServerSkillService {
1077 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1078 formatter
1079 .debug_struct("McpServerSkillService")
1080 .field("catalog", &self.catalog)
1081 .field("options", &self.options)
1082 .field("authorization", &"[POLICY]")
1083 .finish_non_exhaustive()
1084 }
1085}
1086
1087impl ServerHandler for McpServerSkillService {
1088 fn supported_protocol_versions(&self) -> Cow<'static, [ProtocolVersion]> {
1089 Cow::Borrowed(&[ProtocolVersion::V_2026_07_28])
1090 }
1091
1092 fn get_info(&self) -> ServerConfig {
1093 let mut info =
1094 ServerConfig::new(Self::capabilities()).with_server_info(Implementation::new(
1095 self.options.server_name.to_string(),
1096 self.options.server_version.to_string(),
1097 ));
1098 if let Some(instructions) = &self.options.instructions {
1099 info = info.with_instructions(instructions.to_string());
1100 }
1101 info
1102 }
1103
1104 async fn discover(
1105 &self,
1106 _context: RequestContext<RoleServer>,
1107 ) -> Result<DiscoverResult, ErrorData> {
1108 Ok(
1109 DiscoverResult::from_server_info(vec![ProtocolVersion::V_2026_07_28], self.get_info())
1110 .with_ttl_ms(self.options.cache_ttl_ms)
1111 .with_cache_scope(self.options.cache_scope.into()),
1112 )
1113 }
1114
1115 async fn on_custom_request(
1116 &self,
1117 request: CustomRequest,
1118 context: RequestContext<RoleServer>,
1119 ) -> Result<CustomResult, ErrorData> {
1120 self.dispatch_custom(request, context).await
1121 }
1122
1123 async fn list_resources(
1124 &self,
1125 request: Option<PaginatedRequestParams>,
1126 context: RequestContext<RoleServer>,
1127 ) -> Result<ListResourcesResult, ErrorData> {
1128 self.list_skill_resources(request.as_ref(), &context).await
1129 }
1130
1131 async fn list_resource_templates(
1132 &self,
1133 _request: Option<PaginatedRequestParams>,
1134 _context: RequestContext<RoleServer>,
1135 ) -> Result<ListResourceTemplatesResult, ErrorData> {
1136 Ok(ListResourceTemplatesResult::with_all_items(Vec::new())
1137 .with_ttl_ms(self.options.cache_ttl_ms)
1138 .with_cache_scope(self.options.cache_scope.into()))
1139 }
1140
1141 async fn read_resource(
1142 &self,
1143 request: ReadResourceRequestParams,
1144 context: RequestContext<RoleServer>,
1145 ) -> Result<ReadResourceResponse, ErrorData> {
1146 self.read_skill_resource(request, &context).await
1147 }
1148}
1149
1150#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
1152#[non_exhaustive]
1153pub enum McpServerSkillServiceBuildError {
1154 #[error("scope-restricted MCP Skills require a private catalog cache")]
1156 PublicCacheWithScopedSkills,
1157 #[error("dynamic MCP Skill authorization requires a private catalog cache")]
1159 PublicCacheWithDynamicPolicy,
1160}
1161
1162#[derive(Debug, Default, Deserialize)]
1163#[serde(deny_unknown_fields)]
1164struct SkillListParams {
1165 cursor: Option<String>,
1166}
1167
1168#[derive(Debug, Deserialize)]
1169#[serde(deny_unknown_fields)]
1170struct SkillGetParams {
1171 uri: String,
1172}
1173
1174fn parse_list_params(request: &CustomRequest) -> Result<SkillListParams, ErrorData> {
1175 let params = match &request.params {
1176 None => SkillListParams::default(),
1177 Some(value) => serde_json::from_value(value.clone())
1178 .map_err(|_| ErrorData::invalid_params("Invalid skills/list parameters", None))?,
1179 };
1180 if params
1181 .cursor
1182 .as_ref()
1183 .is_some_and(|cursor| cursor.is_empty() || cursor.len() > 224)
1184 {
1185 return Err(invalid_cursor());
1186 }
1187 Ok(params)
1188}
1189
1190fn parse_get_params(request: &CustomRequest) -> Result<SkillGetParams, ErrorData> {
1191 let Some(value) = &request.params else {
1192 return Err(ErrorData::invalid_params(
1193 "Invalid skills/get parameters",
1194 None,
1195 ));
1196 };
1197 let params: SkillGetParams = serde_json::from_value(value.clone())
1198 .map_err(|_| ErrorData::invalid_params("Invalid skills/get parameters", None))?;
1199 if params.uri.is_empty() || params.uri.len() > MAX_URI_BYTES {
1200 return Err(skill_not_found());
1201 }
1202 Ok(params)
1203}
1204
1205pub(crate) fn parse_frontmatter(
1206 document: &str,
1207) -> Result<Map<String, Value>, McpServerSkillDefinitionError> {
1208 let bytes = document.as_bytes();
1209 let Some(first_end) = bytes.iter().position(|byte| *byte == b'\n') else {
1210 return Err(McpServerSkillDefinitionError::InvalidFrontmatter);
1211 };
1212 if document[..first_end].trim_end_matches('\r') != "---" {
1213 return Err(McpServerSkillDefinitionError::InvalidFrontmatter);
1214 }
1215 let mut line_start = first_end + 1;
1216 let mut closing_start = None;
1217 while line_start <= bytes.len() {
1218 let line_end = bytes[line_start..]
1219 .iter()
1220 .position(|byte| *byte == b'\n')
1221 .map_or(bytes.len(), |relative| line_start + relative);
1222 if document[line_start..line_end].trim_end_matches('\r') == "---" {
1223 closing_start = Some(line_start);
1224 break;
1225 }
1226 if line_end == bytes.len() {
1227 break;
1228 }
1229 line_start = line_end + 1;
1230 }
1231 let closing_start = closing_start.ok_or(McpServerSkillDefinitionError::InvalidFrontmatter)?;
1232 let yaml = &document[first_end + 1..closing_start];
1233 if yaml.is_empty() || yaml.len() > MAX_FRONTMATTER_BYTES {
1234 return Err(McpServerSkillDefinitionError::InvalidFrontmatter);
1235 }
1236 let value = BoundedUniqueJsonValueSeed::new(MAX_FRONTMATTER_BYTES)
1237 .deserialize(serde_yaml_ng::Deserializer::from_str(yaml))
1238 .map_err(|_| McpServerSkillDefinitionError::InvalidFrontmatter)?;
1239 value
1240 .as_object()
1241 .cloned()
1242 .ok_or(McpServerSkillDefinitionError::InvalidFrontmatter)
1243}
1244
1245#[derive(Clone)]
1246struct BoundedUniqueJsonValueSeed {
1247 remaining_bytes: Rc<Cell<usize>>,
1248}
1249
1250impl BoundedUniqueJsonValueSeed {
1251 fn new(maximum_bytes: usize) -> Self {
1252 Self {
1253 remaining_bytes: Rc::new(Cell::new(maximum_bytes)),
1254 }
1255 }
1256
1257 fn consume<E>(&self, bytes: usize) -> Result<(), E>
1258 where
1259 E: de::Error,
1260 {
1261 let bytes = bytes.max(1);
1262 let remaining = self.remaining_bytes.get();
1263 if bytes > remaining {
1264 return Err(E::custom("expanded YAML value exceeds its byte budget"));
1265 }
1266 self.remaining_bytes.set(remaining - bytes);
1267 Ok(())
1268 }
1269}
1270
1271impl<'de> DeserializeSeed<'de> for BoundedUniqueJsonValueSeed {
1272 type Value = Value;
1273
1274 fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1275 where
1276 D: Deserializer<'de>,
1277 {
1278 deserializer.deserialize_any(BoundedUniqueJsonValueVisitor { seed: self })
1279 }
1280}
1281
1282struct BoundedUniqueJsonValueVisitor {
1283 seed: BoundedUniqueJsonValueSeed,
1284}
1285
1286impl<'de> Visitor<'de> for BoundedUniqueJsonValueVisitor {
1287 type Value = Value;
1288
1289 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1290 formatter.write_str("a YAML value representable as duplicate-free JSON")
1291 }
1292
1293 fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
1294 where
1295 E: de::Error,
1296 {
1297 self.seed.consume::<E>(1)?;
1298 Ok(Value::Bool(value))
1299 }
1300
1301 fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
1302 where
1303 E: de::Error,
1304 {
1305 self.seed.consume::<E>(std::mem::size_of::<i64>())?;
1306 Ok(Value::Number(value.into()))
1307 }
1308
1309 fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
1310 where
1311 E: de::Error,
1312 {
1313 self.seed.consume::<E>(std::mem::size_of::<u64>())?;
1314 Ok(Value::Number(value.into()))
1315 }
1316
1317 fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E>
1318 where
1319 E: de::Error,
1320 {
1321 self.seed.consume::<E>(std::mem::size_of::<f64>())?;
1322 serde_json::Number::from_f64(value)
1323 .map(Value::Number)
1324 .ok_or_else(|| E::custom("non-finite YAML number"))
1325 }
1326
1327 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
1328 where
1329 E: de::Error,
1330 {
1331 self.seed.consume::<E>(value.len())?;
1332 Ok(Value::String(value.to_owned()))
1333 }
1334
1335 fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
1336 where
1337 E: de::Error,
1338 {
1339 self.seed.consume::<E>(value.len())?;
1340 Ok(Value::String(value))
1341 }
1342
1343 fn visit_none<E>(self) -> Result<Self::Value, E>
1344 where
1345 E: de::Error,
1346 {
1347 self.seed.consume::<E>(1)?;
1348 Ok(Value::Null)
1349 }
1350
1351 fn visit_unit<E>(self) -> Result<Self::Value, E>
1352 where
1353 E: de::Error,
1354 {
1355 self.seed.consume::<E>(1)?;
1356 Ok(Value::Null)
1357 }
1358
1359 fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1360 where
1361 D: Deserializer<'de>,
1362 {
1363 self.seed.deserialize(deserializer)
1364 }
1365
1366 fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
1367 where
1368 A: SeqAccess<'de>,
1369 {
1370 self.seed.consume::<A::Error>(1)?;
1371 let mut values = Vec::with_capacity(sequence.size_hint().unwrap_or_default().min(1024));
1372 while let Some(value) = sequence.next_element_seed(self.seed.clone())? {
1373 values.push(value);
1374 }
1375 Ok(Value::Array(values))
1376 }
1377
1378 fn visit_map<A>(self, mut mapping: A) -> Result<Self::Value, A::Error>
1379 where
1380 A: MapAccess<'de>,
1381 {
1382 self.seed.consume::<A::Error>(1)?;
1383 let mut values = Map::new();
1384 while let Some(key) = mapping.next_key::<String>()? {
1385 self.seed.consume::<A::Error>(key.len())?;
1386 let value = mapping.next_value_seed(self.seed.clone())?;
1387 if values.insert(key, value).is_some() {
1388 return Err(de::Error::custom("duplicate YAML mapping key"));
1389 }
1390 }
1391 Ok(Value::Object(values))
1392 }
1393}
1394
1395pub(crate) fn validate_frontmatter(
1396 frontmatter: &Map<String, Value>,
1397) -> Result<(), McpServerSkillDefinitionError> {
1398 let name = frontmatter
1399 .get("name")
1400 .and_then(Value::as_str)
1401 .ok_or(McpServerSkillDefinitionError::InvalidFrontmatterField)?;
1402 if !valid_skill_name(name) {
1403 return Err(McpServerSkillDefinitionError::InvalidFrontmatterField);
1404 }
1405 let description = frontmatter
1406 .get("description")
1407 .and_then(Value::as_str)
1408 .ok_or(McpServerSkillDefinitionError::InvalidFrontmatterField)?;
1409 if description.trim().is_empty() || description.chars().count() > 1024 {
1410 return Err(McpServerSkillDefinitionError::InvalidFrontmatterField);
1411 }
1412 for field in ["license", "allowed-tools"] {
1413 if frontmatter
1414 .get(field)
1415 .is_some_and(|value| value.as_str().is_none())
1416 {
1417 return Err(McpServerSkillDefinitionError::InvalidFrontmatterField);
1418 }
1419 }
1420 if frontmatter.get("compatibility").is_some_and(|value| {
1421 value
1422 .as_str()
1423 .is_none_or(|text| text.trim().is_empty() || text.chars().count() > 500)
1424 }) {
1425 return Err(McpServerSkillDefinitionError::InvalidFrontmatterField);
1426 }
1427 if frontmatter.get("metadata").is_some_and(|value| {
1428 value
1429 .as_object()
1430 .is_none_or(|metadata| metadata.values().any(|entry| entry.as_str().is_none()))
1431 }) {
1432 return Err(McpServerSkillDefinitionError::InvalidFrontmatterField);
1433 }
1434 Ok(())
1435}
1436
1437fn valid_skill_name(name: &str) -> bool {
1438 !name.is_empty()
1439 && name.len() <= 64
1440 && !name.starts_with('-')
1441 && !name.ends_with('-')
1442 && !name.contains("--")
1443 && name
1444 .bytes()
1445 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
1446}
1447
1448pub(crate) fn validate_skill_uri(uri: &str) -> Result<String, McpServerSkillDefinitionError> {
1449 validate_absolute_uri(uri)?;
1450 let parsed = uri
1451 .parse::<http::Uri>()
1452 .map_err(|_| McpServerSkillDefinitionError::InvalidUri)?;
1453 if parsed.query().is_some() || !parsed.path().ends_with("/SKILL.md") {
1454 return Err(McpServerSkillDefinitionError::InvalidUri);
1455 }
1456 let path = parsed.path();
1457 if path.contains('%')
1458 || path.contains("//")
1459 || path.contains('\\')
1460 || path.split('/').any(|segment| matches!(segment, "." | ".."))
1461 {
1462 return Err(McpServerSkillDefinitionError::InvalidUri);
1463 }
1464 let parent_path = path
1465 .strip_suffix("/SKILL.md")
1466 .expect("checked Skill URI suffix")
1467 .trim_end_matches('/');
1468 let parent = parent_path
1469 .rsplit('/')
1470 .find(|segment| !segment.is_empty())
1471 .map(str::to_owned)
1472 .or_else(|| {
1473 parsed
1474 .authority()
1475 .map(|authority| authority.host().to_owned())
1476 })
1477 .ok_or(McpServerSkillDefinitionError::InvalidUri)?;
1478 if !valid_skill_name(&parent) {
1479 return Err(McpServerSkillDefinitionError::InvalidUri);
1480 }
1481 Ok(parent)
1482}
1483
1484fn validate_absolute_uri(uri: &str) -> Result<(), McpServerSkillDefinitionError> {
1485 if uri.is_empty()
1486 || uri.len() > MAX_URI_BYTES
1487 || uri.chars().any(char::is_control)
1488 || uri
1489 .parse::<http::Uri>()
1490 .map_or(true, |parsed| parsed.scheme().is_none())
1491 {
1492 return Err(McpServerSkillDefinitionError::InvalidUri);
1493 }
1494 Ok(())
1495}
1496
1497pub(crate) fn validate_relative_path(path: &str) -> Result<(), McpServerSkillFileError> {
1498 if path.is_empty()
1499 || path.len() > MAX_RELATIVE_PATH_BYTES
1500 || path.starts_with('/')
1501 || path.ends_with('/')
1502 || path.contains('\\')
1503 || path.chars().any(char::is_control)
1504 {
1505 return Err(McpServerSkillFileError::InvalidRelativePath);
1506 }
1507 for segment in path.split('/') {
1508 if segment.is_empty()
1509 || matches!(segment, "." | "..")
1510 || !segment.bytes().all(|byte| {
1511 byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~')
1512 })
1513 {
1514 return Err(McpServerSkillFileError::InvalidRelativePath);
1515 }
1516 }
1517 Ok(())
1518}
1519
1520fn resource_uri(
1521 skill_uri: &str,
1522 relative_path: &str,
1523) -> Result<String, McpServerSkillDefinitionError> {
1524 let prefix = skill_uri
1525 .strip_suffix(SKILL_DOCUMENT)
1526 .ok_or(McpServerSkillDefinitionError::InvalidUri)?;
1527 let uri = format!("{prefix}{relative_path}");
1528 validate_absolute_uri(&uri)?;
1529 if uri.len() > MAX_URI_BYTES {
1530 return Err(McpServerSkillDefinitionError::InvalidUri);
1531 }
1532 Ok(uri)
1533}
1534
1535fn validate_scopes(
1536 scopes: impl IntoIterator<Item = impl Into<String>>,
1537) -> Result<Arc<[Box<str>]>, McpServerSkillDefinitionError> {
1538 let mut scopes = scopes.into_iter().map(Into::into).collect::<Vec<_>>();
1539 if scopes.len() > MAX_SCOPE_COUNT {
1540 return Err(McpServerSkillDefinitionError::TooManyScopes);
1541 }
1542 if scopes.iter().any(|scope| {
1543 scope.is_empty()
1544 || scope.len() > MAX_SCOPE_BYTES
1545 || scope
1546 .bytes()
1547 .any(|byte| !matches!(byte, b'!' | b'#'..=b'[' | b']'..=b'~'))
1548 }) {
1549 return Err(McpServerSkillDefinitionError::InvalidScope);
1550 }
1551 scopes.sort_unstable();
1552 if scopes.windows(2).any(|pair| pair[0] == pair[1]) {
1553 return Err(McpServerSkillDefinitionError::DuplicateScope);
1554 }
1555 Ok(scopes
1556 .into_iter()
1557 .map(String::into_boxed_str)
1558 .collect::<Vec<_>>()
1559 .into())
1560}
1561
1562fn required_principal(
1563 context: &RequestContext<RoleServer>,
1564) -> Result<&McpServerPrincipal, ErrorData> {
1565 mcp_server_principal(context)
1566 .ok_or_else(|| ErrorData::internal_error("MCP server boundary is missing", None))
1567}
1568
1569fn invalid_cursor() -> ErrorData {
1570 ErrorData::invalid_params("Invalid MCP Skill catalog cursor", None)
1571}
1572
1573fn skill_not_found() -> ErrorData {
1574 ErrorData::invalid_params("MCP Skill was not found or unavailable", None)
1575}
1576
1577fn resource_not_found() -> ErrorData {
1578 ErrorData::resource_not_found("Resource not found or unavailable", None)
1579}
1580
1581fn digest_hex(value: impl AsRef<[u8]>) -> String {
1582 Digest::sha256(value)
1583 .to_string()
1584 .strip_prefix("sha256:")
1585 .expect("StateKnot SHA-256 digest has a stable prefix")
1586 .to_owned()
1587}
1588
1589#[cfg(test)]
1590mod tests {
1591 use super::*;
1592
1593 fn skill(name: &str) -> McpServerSkillDefinition {
1594 let document = format!(
1595 "---\nname: {name}\ndescription: Review code with a fixed checklist.\nmetadata:\n owner: stateknot\n---\n\n# Review\n"
1596 );
1597 McpServerSkillDefinition::new(
1598 format!("skill://{name}/SKILL.md"),
1599 [
1600 McpServerSkillFile::text(SKILL_DOCUMENT, "text/markdown", document).unwrap(),
1601 McpServerSkillFile::text(
1602 "references/checklist.md",
1603 "text/markdown",
1604 "# Checklist\n",
1605 )
1606 .unwrap(),
1607 ],
1608 )
1609 .unwrap()
1610 }
1611
1612 #[test]
1613 fn definition_freezes_complete_manifest() {
1614 let definition = skill("code-review");
1615 assert_eq!(definition.name(), "code-review");
1616 assert_eq!(definition.files().len(), 2);
1617 let wire = definition.to_wire();
1618 assert_eq!(
1619 wire.pointer("/frontmatter/name"),
1620 Some(&json!("code-review"))
1621 );
1622 assert_eq!(
1623 wire.pointer("/resources/0/uri"),
1624 Some(&json!("skill://code-review/SKILL.md"))
1625 );
1626 assert!(
1627 wire.pointer("/resources/0/digest")
1628 .and_then(Value::as_str)
1629 .is_some_and(|digest| digest.starts_with("sha256:"))
1630 );
1631 }
1632
1633 #[test]
1634 fn definition_rejects_traversal_and_name_mismatch() {
1635 assert_eq!(
1636 McpServerSkillFile::text("../secret", "text/plain", "x").unwrap_err(),
1637 McpServerSkillFileError::InvalidRelativePath
1638 );
1639 let document = McpServerSkillFile::text(
1640 SKILL_DOCUMENT,
1641 "text/markdown",
1642 "---\nname: other\ndescription: Valid description.\n---\n",
1643 )
1644 .unwrap();
1645 assert_eq!(
1646 McpServerSkillDefinition::new("skill://expected/SKILL.md", [document]).unwrap_err(),
1647 McpServerSkillDefinitionError::NameUriMismatch
1648 );
1649 let document = McpServerSkillFile::text(
1650 SKILL_DOCUMENT,
1651 "text/markdown",
1652 "---\nname: expected\ndescription: Valid description.\n---\n",
1653 )
1654 .unwrap();
1655 assert_eq!(
1656 McpServerSkillDefinition::new("skill://catalog/../expected/SKILL.md", [document],)
1657 .unwrap_err(),
1658 McpServerSkillDefinitionError::InvalidUri
1659 );
1660 }
1661
1662 #[test]
1663 fn definition_rejects_duplicate_or_malformed_frontmatter() {
1664 let duplicate = McpServerSkillFile::text(
1665 SKILL_DOCUMENT,
1666 "text/markdown",
1667 "---\nname: duplicate\nname: shadow\ndescription: Valid description.\n---\n",
1668 )
1669 .unwrap();
1670 assert_eq!(
1671 McpServerSkillDefinition::new("skill://duplicate/SKILL.md", [duplicate]).unwrap_err(),
1672 McpServerSkillDefinitionError::InvalidFrontmatter
1673 );
1674 let nested_duplicate = McpServerSkillFile::text(
1675 SKILL_DOCUMENT,
1676 "text/markdown",
1677 "---\nname: nested-duplicate\ndescription: Valid description.\nextra:\n owner: first\n owner: second\n---\n",
1678 )
1679 .unwrap();
1680 assert_eq!(
1681 McpServerSkillDefinition::new("skill://nested-duplicate/SKILL.md", [nested_duplicate],)
1682 .unwrap_err(),
1683 McpServerSkillDefinitionError::InvalidFrontmatter
1684 );
1685 let invalid_metadata = McpServerSkillFile::text(
1686 SKILL_DOCUMENT,
1687 "text/markdown",
1688 "---\nname: invalid\ndescription: Valid description.\nmetadata:\n count: 1\n---\n",
1689 )
1690 .unwrap();
1691 assert_eq!(
1692 McpServerSkillDefinition::new("skill://invalid/SKILL.md", [invalid_metadata])
1693 .unwrap_err(),
1694 McpServerSkillDefinitionError::InvalidFrontmatterField
1695 );
1696 }
1697
1698 #[test]
1699 fn definition_rejects_alias_expansion_above_the_materialized_budget() {
1700 let document = McpServerSkillFile::text(
1701 SKILL_DOCUMENT,
1702 "text/markdown",
1703 "---\nname: alias-expansion\ndescription: Valid description.\nbase: &base [0123456789abcdef]\na: &a [*base, *base]\nb: &b [*a, *a]\nc: &c [*b, *b]\nd: &d [*c, *c]\ne: &e [*d, *d]\nf: &f [*e, *e]\ng: &g [*f, *f]\nh: &h [*g, *g]\ni: &i [*h, *h]\nj: &j [*i, *i]\nk: [*j, *j, *j, *j, *j]\n---\n",
1704 )
1705 .unwrap();
1706 assert_eq!(
1707 McpServerSkillDefinition::new("skill://alias-expansion/SKILL.md", [document])
1708 .unwrap_err(),
1709 McpServerSkillDefinitionError::InvalidFrontmatter
1710 );
1711 }
1712
1713 #[test]
1714 fn catalog_rejects_overlapping_resource_namespace() {
1715 let mut catalog = McpServerSkillCatalogBuilder::default();
1716 catalog.register(skill("code-review")).unwrap();
1717 assert_eq!(
1718 catalog.register(skill("code-review")).unwrap_err(),
1719 McpServerSkillCatalogError::DuplicateSkill
1720 );
1721 }
1722}