Skip to main content

stateknot_integrations/
mcp_skill_host.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Verification-first client and durable Host authority for static MCP Skills.
5//!
6//! This profile deliberately declines dynamic manifests. It never materializes
7//! remote files into filesystem Skill discovery paths, fetches only on demand,
8//! and obtains content-bound approval before activation. Approval/window
9//! metadata is mandatory durable authority; remote file bytes remain verified
10//! on demand in a bounded private process cache.
11
12use std::{
13    collections::{BTreeMap, HashMap, HashSet},
14    fmt,
15    marker::PhantomData,
16    sync::{
17        Arc, Mutex,
18        atomic::{AtomicU64, Ordering},
19    },
20};
21
22use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64_STANDARD};
23use serde_json::{Map, Value};
24use stateknot_core::{
25    BoxFuture, CapabilityIdentity, Digest, SkillActingWindow, SkillActingWindowDuration,
26    SkillActingWindowId, SkillActingWindowOpenRequest, SkillActingWindowRevocation,
27    SkillActingWindowRevocationReason, SkillActivationApproval, SkillActivationApprovalId,
28    SkillActivationScope, SkillActivationSource, SkillActivationStore, SkillActivationStoreFailure,
29    SkillAuthorizationSubject,
30};
31use thiserror::Error;
32
33use crate::{
34    MCP_SKILLS_EXTENSION_ID, McpCachePolicy, McpClient, StatelessMcpClientError,
35    mcp_server_skill::{
36        parse_frontmatter, validate_frontmatter, validate_relative_path, validate_skill_uri,
37    },
38    mcp_skill_tool::{McpSkillToolBinding, McpSkillToolInvocation, McpSkillToolOperation},
39};
40
41const MEBIBYTE: usize = 1024 * 1024;
42const MAX_SKILL_URI_BYTES: usize = 4096;
43const MAX_CURSOR_BYTES: usize = 4096;
44const MAX_MIME_TYPE_BYTES: usize = 255;
45const MAX_ORIGIN_LABEL_BYTES: usize = 128;
46const MAX_TOOL_NAME_BYTES: usize = 1024;
47const SKILL_DOCUMENT: &str = "SKILL.md";
48const SKILLS_LIST_METHOD: &str = "skills/list";
49const SKILLS_GET_METHOD: &str = "skills/get";
50const RESOURCE_READ_METHOD: &str = "resources/read";
51
52/// Raw-byte support floor required by Final SEP-2640.
53pub const MCP_SKILL_MAXIMUM_BYTES: usize = 16 * MEBIBYTE;
54/// File-count support floor required by Final SEP-2640.
55pub const MCP_SKILL_MAXIMUM_FILES: usize = 512;
56/// `StateKnot`'s bounded JSON representation ceiling for advertised frontmatter.
57pub const MCP_SKILL_MAXIMUM_FRONTMATTER_BYTES: usize = 64 * 1024;
58/// Bounded JSON/SSE envelope needed for worst-case escaping of a 16 MiB text file.
59pub const MCP_SKILL_WIRE_RESPONSE_BYTES: usize = 104 * MEBIBYTE;
60
61/// Parsed optional capability settings for the MCP Skills extension.
62#[derive(Clone, Copy, Debug, Eq, PartialEq)]
63pub struct McpSkillCapabilities {
64    directory_read: bool,
65}
66
67impl McpSkillCapabilities {
68    /// Returns whether the server advertised `resources/directory/read`.
69    #[must_use]
70    pub const fn directory_read(self) -> bool {
71        self.directory_read
72    }
73}
74
75/// One exact static file descriptor in a Skill manifest.
76#[derive(Clone, Debug, Eq, PartialEq)]
77pub struct McpSkillResource {
78    uri: Arc<str>,
79    digest: Arc<str>,
80    size: usize,
81    relative_path: Arc<str>,
82}
83
84impl McpSkillResource {
85    /// Returns the originating server's exact resource URI.
86    #[must_use]
87    pub fn uri(&self) -> &str {
88        &self.uri
89    }
90
91    /// Returns the exact lower-case `sha256:` digest.
92    #[must_use]
93    pub fn digest(&self) -> &str {
94        &self.digest
95    }
96
97    /// Returns the raw-byte size covered by the digest.
98    #[must_use]
99    pub const fn size(&self) -> usize {
100        self.size
101    }
102
103    /// Returns the canonical path relative to the Skill root.
104    #[must_use]
105    pub fn relative_path(&self) -> &str {
106        &self.relative_path
107    }
108}
109
110/// One strictly validated static Skill entry from an exact client binding.
111#[derive(Clone)]
112pub struct McpSkillEntry {
113    binding_id: u64,
114    uri: Arc<str>,
115    name: Arc<str>,
116    description: Arc<str>,
117    frontmatter: Arc<Map<String, Value>>,
118    resources: Arc<BTreeMap<String, McpSkillResource>>,
119    manifest_digest: Arc<str>,
120    total_bytes: usize,
121}
122
123impl McpSkillEntry {
124    /// Returns the exact URI of this Skill's `SKILL.md`.
125    #[must_use]
126    pub fn uri(&self) -> &str {
127        &self.uri
128    }
129
130    /// Returns the untrusted Agent Skills name label.
131    #[must_use]
132    pub fn name(&self) -> &str {
133        &self.name
134    }
135
136    /// Returns the untrusted Agent Skills description.
137    #[must_use]
138    pub fn description(&self) -> &str {
139        &self.description
140    }
141
142    /// Returns every advertised frontmatter field unchanged as JSON data.
143    #[must_use]
144    pub fn frontmatter(&self) -> &Map<String, Value> {
145        &self.frontmatter
146    }
147
148    /// Returns the complete manifest in canonical URI order.
149    pub fn resources(&self) -> impl ExactSizeIterator<Item = &McpSkillResource> {
150        self.resources.values()
151    }
152
153    /// Returns the aggregate raw-byte size declared by the manifest.
154    #[must_use]
155    pub const fn total_bytes(&self) -> usize {
156        self.total_bytes
157    }
158
159    /// Returns `StateKnot`'s deterministic binding digest for approval records.
160    ///
161    /// This is not a signature or a trust anchor.
162    #[must_use]
163    pub fn manifest_digest(&self) -> &str {
164        &self.manifest_digest
165    }
166
167    fn skill_document(&self) -> &McpSkillResource {
168        self.resources
169            .get(self.uri())
170            .expect("validated Skill manifests contain SKILL.md")
171    }
172
173    fn resource_by_path(&self, relative_path: &str) -> Option<&McpSkillResource> {
174        self.resources
175            .values()
176            .find(|resource| resource.relative_path() == relative_path)
177    }
178}
179
180impl fmt::Debug for McpSkillEntry {
181    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
182        formatter
183            .debug_struct("McpSkillEntry")
184            .field("uri", &self.uri)
185            .field("name", &self.name)
186            .field("resources", &self.resources.len())
187            .field("total_bytes", &self.total_bytes)
188            .field("manifest_digest", &self.manifest_digest)
189            .finish_non_exhaustive()
190    }
191}
192
193/// One bounded page returned by `skills/list`.
194#[derive(Clone, Debug)]
195pub struct McpSkillPage {
196    skills: Vec<McpSkillEntry>,
197    next_cursor: Option<Box<str>>,
198    cache: McpCachePolicy,
199}
200
201impl McpSkillPage {
202    /// Returns validated static entries in wire order.
203    #[must_use]
204    pub fn skills(&self) -> &[McpSkillEntry] {
205        &self.skills
206    }
207
208    /// Returns the next bounded cursor.
209    #[must_use]
210    pub fn next_cursor(&self) -> Option<&str> {
211        self.next_cursor.as_deref()
212    }
213
214    /// Returns the required list cache metadata.
215    #[must_use]
216    pub const fn cache(&self) -> &McpCachePolicy {
217        &self.cache
218    }
219}
220
221/// Complete bounded static Skill catalog from one server binding.
222#[derive(Clone, Debug)]
223pub struct McpSkillCatalog {
224    skills: Vec<McpSkillEntry>,
225}
226
227impl McpSkillCatalog {
228    /// Returns every validated entry in server pagination order.
229    #[must_use]
230    pub fn skills(&self) -> &[McpSkillEntry] {
231        &self.skills
232    }
233
234    /// Finds one entry by exact URI. Names are deliberately not identifiers.
235    #[must_use]
236    pub fn find_uri(&self, uri: &str) -> Option<&McpSkillEntry> {
237        self.skills.iter().find(|entry| entry.uri() == uri)
238    }
239}
240
241/// Exact raw bytes returned by one base `resources/read` request.
242#[derive(Clone, Debug)]
243pub struct McpSkillResourceContent {
244    uri: Arc<str>,
245    mime_type: Option<Arc<str>>,
246    bytes: Arc<[u8]>,
247}
248
249impl McpSkillResourceContent {
250    /// Returns the exact response resource URI.
251    #[must_use]
252    pub fn uri(&self) -> &str {
253        &self.uri
254    }
255
256    /// Returns the optional validated MIME type.
257    #[must_use]
258    pub fn mime_type(&self) -> Option<&str> {
259        self.mime_type.as_deref()
260    }
261
262    /// Returns decoded raw content bytes.
263    #[must_use]
264    pub fn bytes(&self) -> &[u8] {
265        &self.bytes
266    }
267}
268
269/// Strict MCP Skills client failure.
270#[derive(Debug, Error)]
271#[non_exhaustive]
272pub enum McpSkillClientError {
273    /// The underlying bounded stateless transport failed.
274    #[error(transparent)]
275    Transport(#[from] StatelessMcpClientError),
276    /// This client did not opt into the Skills transport and capability profile.
277    #[error("MCP client was not configured for Skills")]
278    ClientSkillsDisabled,
279    /// Discovery did not advertise the base Resources capability.
280    #[error("MCP server did not advertise the Resources capability required by Skills")]
281    ResourcesNotAdvertised,
282    /// Discovery did not advertise the Skills extension.
283    #[error("MCP server did not advertise the Skills extension")]
284    SkillsNotAdvertised,
285    /// The Skills extension capability object was malformed.
286    #[error("MCP Skills capability is invalid")]
287    InvalidCapability,
288    /// This safe profile declines unverifiable dynamic manifests.
289    #[error("dynamic MCP Skills are unsupported by the static Host profile")]
290    DynamicSkillUnsupported,
291    /// A `skills/list` result violated the Final extension contract.
292    #[error("MCP Skills catalog response is invalid")]
293    InvalidCatalog,
294    /// A `skills/get` result violated the Final extension contract.
295    #[error("MCP Skills lookup response is invalid")]
296    InvalidLookup,
297    /// A Skill entry or complete static manifest was malformed.
298    #[error("MCP Skill entry is invalid")]
299    InvalidEntry,
300    /// A cursor was empty, repeated, or oversized.
301    #[error("MCP Skills pagination cursor is invalid")]
302    InvalidPagination,
303    /// Catalog traversal exceeded the configured page ceiling.
304    #[error("MCP Skills catalog exceeds its page limit")]
305    CatalogPageLimit,
306    /// Catalog traversal exceeded the configured entry ceiling.
307    #[error("MCP Skills catalog exceeds its entry limit")]
308    CatalogTooLarge,
309    /// One URI appeared more than once across catalog pages.
310    #[error("MCP Skills catalog contains a duplicate URI")]
311    DuplicateSkillUri,
312    /// A base Resource result could not be represented as one bounded file.
313    #[error("MCP Skill resource response is invalid")]
314    InvalidResource,
315}
316
317impl McpClient {
318    /// Parses the negotiated Final Skills extension settings.
319    pub fn skill_capabilities(&self) -> Result<McpSkillCapabilities, McpSkillClientError> {
320        if !self.options().skills_enabled() {
321            return Err(McpSkillClientError::ClientSkillsDisabled);
322        }
323        if !self.server().supports_resources() {
324            return Err(McpSkillClientError::ResourcesNotAdvertised);
325        }
326        let extensions = self
327            .server()
328            .capabilities()
329            .get("extensions")
330            .and_then(Value::as_object)
331            .ok_or(McpSkillClientError::SkillsNotAdvertised)?;
332        let value = extensions
333            .get(MCP_SKILLS_EXTENSION_ID)
334            .ok_or(McpSkillClientError::SkillsNotAdvertised)?;
335        let object = value
336            .as_object()
337            .ok_or(McpSkillClientError::InvalidCapability)?;
338        let directory_read = match object.get("directoryRead") {
339            Some(value) => value
340                .as_bool()
341                .ok_or(McpSkillClientError::InvalidCapability)?,
342            None => false,
343        };
344        Ok(McpSkillCapabilities { directory_read })
345    }
346
347    /// Requests one bounded, strictly validated page of static Skills.
348    pub async fn list_skills_page(
349        &self,
350        cursor: Option<&str>,
351    ) -> Result<McpSkillPage, McpSkillClientError> {
352        self.skill_capabilities()?;
353        if cursor.is_some_and(|cursor| cursor.is_empty() || cursor.len() > MAX_CURSOR_BYTES) {
354            return Err(McpSkillClientError::InvalidPagination);
355        }
356        let mut params = Map::new();
357        if let Some(cursor) = cursor {
358            params.insert("cursor".to_owned(), Value::String(cursor.to_owned()));
359        }
360        let result = self
361            .send_extension_rpc(SKILLS_LIST_METHOD, None, params)
362            .await?;
363        parse_skill_page(
364            &result,
365            self.binding_id(),
366            self.options().maximum_skill_catalog_entries(),
367        )
368    }
369
370    /// Traverses a complete bounded static Skill catalog.
371    pub async fn list_skills(&self) -> Result<McpSkillCatalog, McpSkillClientError> {
372        let mut cursor: Option<Box<str>> = None;
373        let mut seen_cursors = HashSet::new();
374        let mut seen_uris = HashSet::new();
375        let mut skills = Vec::new();
376        for _ in 0..self.options().maximum_catalog_pages() {
377            let page = self.list_skills_page(cursor.as_deref()).await?;
378            let next_len = skills
379                .len()
380                .checked_add(page.skills.len())
381                .ok_or(McpSkillClientError::CatalogTooLarge)?;
382            if next_len > self.options().maximum_skill_catalog_entries() {
383                return Err(McpSkillClientError::CatalogTooLarge);
384            }
385            for skill in page.skills {
386                if !seen_uris.insert(skill.uri().to_owned()) {
387                    return Err(McpSkillClientError::DuplicateSkillUri);
388                }
389                skills.push(skill);
390            }
391            let Some(next) = page.next_cursor else {
392                return Ok(McpSkillCatalog { skills });
393            };
394            if !seen_cursors.insert(next.to_string()) {
395                return Err(McpSkillClientError::InvalidPagination);
396            }
397            cursor = Some(next);
398        }
399        Err(McpSkillClientError::CatalogPageLimit)
400    }
401
402    /// Resolves one static Skill by exact URI, independently of listing.
403    pub async fn get_skill(&self, uri: &str) -> Result<McpSkillEntry, McpSkillClientError> {
404        self.skill_capabilities()?;
405        if uri.is_empty() || uri.len() > MAX_SKILL_URI_BYTES {
406            return Err(McpSkillClientError::InvalidEntry);
407        }
408        let result = self
409            .send_extension_rpc(
410                SKILLS_GET_METHOD,
411                None,
412                Map::from_iter([("uri".to_owned(), Value::String(uri.to_owned()))]),
413            )
414            .await?;
415        let object = result
416            .as_object()
417            .ok_or(McpSkillClientError::InvalidLookup)?;
418        validate_complete(object, McpSkillClientError::InvalidLookup)?;
419        parse_required_cache(object).map_err(|()| McpSkillClientError::InvalidLookup)?;
420        let entry = parse_skill_entry(
421            object
422                .get("skill")
423                .ok_or(McpSkillClientError::InvalidLookup)?,
424            self.binding_id(),
425        )?;
426        if entry.uri() != uri {
427            return Err(McpSkillClientError::InvalidLookup);
428        }
429        Ok(entry)
430    }
431
432    /// Reads one resource after Skills capability negotiation.
433    ///
434    /// Host callers must still verify these bytes against a retained entry.
435    pub async fn read_skill_resource(
436        &self,
437        uri: &str,
438    ) -> Result<McpSkillResourceContent, McpSkillClientError> {
439        self.skill_capabilities()?;
440        if uri.is_empty() || uri.len() > MAX_SKILL_URI_BYTES {
441            return Err(McpSkillClientError::InvalidResource);
442        }
443        let result = self
444            .send_extension_rpc(
445                RESOURCE_READ_METHOD,
446                Some(uri),
447                Map::from_iter([("uri".to_owned(), Value::String(uri.to_owned()))]),
448            )
449            .await?;
450        parse_resource_content(&result, uri)
451    }
452}
453
454fn parse_skill_page(
455    value: &Value,
456    binding_id: u64,
457    maximum_entries: usize,
458) -> Result<McpSkillPage, McpSkillClientError> {
459    let object = value
460        .as_object()
461        .ok_or(McpSkillClientError::InvalidCatalog)?;
462    validate_complete(object, McpSkillClientError::InvalidCatalog)?;
463    let cache = parse_required_cache(object).map_err(|()| McpSkillClientError::InvalidCatalog)?;
464    let entries = object
465        .get("skills")
466        .and_then(Value::as_array)
467        .filter(|entries| entries.len() <= maximum_entries)
468        .ok_or(McpSkillClientError::InvalidCatalog)?;
469    let mut skills = Vec::with_capacity(entries.len());
470    let mut seen_uris = HashSet::new();
471    for value in entries {
472        let entry = parse_skill_entry(value, binding_id)?;
473        if !seen_uris.insert(entry.uri().to_owned()) {
474            return Err(McpSkillClientError::DuplicateSkillUri);
475        }
476        skills.push(entry);
477    }
478    let next_cursor = match object.get("nextCursor") {
479        Some(value) => Some(
480            value
481                .as_str()
482                .filter(|cursor| !cursor.is_empty() && cursor.len() <= MAX_CURSOR_BYTES)
483                .ok_or(McpSkillClientError::InvalidPagination)?
484                .to_owned()
485                .into_boxed_str(),
486        ),
487        None => None,
488    };
489    Ok(McpSkillPage {
490        skills,
491        next_cursor,
492        cache,
493    })
494}
495
496fn parse_skill_entry(value: &Value, binding_id: u64) -> Result<McpSkillEntry, McpSkillClientError> {
497    let object = value.as_object().ok_or(McpSkillClientError::InvalidEntry)?;
498    let uri = object
499        .get("uri")
500        .and_then(Value::as_str)
501        .filter(|uri| !uri.is_empty() && uri.len() <= MAX_SKILL_URI_BYTES)
502        .ok_or(McpSkillClientError::InvalidEntry)?;
503    let uri_parent = validate_skill_uri(uri).map_err(|_| McpSkillClientError::InvalidEntry)?;
504    let frontmatter = object
505        .get("frontmatter")
506        .and_then(Value::as_object)
507        .cloned()
508        .ok_or(McpSkillClientError::InvalidEntry)?;
509    if serde_json::to_vec(&frontmatter)
510        .map_err(|_| McpSkillClientError::InvalidEntry)?
511        .len()
512        > MCP_SKILL_MAXIMUM_FRONTMATTER_BYTES
513    {
514        return Err(McpSkillClientError::InvalidEntry);
515    }
516    validate_frontmatter(&frontmatter).map_err(|_| McpSkillClientError::InvalidEntry)?;
517    let name = frontmatter
518        .get("name")
519        .and_then(Value::as_str)
520        .ok_or(McpSkillClientError::InvalidEntry)?;
521    if name != uri_parent {
522        return Err(McpSkillClientError::InvalidEntry);
523    }
524    let description = frontmatter
525        .get("description")
526        .and_then(Value::as_str)
527        .ok_or(McpSkillClientError::InvalidEntry)?;
528    let resources = match object.get("resources") {
529        Some(Value::String(value)) if value == "dynamic" => {
530            return Err(McpSkillClientError::DynamicSkillUnsupported);
531        }
532        Some(Value::Array(resources)) => resources,
533        _ => return Err(McpSkillClientError::InvalidEntry),
534    };
535    if resources.is_empty() || resources.len() > MCP_SKILL_MAXIMUM_FILES {
536        return Err(McpSkillClientError::InvalidEntry);
537    }
538    let root = uri
539        .strip_suffix(SKILL_DOCUMENT)
540        .ok_or(McpSkillClientError::InvalidEntry)?;
541    let mut manifest = BTreeMap::new();
542    let mut total_bytes = 0usize;
543    for resource in resources {
544        let resource = parse_skill_resource(resource, uri, root)?;
545        total_bytes = total_bytes
546            .checked_add(resource.size())
547            .ok_or(McpSkillClientError::InvalidEntry)?;
548        if total_bytes > MCP_SKILL_MAXIMUM_BYTES
549            || manifest
550                .insert(resource.uri().to_owned(), resource)
551                .is_some()
552        {
553            return Err(McpSkillClientError::InvalidEntry);
554        }
555    }
556    if !manifest.contains_key(uri) {
557        return Err(McpSkillClientError::InvalidEntry);
558    }
559    let manifest_digest = manifest_binding_digest(uri, manifest.values());
560    Ok(McpSkillEntry {
561        binding_id,
562        uri: Arc::from(uri),
563        name: Arc::from(name),
564        description: Arc::from(description),
565        frontmatter: Arc::new(frontmatter),
566        resources: Arc::new(manifest),
567        manifest_digest: Arc::from(manifest_digest),
568        total_bytes,
569    })
570}
571
572fn parse_skill_resource(
573    value: &Value,
574    skill_uri: &str,
575    root: &str,
576) -> Result<McpSkillResource, McpSkillClientError> {
577    let object = value.as_object().ok_or(McpSkillClientError::InvalidEntry)?;
578    let uri = object
579        .get("uri")
580        .and_then(Value::as_str)
581        .filter(|uri| !uri.is_empty() && uri.len() <= MAX_SKILL_URI_BYTES)
582        .ok_or(McpSkillClientError::InvalidEntry)?;
583    let relative_path = if uri == skill_uri {
584        SKILL_DOCUMENT
585    } else {
586        uri.strip_prefix(root)
587            .ok_or(McpSkillClientError::InvalidEntry)?
588    };
589    validate_relative_path(relative_path).map_err(|_| McpSkillClientError::InvalidEntry)?;
590    if format!("{root}{relative_path}") != uri {
591        return Err(McpSkillClientError::InvalidEntry);
592    }
593    let digest = object
594        .get("digest")
595        .and_then(Value::as_str)
596        .filter(|digest| valid_sha256(digest))
597        .ok_or(McpSkillClientError::InvalidEntry)?;
598    let size = object
599        .get("size")
600        .and_then(Value::as_u64)
601        .and_then(|size| usize::try_from(size).ok())
602        .filter(|size| *size <= MCP_SKILL_MAXIMUM_BYTES)
603        .ok_or(McpSkillClientError::InvalidEntry)?;
604    Ok(McpSkillResource {
605        uri: Arc::from(uri),
606        digest: Arc::from(digest),
607        size,
608        relative_path: Arc::from(relative_path),
609    })
610}
611
612fn valid_sha256(value: &str) -> bool {
613    value.len() == 71
614        && value.starts_with("sha256:")
615        && value[7..]
616            .bytes()
617            .all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f'))
618}
619
620fn manifest_binding_digest<'a>(
621    skill_uri: &str,
622    resources: impl Iterator<Item = &'a McpSkillResource>,
623) -> String {
624    let mut material = b"stateknot/mcp-skills/approval/v1".to_vec();
625    append_digest_part(&mut material, skill_uri.as_bytes());
626    for resource in resources {
627        append_digest_part(&mut material, resource.uri().as_bytes());
628        append_digest_part(&mut material, resource.digest().as_bytes());
629        append_digest_part(&mut material, &(resource.size() as u64).to_be_bytes());
630    }
631    Digest::sha256(material).to_string()
632}
633
634fn append_digest_part(target: &mut Vec<u8>, value: &[u8]) {
635    target.extend_from_slice(&(value.len() as u64).to_be_bytes());
636    target.extend_from_slice(value);
637}
638
639fn parse_resource_content(
640    value: &Value,
641    expected_uri: &str,
642) -> Result<McpSkillResourceContent, McpSkillClientError> {
643    let object = value
644        .as_object()
645        .ok_or(McpSkillClientError::InvalidResource)?;
646    validate_complete(object, McpSkillClientError::InvalidResource)?;
647    let contents = object
648        .get("contents")
649        .and_then(Value::as_array)
650        .filter(|contents| contents.len() == 1)
651        .ok_or(McpSkillClientError::InvalidResource)?;
652    let content = contents[0]
653        .as_object()
654        .ok_or(McpSkillClientError::InvalidResource)?;
655    let uri = content
656        .get("uri")
657        .and_then(Value::as_str)
658        .filter(|uri| *uri == expected_uri)
659        .ok_or(McpSkillClientError::InvalidResource)?;
660    let mime_type = match content.get("mimeType") {
661        Some(value) => {
662            let mime = value
663                .as_str()
664                .filter(|mime| {
665                    !mime.is_empty()
666                        && mime.len() <= MAX_MIME_TYPE_BYTES
667                        && mime.trim() == *mime
668                        && mime.parse::<mime::Mime>().is_ok()
669                })
670                .ok_or(McpSkillClientError::InvalidResource)?;
671            Some(Arc::from(mime))
672        }
673        None => None,
674    };
675    let bytes = match (content.get("text"), content.get("blob")) {
676        (Some(Value::String(text)), None) => text.as_bytes().to_vec(),
677        (None, Some(Value::String(blob))) => BASE64_STANDARD
678            .decode(blob)
679            .map_err(|_| McpSkillClientError::InvalidResource)?,
680        _ => return Err(McpSkillClientError::InvalidResource),
681    };
682    if bytes.len() > MCP_SKILL_MAXIMUM_BYTES {
683        return Err(McpSkillClientError::InvalidResource);
684    }
685    Ok(McpSkillResourceContent {
686        uri: Arc::from(uri),
687        mime_type,
688        bytes: Arc::from(bytes),
689    })
690}
691
692fn validate_complete(
693    object: &Map<String, Value>,
694    error: McpSkillClientError,
695) -> Result<(), McpSkillClientError> {
696    if object.get("resultType").and_then(Value::as_str) == Some("complete") {
697        Ok(())
698    } else {
699        Err(error)
700    }
701}
702
703fn parse_required_cache(object: &Map<String, Value>) -> Result<McpCachePolicy, ()> {
704    let ttl_ms = object.get("ttlMs").and_then(Value::as_u64).ok_or(())?;
705    let scope = object
706        .get("cacheScope")
707        .and_then(Value::as_str)
708        .filter(|scope| matches!(*scope, "private" | "public"))
709        .ok_or(())?;
710    Ok(McpCachePolicy::required(ttl_ms, scope.into()))
711}
712
713/// Host-assigned server label used in every Skill identity and model-visible file.
714#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
715pub struct McpSkillOrigin(Arc<str>);
716
717impl McpSkillOrigin {
718    /// Constructs a bounded printable label. Never use self-reported server info.
719    pub fn new(value: impl Into<String>) -> Result<Self, McpSkillOriginError> {
720        let value = value.into();
721        if value.is_empty() {
722            return Err(McpSkillOriginError::Empty);
723        }
724        if value.len() > MAX_ORIGIN_LABEL_BYTES {
725            return Err(McpSkillOriginError::TooLong);
726        }
727        if value.trim() != value {
728            return Err(McpSkillOriginError::BoundaryWhitespace);
729        }
730        if value.chars().any(char::is_control) {
731            return Err(McpSkillOriginError::ControlCharacter);
732        }
733        Ok(Self(Arc::from(value)))
734    }
735
736    /// Returns the exact host-assigned label.
737    #[must_use]
738    pub fn as_str(&self) -> &str {
739        &self.0
740    }
741}
742
743impl fmt::Debug for McpSkillOrigin {
744    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
745        formatter
746            .debug_tuple("McpSkillOrigin")
747            .field(&self.0)
748            .finish()
749    }
750}
751
752/// Invalid host-assigned MCP server label.
753#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
754#[non_exhaustive]
755pub enum McpSkillOriginError {
756    /// The label was empty.
757    #[error("MCP Skill origin label is empty")]
758    Empty,
759    /// The label exceeded 128 bytes.
760    #[error("MCP Skill origin label is too long")]
761    TooLong,
762    /// Trimming would change the label.
763    #[error("MCP Skill origin label has boundary whitespace")]
764    BoundaryWhitespace,
765    /// The label contained a control character.
766    #[error("MCP Skill origin label contains a control character")]
767    ControlCharacter,
768}
769
770/// Collision-safe identity: host-assigned origin plus exact server-scoped URI.
771#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
772pub struct McpSkillIdentity {
773    origin: McpSkillOrigin,
774    uri: Arc<str>,
775}
776
777impl McpSkillIdentity {
778    /// Returns the host-assigned server origin.
779    #[must_use]
780    pub fn origin(&self) -> &McpSkillOrigin {
781        &self.origin
782    }
783
784    /// Returns the exact URI within that origin.
785    #[must_use]
786    pub fn uri(&self) -> &str {
787        &self.uri
788    }
789}
790
791/// Why a fresh Skill activation was requested.
792#[derive(Clone, Debug, Eq, PartialEq)]
793#[non_exhaustive]
794pub enum McpSkillActivationSource {
795    /// User or host selected a top-level Skill directly.
796    Direct,
797    /// An active Skill requested one of its manifest-listed nested Skills.
798    Nested {
799        /// Collision-safe identity of the parent Skill.
800        identity: McpSkillIdentity,
801        /// Durable authority window of the parent Skill.
802        parent_window_id: SkillActingWindowId,
803    },
804}
805
806/// Caller-retained idempotency identities for one activation attempt.
807#[derive(Clone, Copy, Debug, Eq, PartialEq)]
808pub struct McpSkillActivationAttempt {
809    approval_id: SkillActivationApprovalId,
810    window_id: SkillActingWindowId,
811}
812
813impl McpSkillActivationAttempt {
814    /// Generates fresh `UUIDv7` identities which callers retain across retries.
815    #[must_use]
816    pub fn generate() -> Self {
817        Self {
818            approval_id: SkillActivationApprovalId::generate(),
819            window_id: SkillActingWindowId::generate(),
820        }
821    }
822
823    /// Constructs an explicit retry-stable activation attempt.
824    #[must_use]
825    pub const fn new(
826        approval_id: SkillActivationApprovalId,
827        window_id: SkillActingWindowId,
828    ) -> Self {
829        Self {
830            approval_id,
831            window_id,
832        }
833    }
834
835    /// Returns the immutable approval identity.
836    #[must_use]
837    pub const fn approval_id(self) -> SkillActivationApprovalId {
838        self.approval_id
839    }
840
841    /// Returns the durable acting-window identity.
842    #[must_use]
843    pub const fn window_id(self) -> SkillActingWindowId {
844        self.window_id
845    }
846}
847
848/// Owned, content-bound facts presented before a Skill is fetched or activated.
849#[derive(Clone, Debug)]
850pub struct McpSkillActivationRequest {
851    identity: McpSkillIdentity,
852    source: McpSkillActivationSource,
853    entry: McpSkillEntry,
854    scope: SkillActivationScope,
855    attempt: McpSkillActivationAttempt,
856}
857
858impl McpSkillActivationRequest {
859    /// Returns the collision-safe identity being approved.
860    #[must_use]
861    pub const fn identity(&self) -> &McpSkillIdentity {
862        &self.identity
863    }
864
865    /// Returns whether this is direct or fresh nested activation.
866    #[must_use]
867    pub const fn source(&self) -> &McpSkillActivationSource {
868        &self.source
869    }
870
871    /// Returns the exact entry whose complete Manifest binds the decision.
872    #[must_use]
873    pub const fn entry(&self) -> &McpSkillEntry {
874        &self.entry
875    }
876
877    /// Returns the exact durable run scope receiving authority.
878    #[must_use]
879    pub fn scope(&self) -> &SkillActivationScope {
880        &self.scope
881    }
882
883    /// Returns the caller-retained idempotency identities.
884    #[must_use]
885    pub const fn attempt(&self) -> McpSkillActivationAttempt {
886        self.attempt
887    }
888
889    /// Returns the untrusted `allowed-tools` request, without granting it.
890    #[must_use]
891    pub fn requested_allowed_tools(&self) -> Option<&str> {
892        self.entry
893            .frontmatter()
894            .get("allowed-tools")
895            .and_then(Value::as_str)
896    }
897}
898
899/// Owned facts for one Tool operation proposed during an active Skill window.
900#[derive(Clone, Debug)]
901pub struct McpSkillToolAuthorizationRequest {
902    identity: McpSkillIdentity,
903    manifest_digest: Arc<str>,
904    activation_id: u64,
905    acting_window_id: SkillActingWindowId,
906    tool_name: Arc<str>,
907    tool_identity: Option<CapabilityIdentity>,
908    tool_descriptor_digest: Option<Digest>,
909    operation: McpSkillToolOperation,
910    invocation: Option<McpSkillToolInvocation>,
911    host_code_execution: bool,
912    requested_allowed_tools: Option<Arc<str>>,
913}
914
915impl McpSkillToolAuthorizationRequest {
916    /// Returns the collision-safe active Skill identity.
917    #[must_use]
918    pub const fn identity(&self) -> &McpSkillIdentity {
919        &self.identity
920    }
921
922    /// Returns the complete Manifest binding digest.
923    #[must_use]
924    pub fn manifest_digest(&self) -> &str {
925        &self.manifest_digest
926    }
927
928    /// Returns this process-local activation identifier.
929    #[must_use]
930    pub const fn activation_id(&self) -> u64 {
931        self.activation_id
932    }
933
934    /// Returns the durable authority window for this operation.
935    #[must_use]
936    pub const fn acting_window_id(&self) -> SkillActingWindowId {
937        self.acting_window_id
938    }
939
940    /// Returns the exact proposed host Tool name.
941    #[must_use]
942    pub fn tool_name(&self) -> &str {
943        &self.tool_name
944    }
945
946    /// Returns the exact owner-qualified Tool version for a runtime-bound call.
947    ///
948    /// Name-only custom execution paths return `None`; policies may reject
949    /// those paths when an exact registry binding is required.
950    #[must_use]
951    pub const fn tool_identity(&self) -> Option<&CapabilityIdentity> {
952        self.tool_identity.as_ref()
953    }
954
955    /// Returns the canonical descriptor digest for a runtime-bound call.
956    #[must_use]
957    pub const fn tool_descriptor_digest(&self) -> Option<Digest> {
958        self.tool_descriptor_digest
959    }
960
961    /// Returns whether execution or recovery reconciliation was requested.
962    #[must_use]
963    pub const fn operation(&self) -> McpSkillToolOperation {
964        self.operation
965    }
966
967    /// Returns exact bounded invocation facts for a runtime-bound operation.
968    ///
969    /// Name-only custom execution paths return `None`.
970    #[must_use]
971    pub const fn invocation(&self) -> Option<&McpSkillToolInvocation> {
972        self.invocation.as_ref()
973    }
974
975    /// Returns whether the Tool can execute code on the Host.
976    #[must_use]
977    pub const fn host_code_execution(&self) -> bool {
978        self.host_code_execution
979    }
980
981    /// Returns the untrusted frontmatter request for UI comparison only.
982    #[must_use]
983    pub fn requested_allowed_tools(&self) -> Option<&str> {
984        self.requested_allowed_tools.as_deref()
985    }
986}
987
988/// Explicit application policy for activation and every acting-window Tool call.
989pub trait McpSkillHostPolicy: Send + Sync + 'static {
990    /// Obtains fresh user/policy consent before any Skill file is fetched.
991    fn approve_activation(
992        &self,
993        request: McpSkillActivationRequest,
994    ) -> BoxFuture<'_, Result<McpSkillActivationGrant, McpSkillHostPolicyError>>;
995
996    /// Authorizes one exact Tool operation without trusting `allowed-tools` as a grant.
997    fn authorize_tool_call(
998        &self,
999        request: McpSkillToolAuthorizationRequest,
1000    ) -> BoxFuture<'_, Result<McpSkillToolAuthorizationGrant, McpSkillHostPolicyError>>;
1001}
1002
1003/// Exact policy evidence and bounded authority lifetime for an activation.
1004#[derive(Clone, Debug, Eq, PartialEq)]
1005pub struct McpSkillActivationGrant {
1006    policy: CapabilityIdentity,
1007    policy_digest: Digest,
1008    decision_digest: Digest,
1009    duration: SkillActingWindowDuration,
1010}
1011
1012impl McpSkillActivationGrant {
1013    /// Constructs a version-pinned activation grant.
1014    #[must_use]
1015    pub const fn new(
1016        policy: CapabilityIdentity,
1017        policy_digest: Digest,
1018        decision_digest: Digest,
1019        duration: SkillActingWindowDuration,
1020    ) -> Self {
1021        Self {
1022            policy,
1023            policy_digest,
1024            decision_digest,
1025            duration,
1026        }
1027    }
1028
1029    /// Returns the policy implementation identity.
1030    #[must_use]
1031    pub const fn policy(&self) -> &CapabilityIdentity {
1032        &self.policy
1033    }
1034
1035    /// Returns the immutable policy artifact binding.
1036    #[must_use]
1037    pub const fn policy_digest(&self) -> Digest {
1038        self.policy_digest
1039    }
1040
1041    /// Returns the private decision-evidence binding.
1042    #[must_use]
1043    pub const fn decision_digest(&self) -> Digest {
1044        self.decision_digest
1045    }
1046
1047    /// Returns the approved bounded lifetime.
1048    #[must_use]
1049    pub const fn duration(&self) -> SkillActingWindowDuration {
1050        self.duration
1051    }
1052}
1053
1054/// Exact policy evidence retained by a successful Skill Tool authorization.
1055///
1056/// The decision digest binds private policy inputs without placing them in the
1057/// permit or durable authorization receipt.
1058#[derive(Clone, Debug, Eq, PartialEq)]
1059pub struct McpSkillToolAuthorizationGrant {
1060    policy: CapabilityIdentity,
1061    policy_digest: Digest,
1062    decision_digest: Digest,
1063}
1064
1065impl McpSkillToolAuthorizationGrant {
1066    /// Constructs exact immutable policy evidence for one decision.
1067    #[must_use]
1068    pub const fn new(
1069        policy: CapabilityIdentity,
1070        policy_digest: Digest,
1071        decision_digest: Digest,
1072    ) -> Self {
1073        Self {
1074            policy,
1075            policy_digest,
1076            decision_digest,
1077        }
1078    }
1079
1080    /// Returns the owner-qualified, version-pinned policy implementation.
1081    #[must_use]
1082    pub const fn policy(&self) -> &CapabilityIdentity {
1083        &self.policy
1084    }
1085
1086    /// Returns the immutable policy artifact binding.
1087    #[must_use]
1088    pub const fn policy_digest(&self) -> Digest {
1089        self.policy_digest
1090    }
1091
1092    /// Returns the policy-supplied exact decision evidence binding.
1093    #[must_use]
1094    pub const fn decision_digest(&self) -> Digest {
1095        self.decision_digest
1096    }
1097}
1098
1099/// Safe default denying all remote Skill activation and execution.
1100#[derive(Clone, Copy, Debug, Default)]
1101pub struct DenyMcpSkillHostPolicy;
1102
1103impl McpSkillHostPolicy for DenyMcpSkillHostPolicy {
1104    fn approve_activation(
1105        &self,
1106        _request: McpSkillActivationRequest,
1107    ) -> BoxFuture<'_, Result<McpSkillActivationGrant, McpSkillHostPolicyError>> {
1108        Box::pin(async { Err(McpSkillHostPolicyError::Denied) })
1109    }
1110
1111    fn authorize_tool_call(
1112        &self,
1113        _request: McpSkillToolAuthorizationRequest,
1114    ) -> BoxFuture<'_, Result<McpSkillToolAuthorizationGrant, McpSkillHostPolicyError>> {
1115        Box::pin(async { Err(McpSkillHostPolicyError::Denied) })
1116    }
1117}
1118
1119/// Public-safe Host policy failure.
1120#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
1121#[non_exhaustive]
1122pub enum McpSkillHostPolicyError {
1123    /// User or policy denied this exact operation.
1124    #[error("MCP Skill Host policy denied the operation")]
1125    Denied,
1126    /// The policy authority is temporarily unavailable.
1127    #[error("MCP Skill Host policy is unavailable")]
1128    Unavailable,
1129}
1130
1131/// Bounded private memory-cache policy for verified files.
1132#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1133pub struct McpSkillHostOptions {
1134    maximum_cache_entries: usize,
1135    maximum_cache_bytes: usize,
1136}
1137
1138impl McpSkillHostOptions {
1139    /// Hard process-local cache entry ceiling.
1140    pub const HARD_MAXIMUM_CACHE_ENTRIES: usize = 65_536;
1141    /// Hard process-local cache byte ceiling.
1142    pub const HARD_MAXIMUM_CACHE_BYTES: usize = 1024 * MEBIBYTE;
1143
1144    /// Constructs positive cache limits within implementation ceilings.
1145    pub const fn new(
1146        maximum_cache_entries: usize,
1147        maximum_cache_bytes: usize,
1148    ) -> Result<Self, McpSkillHostOptionsError> {
1149        if maximum_cache_entries == 0 || maximum_cache_bytes == 0 {
1150            return Err(McpSkillHostOptionsError::ZeroLimit);
1151        }
1152        if maximum_cache_entries > Self::HARD_MAXIMUM_CACHE_ENTRIES
1153            || maximum_cache_bytes > Self::HARD_MAXIMUM_CACHE_BYTES
1154        {
1155            return Err(McpSkillHostOptionsError::AboveHardMaximum);
1156        }
1157        Ok(Self {
1158            maximum_cache_entries,
1159            maximum_cache_bytes,
1160        })
1161    }
1162
1163    /// Returns the process-local verified-file entry ceiling.
1164    #[must_use]
1165    pub const fn maximum_cache_entries(self) -> usize {
1166        self.maximum_cache_entries
1167    }
1168
1169    /// Returns the process-local verified-file byte ceiling.
1170    #[must_use]
1171    pub const fn maximum_cache_bytes(self) -> usize {
1172        self.maximum_cache_bytes
1173    }
1174}
1175
1176impl Default for McpSkillHostOptions {
1177    fn default() -> Self {
1178        Self {
1179            maximum_cache_entries: 4096,
1180            maximum_cache_bytes: 64 * MEBIBYTE,
1181        }
1182    }
1183}
1184
1185/// Invalid MCP Skill Host cache policy.
1186#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
1187#[non_exhaustive]
1188pub enum McpSkillHostOptionsError {
1189    /// Cache limits must be positive.
1190    #[error("MCP Skill Host cache limits must be positive")]
1191    ZeroLimit,
1192    /// A cache limit exceeded its hard ceiling.
1193    #[error("MCP Skill Host cache limit exceeds the hard maximum")]
1194    AboveHardMaximum,
1195}
1196
1197#[derive(Clone, Debug, Eq, Hash, PartialEq)]
1198struct CacheKey {
1199    binding_id: u64,
1200    origin: McpSkillOrigin,
1201    uri: Arc<str>,
1202    digest: Arc<str>,
1203    size: usize,
1204}
1205
1206#[derive(Default)]
1207struct MemoryCache {
1208    entries: HashMap<CacheKey, Arc<McpSkillResourceContent>>,
1209    bytes: usize,
1210}
1211
1212struct McpSkillHostInner {
1213    client: McpClient,
1214    origin: McpSkillOrigin,
1215    scope: SkillActivationScope,
1216    policy: Arc<dyn McpSkillHostPolicy>,
1217    activation_store: Arc<dyn SkillActivationStore>,
1218    options: McpSkillHostOptions,
1219    cache: Mutex<MemoryCache>,
1220    next_activation_id: AtomicU64,
1221}
1222
1223/// Secure static-manifest Host bound to one exact MCP client and assigned origin.
1224#[derive(Clone)]
1225pub struct McpSkillHost {
1226    inner: Arc<McpSkillHostInner>,
1227}
1228
1229impl McpSkillHost {
1230    /// Builds a fail-closed Host. Use [`crate::McpClientOptions::for_skills`]
1231    /// when connecting the underlying client.
1232    pub fn new(
1233        client: McpClient,
1234        origin: McpSkillOrigin,
1235        scope: SkillActivationScope,
1236        policy: Arc<dyn McpSkillHostPolicy>,
1237        activation_store: Arc<dyn SkillActivationStore>,
1238        options: McpSkillHostOptions,
1239    ) -> Result<Self, McpSkillHostError> {
1240        let transport = client.options().transport();
1241        if transport.maximum_response_bytes() < MCP_SKILL_WIRE_RESPONSE_BYTES
1242            || transport.maximum_sse_line_bytes() < MCP_SKILL_WIRE_RESPONSE_BYTES
1243            || transport.maximum_sse_event_bytes() < MCP_SKILL_WIRE_RESPONSE_BYTES
1244            || transport.maximum_sse_total_bytes() < MCP_SKILL_WIRE_RESPONSE_BYTES
1245        {
1246            return Err(McpSkillHostError::TransportProfileTooSmall);
1247        }
1248        client.skill_capabilities()?;
1249        Ok(Self {
1250            inner: Arc::new(McpSkillHostInner {
1251                client,
1252                origin,
1253                scope,
1254                policy,
1255                activation_store,
1256                options,
1257                cache: Mutex::new(MemoryCache::default()),
1258                next_activation_id: AtomicU64::new(1),
1259            }),
1260        })
1261    }
1262
1263    /// Returns the host-assigned origin, never self-reported server metadata.
1264    #[must_use]
1265    pub fn origin(&self) -> &McpSkillOrigin {
1266        &self.inner.origin
1267    }
1268
1269    /// Returns the exact durable run scope receiving Skill authority.
1270    #[must_use]
1271    pub fn scope(&self) -> &SkillActivationScope {
1272        &self.inner.scope
1273    }
1274
1275    /// Lists entries without fetching any Skill files.
1276    pub async fn list_skills(&self) -> Result<McpSkillCatalog, McpSkillHostError> {
1277        Ok(self.inner.client.list_skills().await?)
1278    }
1279
1280    /// Resolves one entry without fetching its Skill files.
1281    pub async fn get_skill(&self, uri: &str) -> Result<McpSkillEntry, McpSkillHostError> {
1282        Ok(self.inner.client.get_skill(uri).await?)
1283    }
1284
1285    /// Assigns the collision-safe identity for one entry from this binding.
1286    pub fn identity(&self, entry: &McpSkillEntry) -> Result<McpSkillIdentity, McpSkillHostError> {
1287        self.require_local_entry(entry)?;
1288        Ok(McpSkillIdentity {
1289            origin: self.inner.origin.clone(),
1290            uri: entry.uri.clone(),
1291        })
1292    }
1293
1294    /// Resolves, approves, verifies, and activates one exact URI.
1295    pub async fn activate_uri(
1296        &self,
1297        uri: &str,
1298        attempt: McpSkillActivationAttempt,
1299    ) -> Result<McpActivatedSkill, McpSkillHostError> {
1300        let entry = self.get_skill(uri).await?;
1301        self.activate_entry(entry, McpSkillActivationSource::Direct, attempt)
1302            .await
1303    }
1304
1305    /// Freshly approves and activates one listed entry.
1306    pub async fn activate(
1307        &self,
1308        entry: &McpSkillEntry,
1309        attempt: McpSkillActivationAttempt,
1310    ) -> Result<McpActivatedSkill, McpSkillHostError> {
1311        self.activate_entry(entry.clone(), McpSkillActivationSource::Direct, attempt)
1312            .await
1313    }
1314
1315    async fn activate_entry(
1316        &self,
1317        entry: McpSkillEntry,
1318        source: McpSkillActivationSource,
1319        attempt: McpSkillActivationAttempt,
1320    ) -> Result<McpActivatedSkill, McpSkillHostError> {
1321        let identity = self.identity(&entry)?;
1322        let grant = self
1323            .inner
1324            .policy
1325            .approve_activation(McpSkillActivationRequest {
1326                identity: identity.clone(),
1327                source: source.clone(),
1328                entry: entry.clone(),
1329                scope: self.inner.scope.clone(),
1330                attempt,
1331            })
1332            .await
1333            .map_err(map_activation_policy_error)?;
1334        let instructions = self.verify_instructions(&identity, &entry).await?;
1335        let subject = Self::authorization_subject(&identity, &entry)?;
1336        let durable_source = match source {
1337            McpSkillActivationSource::Direct => SkillActivationSource::Direct,
1338            McpSkillActivationSource::Nested {
1339                parent_window_id, ..
1340            } => SkillActivationSource::Nested { parent_window_id },
1341        };
1342        let approval = SkillActivationApproval::new(
1343            attempt.approval_id(),
1344            self.inner.scope.clone(),
1345            subject,
1346            durable_source,
1347            grant.policy().clone(),
1348            grant.policy_digest(),
1349            grant.decision_digest(),
1350            grant.duration(),
1351        )
1352        .map_err(|_| McpSkillHostError::ActivationEvidenceInvalid)?;
1353        let window = self
1354            .inner
1355            .activation_store
1356            .open(SkillActingWindowOpenRequest::new(
1357                attempt.window_id(),
1358                approval.clone(),
1359            ))
1360            .await
1361            .map_err(map_activation_store_error)?;
1362        if window.window_id() != attempt.window_id() || window.approval() != &approval {
1363            return Err(McpSkillHostError::ActivationStoreRejected);
1364        }
1365        self.inner
1366            .activation_store
1367            .assert_active(window.clone())
1368            .await
1369            .map_err(map_activation_store_error)?;
1370        self.finish_activation(identity, entry, instructions, window)
1371    }
1372
1373    /// Restores one exact, unexpired, unrevoked acting window after restart.
1374    pub async fn resume(
1375        &self,
1376        entry: &McpSkillEntry,
1377        window_id: SkillActingWindowId,
1378    ) -> Result<McpActivatedSkill, McpSkillHostError> {
1379        self.require_local_entry(entry)?;
1380        let window = self
1381            .inner
1382            .activation_store
1383            .load_active(self.inner.scope.tenant_id().clone(), window_id)
1384            .await
1385            .map_err(map_activation_store_error)?;
1386        let identity = self.identity(entry)?;
1387        let subject = Self::authorization_subject(&identity, entry)?;
1388        if window.approval().scope() != &self.inner.scope || window.approval().subject() != &subject
1389        {
1390            return Err(McpSkillHostError::ActivationStoreRejected);
1391        }
1392        let instructions = self.verify_instructions(&identity, entry).await?;
1393        self.inner
1394            .activation_store
1395            .assert_active(window.clone())
1396            .await
1397            .map_err(map_activation_store_error)?;
1398        self.finish_activation(identity, entry.clone(), instructions, window)
1399    }
1400
1401    fn finish_activation(
1402        &self,
1403        identity: McpSkillIdentity,
1404        entry: McpSkillEntry,
1405        instructions: McpVerifiedSkillFile,
1406        window: SkillActingWindow,
1407    ) -> Result<McpActivatedSkill, McpSkillHostError> {
1408        let activation_id = allocate_monotonic_id(&self.inner.next_activation_id)
1409            .ok_or(McpSkillHostError::ActivationIdExhausted)?;
1410        Ok(McpActivatedSkill {
1411            host: self.clone(),
1412            identity,
1413            entry,
1414            instructions,
1415            activation_id,
1416            window,
1417        })
1418    }
1419
1420    async fn verify_instructions(
1421        &self,
1422        identity: &McpSkillIdentity,
1423        entry: &McpSkillEntry,
1424    ) -> Result<McpVerifiedSkillFile, McpSkillHostError> {
1425        let instructions = self
1426            .verified_file(identity, entry, entry.skill_document())
1427            .await?;
1428        let text = std::str::from_utf8(instructions.bytes())
1429            .map_err(|_| McpSkillHostError::SkillDocumentNotUtf8)?;
1430        let frontmatter = parse_frontmatter(text)
1431            .map_err(|_| McpSkillHostError::FrontmatterVerificationFailed)?;
1432        if &frontmatter != entry.frontmatter() {
1433            return Err(McpSkillHostError::FrontmatterVerificationFailed);
1434        }
1435        Ok(instructions)
1436    }
1437
1438    fn authorization_subject(
1439        identity: &McpSkillIdentity,
1440        entry: &McpSkillEntry,
1441    ) -> Result<SkillAuthorizationSubject, McpSkillHostError> {
1442        let manifest_digest = entry
1443            .manifest_digest()
1444            .parse()
1445            .map_err(|_| McpSkillHostError::ActivationEvidenceInvalid)?;
1446        SkillAuthorizationSubject::new(
1447            "mcp",
1448            identity.origin().as_str(),
1449            identity.uri(),
1450            manifest_digest,
1451        )
1452        .map_err(|_| McpSkillHostError::ActivationEvidenceInvalid)
1453    }
1454
1455    async fn verified_file(
1456        &self,
1457        identity: &McpSkillIdentity,
1458        entry: &McpSkillEntry,
1459        resource: &McpSkillResource,
1460    ) -> Result<McpVerifiedSkillFile, McpSkillHostError> {
1461        self.require_local_entry(entry)?;
1462        let key = CacheKey {
1463            binding_id: entry.binding_id,
1464            origin: identity.origin.clone(),
1465            uri: resource.uri.clone(),
1466            digest: resource.digest.clone(),
1467            size: resource.size,
1468        };
1469        if let Some(content) = self
1470            .inner
1471            .cache
1472            .lock()
1473            .map_err(|_| McpSkillHostError::CacheUnavailable)?
1474            .entries
1475            .get(&key)
1476            .cloned()
1477        {
1478            return Ok(McpVerifiedSkillFile::new(
1479                identity.clone(),
1480                resource.relative_path.clone(),
1481                content,
1482            ));
1483        }
1484        let content = Arc::new(
1485            self.inner
1486                .client
1487                .read_skill_resource(resource.uri())
1488                .await?,
1489        );
1490        verify_resource(resource, &content)?;
1491        let mut cache = self
1492            .inner
1493            .cache
1494            .lock()
1495            .map_err(|_| McpSkillHostError::CacheUnavailable)?;
1496        if let Some(existing) = cache.entries.get(&key).cloned() {
1497            return Ok(McpVerifiedSkillFile::new(
1498                identity.clone(),
1499                resource.relative_path.clone(),
1500                existing,
1501            ));
1502        }
1503        let next_bytes = cache.bytes.checked_add(content.bytes().len());
1504        if cache.entries.len() < self.inner.options.maximum_cache_entries
1505            && next_bytes.is_some_and(|bytes| bytes <= self.inner.options.maximum_cache_bytes)
1506        {
1507            cache.bytes = next_bytes.expect("checked cache size exists");
1508            cache.entries.insert(key, Arc::clone(&content));
1509        }
1510        Ok(McpVerifiedSkillFile::new(
1511            identity.clone(),
1512            resource.relative_path.clone(),
1513            content,
1514        ))
1515    }
1516
1517    fn require_local_entry(&self, entry: &McpSkillEntry) -> Result<(), McpSkillHostError> {
1518        if entry.binding_id == self.inner.client.binding_id() {
1519            Ok(())
1520        } else {
1521            Err(McpSkillHostError::ForeignClientBinding)
1522        }
1523    }
1524}
1525
1526impl fmt::Debug for McpSkillHost {
1527    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1528        formatter
1529            .debug_struct("McpSkillHost")
1530            .field("origin", &self.inner.origin)
1531            .field("scope", &self.inner.scope)
1532            .field("client", &self.inner.client)
1533            .field("options", &self.inner.options)
1534            .field("policy", &"[POLICY]")
1535            .field("activation_store", &"[DURABLE STORE]")
1536            .finish_non_exhaustive()
1537    }
1538}
1539
1540/// One verified, origin-tagged file safe to expose only as untrusted MCP input.
1541#[derive(Clone)]
1542pub struct McpVerifiedSkillFile {
1543    identity: McpSkillIdentity,
1544    relative_path: Arc<str>,
1545    content: Arc<McpSkillResourceContent>,
1546}
1547
1548impl McpVerifiedSkillFile {
1549    fn new(
1550        identity: McpSkillIdentity,
1551        relative_path: Arc<str>,
1552        content: Arc<McpSkillResourceContent>,
1553    ) -> Self {
1554        Self {
1555            identity,
1556            relative_path,
1557            content,
1558        }
1559    }
1560
1561    /// Returns the collision-safe MCP origin tag that must remain model-visible.
1562    #[must_use]
1563    pub const fn identity(&self) -> &McpSkillIdentity {
1564        &self.identity
1565    }
1566
1567    /// Returns the canonical path relative to the active Skill root.
1568    #[must_use]
1569    pub fn relative_path(&self) -> &str {
1570        &self.relative_path
1571    }
1572
1573    /// Returns the exact originating Resource URI.
1574    #[must_use]
1575    pub fn uri(&self) -> &str {
1576        self.content.uri()
1577    }
1578
1579    /// Returns the server-declared MIME type after syntax validation.
1580    #[must_use]
1581    pub fn mime_type(&self) -> Option<&str> {
1582        self.content.mime_type()
1583    }
1584
1585    /// Returns digest- and size-verified raw bytes.
1586    #[must_use]
1587    pub fn bytes(&self) -> &[u8] {
1588        self.content.bytes()
1589    }
1590
1591    /// Returns verified UTF-8 text when representable.
1592    #[must_use]
1593    pub fn text(&self) -> Option<&str> {
1594        std::str::from_utf8(self.bytes()).ok()
1595    }
1596}
1597
1598impl fmt::Debug for McpVerifiedSkillFile {
1599    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1600        formatter
1601            .debug_struct("McpVerifiedSkillFile")
1602            .field("identity", &self.identity)
1603            .field("relative_path", &self.relative_path)
1604            .field("uri", &self.content.uri)
1605            .field("size", &self.content.bytes.len())
1606            .finish_non_exhaustive()
1607    }
1608}
1609
1610/// Direct child derived locally from the retained complete Manifest.
1611#[derive(Clone, Debug, Eq, PartialEq)]
1612pub struct McpSkillDirectoryEntry {
1613    relative_path: Arc<str>,
1614    uri: Arc<str>,
1615    directory: bool,
1616}
1617
1618impl McpSkillDirectoryEntry {
1619    /// Returns the path relative to the active Skill root.
1620    #[must_use]
1621    pub fn relative_path(&self) -> &str {
1622        &self.relative_path
1623    }
1624
1625    /// Returns the exact or derived URI at the originating server.
1626    #[must_use]
1627    pub fn uri(&self) -> &str {
1628        &self.uri
1629    }
1630
1631    /// Returns whether this direct child represents a directory.
1632    #[must_use]
1633    pub const fn is_directory(&self) -> bool {
1634        self.directory
1635    }
1636}
1637
1638/// Acting-window handle retaining exact durable authority and verified content.
1639pub struct McpActivatedSkill {
1640    host: McpSkillHost,
1641    identity: McpSkillIdentity,
1642    entry: McpSkillEntry,
1643    instructions: McpVerifiedSkillFile,
1644    activation_id: u64,
1645    window: SkillActingWindow,
1646}
1647
1648impl McpActivatedSkill {
1649    /// Returns the origin-scoped Skill identity.
1650    #[must_use]
1651    pub const fn identity(&self) -> &McpSkillIdentity {
1652        &self.identity
1653    }
1654
1655    /// Returns the exact held entry for the full acting window.
1656    #[must_use]
1657    pub const fn entry(&self) -> &McpSkillEntry {
1658        &self.entry
1659    }
1660
1661    /// Returns the verified, origin-tagged `SKILL.md` content.
1662    #[must_use]
1663    pub const fn instructions(&self) -> &McpVerifiedSkillFile {
1664        &self.instructions
1665    }
1666
1667    /// Returns the exact durable approval and authority window.
1668    #[must_use]
1669    pub const fn acting_window(&self) -> &SkillActingWindow {
1670        &self.window
1671    }
1672
1673    /// Lazily reads one manifest-listed file from the same originating server.
1674    pub async fn read_file(
1675        &self,
1676        relative_path: &str,
1677    ) -> Result<McpVerifiedSkillFile, McpSkillHostError> {
1678        self.assert_active().await?;
1679        validate_relative_path(relative_path)
1680            .map_err(|_| McpSkillHostError::InvalidRelativePath)?;
1681        let resource = self
1682            .entry
1683            .resource_by_path(relative_path)
1684            .ok_or(McpSkillHostError::ResourceOutsideHeldManifest)?;
1685        let file = self
1686            .host
1687            .verified_file(&self.identity, &self.entry, resource)
1688            .await?;
1689        self.assert_active().await?;
1690        Ok(file)
1691    }
1692
1693    /// Lists direct children from the held Manifest without a live directory read.
1694    pub fn list_directory(
1695        &self,
1696        relative_directory: &str,
1697    ) -> Result<Vec<McpSkillDirectoryEntry>, McpSkillHostError> {
1698        if !relative_directory.is_empty() {
1699            validate_relative_path(relative_directory)
1700                .map_err(|_| McpSkillHostError::InvalidRelativePath)?;
1701        }
1702        let prefix = if relative_directory.is_empty() {
1703            String::new()
1704        } else {
1705            format!("{relative_directory}/")
1706        };
1707        let root = self
1708            .entry
1709            .uri()
1710            .strip_suffix(SKILL_DOCUMENT)
1711            .expect("validated Skill URI ends in SKILL.md");
1712        let mut children = BTreeMap::<String, bool>::new();
1713        for resource in self.entry.resources() {
1714            let Some(remainder) = resource.relative_path().strip_prefix(&prefix) else {
1715                continue;
1716            };
1717            if remainder.is_empty() {
1718                continue;
1719            }
1720            let (name, directory) = remainder
1721                .split_once('/')
1722                .map_or((remainder, false), |(name, _)| (name, true));
1723            let child = format!("{prefix}{name}");
1724            children
1725                .entry(child)
1726                .and_modify(|current| *current |= directory)
1727                .or_insert(directory);
1728        }
1729        Ok(children
1730            .into_iter()
1731            .map(|(relative_path, directory)| McpSkillDirectoryEntry {
1732                uri: Arc::from(format!("{root}{relative_path}")),
1733                relative_path: Arc::from(relative_path),
1734                directory,
1735            })
1736            .collect())
1737    }
1738
1739    /// Activates one nested `SKILL.md` only after a separate fresh approval.
1740    pub async fn activate_nested(
1741        &self,
1742        relative_skill_document: &str,
1743        attempt: McpSkillActivationAttempt,
1744    ) -> Result<McpActivatedSkill, McpSkillHostError> {
1745        self.assert_active().await?;
1746        validate_relative_path(relative_skill_document)
1747            .map_err(|_| McpSkillHostError::InvalidRelativePath)?;
1748        if relative_skill_document == SKILL_DOCUMENT
1749            || !relative_skill_document.ends_with("/SKILL.md")
1750        {
1751            return Err(McpSkillHostError::InvalidNestedSkill);
1752        }
1753        let resource = self
1754            .entry
1755            .resource_by_path(relative_skill_document)
1756            .ok_or(McpSkillHostError::ResourceOutsideHeldManifest)?;
1757        let nested = self.host.get_skill(resource.uri()).await?;
1758        self.host
1759            .activate_entry(
1760                nested,
1761                McpSkillActivationSource::Nested {
1762                    identity: self.identity.clone(),
1763                    parent_window_id: self.window.window_id(),
1764                },
1765                attempt,
1766            )
1767            .await
1768    }
1769
1770    /// Permanently revokes this authority window with immutable evidence.
1771    pub async fn revoke(
1772        &self,
1773        reason: SkillActingWindowRevocationReason,
1774    ) -> Result<SkillActingWindowRevocation, McpSkillHostError> {
1775        self.host
1776            .inner
1777            .activation_store
1778            .revoke(self.window.clone(), reason)
1779            .await
1780            .map_err(map_activation_store_error)
1781    }
1782
1783    async fn assert_active(&self) -> Result<(), McpSkillHostError> {
1784        self.host
1785            .inner
1786            .activation_store
1787            .assert_active(self.window.clone())
1788            .await
1789            .map_err(map_activation_store_error)
1790    }
1791
1792    /// Obtains an explicit permit for one exact Tool call during this window.
1793    pub async fn authorize_tool_call<'activation>(
1794        &'activation self,
1795        tool_name: &str,
1796        host_code_execution: bool,
1797    ) -> Result<McpSkillExecutionPermit<'activation>, McpSkillHostError> {
1798        self.assert_active().await?;
1799        if tool_name.is_empty()
1800            || tool_name.len() > MAX_TOOL_NAME_BYTES
1801            || tool_name.trim() != tool_name
1802            || tool_name.chars().any(char::is_control)
1803        {
1804            return Err(McpSkillHostError::InvalidToolName);
1805        }
1806        let requested_allowed_tools = self
1807            .entry
1808            .frontmatter()
1809            .get("allowed-tools")
1810            .and_then(Value::as_str)
1811            .map(Arc::from);
1812        let grant = self
1813            .host
1814            .inner
1815            .policy
1816            .authorize_tool_call(McpSkillToolAuthorizationRequest {
1817                identity: self.identity.clone(),
1818                manifest_digest: self.entry.manifest_digest.clone(),
1819                activation_id: self.activation_id,
1820                acting_window_id: self.window.window_id(),
1821                tool_name: Arc::from(tool_name),
1822                tool_identity: None,
1823                tool_descriptor_digest: None,
1824                operation: McpSkillToolOperation::Execute,
1825                invocation: None,
1826                host_code_execution,
1827                requested_allowed_tools,
1828            })
1829            .await
1830            .map_err(map_tool_policy_error)?;
1831        self.assert_active().await?;
1832        Ok(McpSkillExecutionPermit {
1833            identity: self.identity.clone(),
1834            manifest_digest: self.entry.manifest_digest.clone(),
1835            activation_id: self.activation_id,
1836            acting_window: self.window.clone(),
1837            tool_name: Arc::from(tool_name),
1838            tool_identity: None,
1839            tool_descriptor_digest: None,
1840            operation: McpSkillToolOperation::Execute,
1841            invocation: None,
1842            host_code_execution,
1843            grant,
1844            activation: PhantomData,
1845        })
1846    }
1847
1848    pub(crate) async fn authorize_bound_tool_operation<'activation>(
1849        &'activation self,
1850        binding: &McpSkillToolBinding,
1851        operation: McpSkillToolOperation,
1852        invocation: &McpSkillToolInvocation,
1853    ) -> Result<McpSkillExecutionPermit<'activation>, McpSkillHostError> {
1854        self.assert_active().await?;
1855        let requested_allowed_tools = self
1856            .entry
1857            .frontmatter()
1858            .get("allowed-tools")
1859            .and_then(Value::as_str)
1860            .map(Arc::from);
1861        let tool_name = Arc::from(binding.tool_name());
1862        let grant = self
1863            .host
1864            .inner
1865            .policy
1866            .authorize_tool_call(McpSkillToolAuthorizationRequest {
1867                identity: self.identity.clone(),
1868                manifest_digest: self.entry.manifest_digest.clone(),
1869                activation_id: self.activation_id,
1870                acting_window_id: self.window.window_id(),
1871                tool_name: Arc::clone(&tool_name),
1872                tool_identity: Some(binding.identity().clone()),
1873                tool_descriptor_digest: Some(binding.descriptor_digest()),
1874                operation,
1875                invocation: Some(invocation.clone()),
1876                host_code_execution: binding.host_code_execution(),
1877                requested_allowed_tools,
1878            })
1879            .await
1880            .map_err(map_tool_policy_error)?;
1881        Ok(McpSkillExecutionPermit {
1882            identity: self.identity.clone(),
1883            manifest_digest: self.entry.manifest_digest.clone(),
1884            activation_id: self.activation_id,
1885            acting_window: self.window.clone(),
1886            tool_name,
1887            tool_identity: Some(binding.identity().clone()),
1888            tool_descriptor_digest: Some(binding.descriptor_digest()),
1889            operation,
1890            invocation: Some(invocation.clone()),
1891            host_code_execution: binding.host_code_execution(),
1892            grant,
1893            activation: PhantomData,
1894        })
1895    }
1896}
1897
1898impl fmt::Debug for McpActivatedSkill {
1899    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1900        formatter
1901            .debug_struct("McpActivatedSkill")
1902            .field("identity", &self.identity)
1903            .field("manifest_digest", &self.entry.manifest_digest)
1904            .field("activation_id", &self.activation_id)
1905            .field("acting_window", &self.window)
1906            .finish_non_exhaustive()
1907    }
1908}
1909
1910/// Non-constructible proof of explicit policy approval for one exact Tool operation.
1911#[derive(Debug)]
1912#[must_use = "the permit must be consumed by the exact approved Tool execution"]
1913pub struct McpSkillExecutionPermit<'activation> {
1914    identity: McpSkillIdentity,
1915    manifest_digest: Arc<str>,
1916    activation_id: u64,
1917    acting_window: SkillActingWindow,
1918    tool_name: Arc<str>,
1919    tool_identity: Option<CapabilityIdentity>,
1920    tool_descriptor_digest: Option<Digest>,
1921    operation: McpSkillToolOperation,
1922    invocation: Option<McpSkillToolInvocation>,
1923    host_code_execution: bool,
1924    grant: McpSkillToolAuthorizationGrant,
1925    activation: PhantomData<&'activation McpActivatedSkill>,
1926}
1927
1928impl McpSkillExecutionPermit<'_> {
1929    /// Returns the approved Skill identity.
1930    #[must_use]
1931    pub const fn identity(&self) -> &McpSkillIdentity {
1932        &self.identity
1933    }
1934
1935    /// Returns the content binding approved for this call.
1936    #[must_use]
1937    pub fn manifest_digest(&self) -> &str {
1938        &self.manifest_digest
1939    }
1940
1941    /// Returns the process-local activation identifier.
1942    #[must_use]
1943    pub const fn activation_id(&self) -> u64 {
1944        self.activation_id
1945    }
1946
1947    /// Returns the durable window which must remain active at receipt commit.
1948    #[must_use]
1949    pub const fn acting_window(&self) -> &SkillActingWindow {
1950        &self.acting_window
1951    }
1952
1953    /// Returns the exact approved Tool name.
1954    #[must_use]
1955    pub fn tool_name(&self) -> &str {
1956        &self.tool_name
1957    }
1958
1959    /// Returns the exact runtime Tool identity when this permit is registry-bound.
1960    #[must_use]
1961    pub const fn tool_identity(&self) -> Option<&CapabilityIdentity> {
1962        self.tool_identity.as_ref()
1963    }
1964
1965    /// Returns the exact runtime descriptor digest when registry-bound.
1966    #[must_use]
1967    pub const fn tool_descriptor_digest(&self) -> Option<Digest> {
1968        self.tool_descriptor_digest
1969    }
1970
1971    /// Returns the approved execution or reconciliation operation.
1972    #[must_use]
1973    pub const fn operation(&self) -> McpSkillToolOperation {
1974        self.operation
1975    }
1976
1977    /// Returns exact bounded invocation facts when this permit is registry-bound.
1978    #[must_use]
1979    pub const fn invocation(&self) -> Option<&McpSkillToolInvocation> {
1980        self.invocation.as_ref()
1981    }
1982
1983    /// Returns whether Host code execution was disclosed and approved.
1984    #[must_use]
1985    pub const fn host_code_execution(&self) -> bool {
1986        self.host_code_execution
1987    }
1988
1989    /// Returns the exact policy evidence authorizing this operation.
1990    #[must_use]
1991    pub const fn grant(&self) -> &McpSkillToolAuthorizationGrant {
1992        &self.grant
1993    }
1994}
1995
1996/// Closed Host lifecycle failure.
1997#[derive(Debug, Error)]
1998#[non_exhaustive]
1999pub enum McpSkillHostError {
2000    /// The strict Skills client boundary rejected the exchange.
2001    #[error(transparent)]
2002    Client(#[from] McpSkillClientError),
2003    /// The connected client transport cannot carry the SEP-2640 support floor.
2004    #[error("MCP client transport limits are too small for static Skills")]
2005    TransportProfileTooSmall,
2006    /// An entry originated from another client binding.
2007    #[error("MCP Skill entry belongs to another client binding")]
2008    ForeignClientBinding,
2009    /// Fresh activation approval was denied.
2010    #[error("MCP Skill activation was denied")]
2011    ActivationDenied,
2012    /// Tool execution approval was denied.
2013    #[error("MCP Skill Tool call was denied")]
2014    ToolCallDenied,
2015    /// The policy authority was unavailable.
2016    #[error("MCP Skill Host policy is unavailable")]
2017    PolicyUnavailable,
2018    /// Fetched bytes did not match the retained Manifest.
2019    #[error("MCP Skill resource verification failed")]
2020    ResourceVerificationFailed,
2021    /// The fetched `SKILL.md` was not UTF-8.
2022    #[error("MCP Skill SKILL.md is not UTF-8")]
2023    SkillDocumentNotUtf8,
2024    /// Parsed `SKILL.md` frontmatter differed from the approved entry.
2025    #[error("MCP Skill frontmatter verification failed")]
2026    FrontmatterVerificationFailed,
2027    /// A file read was outside the held complete Manifest.
2028    #[error("MCP Skill resource is outside the held Manifest")]
2029    ResourceOutsideHeldManifest,
2030    /// A relative path was not canonical and safe.
2031    #[error("invalid MCP Skill relative path")]
2032    InvalidRelativePath,
2033    /// A nested activation did not identify a descendant `SKILL.md`.
2034    #[error("invalid nested MCP Skill activation")]
2035    InvalidNestedSkill,
2036    /// A proposed Tool name was empty, oversized, or ambiguous.
2037    #[error("invalid MCP Skill Tool name")]
2038    InvalidToolName,
2039    /// Private cache synchronization was unavailable.
2040    #[error("MCP Skill private cache is unavailable")]
2041    CacheUnavailable,
2042    /// A unique process-local activation ID could not be allocated.
2043    #[error("MCP Skill activation identifier space is exhausted")]
2044    ActivationIdExhausted,
2045    /// Activation evidence could not be constructed from validated inputs.
2046    #[error("MCP Skill activation evidence is invalid")]
2047    ActivationEvidenceInvalid,
2048    /// Durable activation storage was temporarily unavailable.
2049    #[error("MCP Skill activation store is unavailable")]
2050    ActivationStoreUnavailable,
2051    /// The durable acting window did not exist.
2052    #[error("MCP Skill acting window was not found")]
2053    ActingWindowNotFound,
2054    /// The durable acting window expired or was revoked.
2055    #[error("MCP Skill acting window is inactive")]
2056    ActingWindowInactive,
2057    /// Durable activation evidence conflicted with the requested activation.
2058    #[error("MCP Skill activation store rejected the evidence")]
2059    ActivationStoreRejected,
2060}
2061
2062fn verify_resource(
2063    expected: &McpSkillResource,
2064    actual: &McpSkillResourceContent,
2065) -> Result<(), McpSkillHostError> {
2066    if actual.uri() != expected.uri()
2067        || actual.bytes().len() != expected.size()
2068        || Digest::sha256(actual.bytes()).to_string() != expected.digest()
2069    {
2070        return Err(McpSkillHostError::ResourceVerificationFailed);
2071    }
2072    Ok(())
2073}
2074
2075fn map_activation_policy_error(error: McpSkillHostPolicyError) -> McpSkillHostError {
2076    match error {
2077        McpSkillHostPolicyError::Denied => McpSkillHostError::ActivationDenied,
2078        McpSkillHostPolicyError::Unavailable => McpSkillHostError::PolicyUnavailable,
2079    }
2080}
2081
2082fn map_tool_policy_error(error: McpSkillHostPolicyError) -> McpSkillHostError {
2083    match error {
2084        McpSkillHostPolicyError::Denied => McpSkillHostError::ToolCallDenied,
2085        McpSkillHostPolicyError::Unavailable => McpSkillHostError::PolicyUnavailable,
2086    }
2087}
2088
2089fn map_activation_store_error(
2090    error: stateknot_core::SkillActivationStoreError,
2091) -> McpSkillHostError {
2092    let failure = error.failure();
2093    drop(error);
2094    match failure {
2095        SkillActivationStoreFailure::Unavailable => McpSkillHostError::ActivationStoreUnavailable,
2096        SkillActivationStoreFailure::NotFound => McpSkillHostError::ActingWindowNotFound,
2097        SkillActivationStoreFailure::Inactive => McpSkillHostError::ActingWindowInactive,
2098        _ => McpSkillHostError::ActivationStoreRejected,
2099    }
2100}
2101
2102fn allocate_monotonic_id(counter: &AtomicU64) -> Option<u64> {
2103    counter
2104        .fetch_update(Ordering::AcqRel, Ordering::Acquire, |current| {
2105            (current != u64::MAX).then_some(current + 1)
2106        })
2107        .ok()
2108}
2109
2110#[cfg(test)]
2111mod tests {
2112    use super::*;
2113    use serde_json::json;
2114
2115    #[test]
2116    fn static_entry_rejects_dynamic_and_manifest_escape() {
2117        let dynamic = json!({
2118            "uri": "skill://review/SKILL.md",
2119            "frontmatter": {"name": "review", "description": "Review code."},
2120            "resources": "dynamic"
2121        });
2122        assert!(matches!(
2123            parse_skill_entry(&dynamic, 1),
2124            Err(McpSkillClientError::DynamicSkillUnsupported)
2125        ));
2126
2127        let escaped = json!({
2128            "uri": "skill://review/SKILL.md",
2129            "frontmatter": {"name": "review", "description": "Review code."},
2130            "resources": [{
2131                "uri": "skill://other/secret.txt",
2132                "digest": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
2133                "size": 1
2134            }]
2135        });
2136        assert!(matches!(
2137            parse_skill_entry(&escaped, 1),
2138            Err(McpSkillClientError::InvalidEntry)
2139        ));
2140    }
2141
2142    #[test]
2143    fn origin_and_digest_are_stable_and_collision_safe() {
2144        assert!(McpSkillOrigin::new(" docs ").is_err());
2145        let first = McpSkillIdentity {
2146            origin: McpSkillOrigin::new("docs-a").unwrap(),
2147            uri: Arc::from("skill://review/SKILL.md"),
2148        };
2149        let second = McpSkillIdentity {
2150            origin: McpSkillOrigin::new("docs-b").unwrap(),
2151            uri: Arc::from("skill://review/SKILL.md"),
2152        };
2153        assert_ne!(first, second);
2154    }
2155
2156    #[test]
2157    fn static_entry_requires_a_complete_bounded_canonical_manifest() {
2158        let digest = "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
2159        let missing_document = json!({
2160            "uri": "skill://review/SKILL.md",
2161            "frontmatter": {"name": "review", "description": "Review code."},
2162            "resources": [{
2163                "uri": "skill://review/reference.md",
2164                "digest": digest,
2165                "size": 1
2166            }]
2167        });
2168        assert!(matches!(
2169            parse_skill_entry(&missing_document, 1),
2170            Err(McpSkillClientError::InvalidEntry)
2171        ));
2172
2173        let upper_case_digest = json!({
2174            "uri": "skill://review/SKILL.md",
2175            "frontmatter": {"name": "review", "description": "Review code."},
2176            "resources": [{
2177                "uri": "skill://review/SKILL.md",
2178                "digest": "sha256:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
2179                "size": 1
2180            }]
2181        });
2182        assert!(matches!(
2183            parse_skill_entry(&upper_case_digest, 1),
2184            Err(McpSkillClientError::InvalidEntry)
2185        ));
2186
2187        let oversized_frontmatter = json!({
2188            "uri": "skill://review/SKILL.md",
2189            "frontmatter": {
2190                "name": "review",
2191                "description": "Review code.",
2192                "untrusted-extension": "x".repeat(MCP_SKILL_MAXIMUM_FRONTMATTER_BYTES)
2193            },
2194            "resources": [{
2195                "uri": "skill://review/SKILL.md",
2196                "digest": digest,
2197                "size": 1
2198            }]
2199        });
2200        assert!(matches!(
2201            parse_skill_entry(&oversized_frontmatter, 1),
2202            Err(McpSkillClientError::InvalidEntry)
2203        ));
2204    }
2205
2206    #[test]
2207    fn catalog_page_enforces_the_callers_entry_ceiling() {
2208        let entry = json!({
2209            "uri": "skill://review/SKILL.md",
2210            "frontmatter": {"name": "review", "description": "Review code."},
2211            "resources": [{
2212                "uri": "skill://review/SKILL.md",
2213                "digest": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
2214                "size": 1
2215            }]
2216        });
2217        let page = json!({
2218            "resultType": "complete",
2219            "skills": [entry.clone(), entry],
2220            "ttlMs": 0,
2221            "cacheScope": "private"
2222        });
2223        assert!(matches!(
2224            parse_skill_page(&page, 1, 1),
2225            Err(McpSkillClientError::InvalidCatalog)
2226        ));
2227    }
2228}