anda_engine 0.19.0

Agents engine for Anda -- an AI agent framework built with Rust, powered by ICP and TEEs.
//! Explicit MCP Skills access (SEP-2640, `io.modelcontextprotocol/skills`).
//!
//! Skills remain untrusted remote content and are never installed or executed
//! implicitly. Hosts opt in per server via [`McpServerConfig::skills`], inspect
//! validated manifests via [`McpToolProvider::list_skills`] /
//! [`McpToolProvider::get_skill`], and read individual skill files through
//! [`McpToolProvider::read_skill_resource`], which enforces manifest membership
//! and SHA-256 digest verification for static skills and directory containment
//! for dynamic skills.

use super::{McpLimits, McpToolProvider, catalog::collect_pages, http_client};
use anda_core::{BoxError, ByteBufB64, CancellationToken};
use rmcp::model::{
    GetSkillRequestParams, GetSkillResult, ResourceContents, SKILL_MD, Skill, SkillResource,
    SkillResources, validate_skills,
};
use std::{str::FromStr, time::Duration};

impl McpToolProvider {
    /// Lists bounded, validated skills from a server declaring the SEP-2640
    /// skills extension. Requires the server's `skills` opt-in.
    ///
    /// Returns `Ok(None)` without sending a request when the server does not
    /// advertise `io.modelcontextprotocol/skills`.
    pub async fn list_skills(
        &self,
        server_id: &str,
        cancellation: CancellationToken,
    ) -> Result<Option<Vec<Skill>>, BoxError> {
        let config = self.server_config(server_id)?;
        if !config.skills {
            return Err("MCP skills are disabled for this server".into());
        }
        let result: Result<Option<Vec<Skill>>, BoxError> = tokio::select! {
            biased;
            _ = cancellation.cancelled() => Err("MCP skill listing cancelled".into()),
            _ = config.cancelled.cancelled() => Err("MCP server removed".into()),
            result = tokio::time::timeout(
                Duration::from_secs(config.timeouts.setup_secs + config.timeouts.list_secs),
                async {
                    let session = self.ensure_session(&config).await?;
                    let peer = session.service.lock().await.peer().clone();
                    if !peer
                        .peer_info()
                        .is_some_and(|info| info.capabilities.supports_skills())
                    {
                        return Ok(None);
                    }
                    let skills = collect_pages(&config.limits, |params| {
                        let peer = peer.clone();
                        async move {
                            let page =
                                http_client::retry_read(|| peer.list_skills(params.clone()))
                                    .await?;
                            Ok((page.skills, page.next_cursor))
                        }
                    })
                    .await?;
                    validate_skills(&skills)?;
                    for skill in &skills {
                        validate_skill_limits(skill, &config.limits)?;
                    }
                    Ok(Some(skills))
                },
            ) => result.map_err(|_| BoxError::from("MCP skill listing timed out"))?,
        };
        if let Err(err) = &result {
            config.record_auth_challenge(err.as_ref());
        }
        result
    }

    /// Fetches and validates one skill entry by its `SKILL.md` URI (`skills/get`,
    /// SEP-2640). Requires the server's `skills` opt-in.
    pub async fn get_skill(
        &self,
        server_id: &str,
        uri: String,
        cancellation: CancellationToken,
    ) -> Result<GetSkillResult, BoxError> {
        let config = self.server_config(server_id)?;
        if !config.skills {
            return Err("MCP skills are disabled for this server".into());
        }
        if uri.len() > config.limits.cursor_bytes {
            return Err("MCP skill URI limit exceeded".into());
        }
        let result: Result<GetSkillResult, BoxError> = tokio::select! {
            biased;
            _ = cancellation.cancelled() => Err("MCP skill fetch cancelled".into()),
            _ = config.cancelled.cancelled() => Err("MCP server removed".into()),
            result = tokio::time::timeout(
                Duration::from_secs(config.timeouts.setup_secs + config.timeouts.list_secs),
                async {
                    let session = self.ensure_session(&config).await?;
                    let peer = session.service.lock().await.peer().clone();
                    let result = http_client::retry_read(|| {
                        peer.get_skill(GetSkillRequestParams::new(uri.clone()))
                    })
                    .await?;
                    result.skill.validate()?;
                    if result.skill.uri != uri {
                        return Err(format!(
                            "MCP skill response URI mismatch: expected {uri}, got {}",
                            result.skill.uri
                        )
                        .into());
                    }
                    validate_skill_limits(&result.skill, &config.limits)?;
                    Ok(result)
                },
            ) => result.map_err(|_| BoxError::from("MCP skill fetch timed out"))?,
        };
        if let Err(err) = &result {
            config.record_auth_challenge(err.as_ref());
        }
        result
    }

    /// Reads one file belonging to `skill` over `resources/read` and verifies its
    /// manifest boundary and integrity.
    ///
    /// - For static skills (`SkillResources::Files`), `uri` must appear verbatim in
    ///   `skill.resources`, its declared size must fit `limits.message_bytes`, and
    ///   the returned bytes must match both size and `sha256:` digest via
    ///   [`SkillResource::verify`].
    /// - For dynamic skills (`SkillResources::Dynamic`), `uri` must resolve strictly
    ///   within the skill's directory root (rejecting traversal or sibling-prefix
    ///   URIs).
    pub async fn read_skill_resource(
        &self,
        server_id: &str,
        skill: &Skill,
        uri: String,
        cancellation: CancellationToken,
    ) -> Result<Vec<u8>, BoxError> {
        let config = self.server_config(server_id)?;
        if !config.skills {
            return Err("MCP skills are disabled for this server".into());
        }
        if uri.len() > config.limits.cursor_bytes {
            return Err("MCP skill resource URI limit exceeded".into());
        }
        skill.validate()?;
        validate_skill_limits(skill, &config.limits)?;

        let manifest_entry: Option<&SkillResource> = match &skill.resources {
            SkillResources::Files(files) => {
                let entry = files.iter().find(|file| file.uri == uri).ok_or_else(|| {
                    format!(
                        "MCP skill resource {uri} is not listed in skill {} manifest",
                        skill.uri
                    )
                })?;
                if entry.size > config.limits.message_bytes as u64 {
                    return Err(format!(
                        "MCP skill resource {uri} declared size {} exceeds message byte budget",
                        entry.size
                    )
                    .into());
                }
                Some(entry)
            }
            SkillResources::Dynamic => {
                if !is_within_skill_directory(skill, &uri) {
                    return Err(format!(
                        "MCP skill resource {uri} is outside skill {} directory",
                        skill.uri
                    )
                    .into());
                }
                None
            }
            _ => return Err("MCP skill uses an unsupported resource manifest format".into()),
        };

        let result = self
            .read_resource_inner(&config, uri.clone(), &cancellation)
            .await?;
        let bytes =
            decode_single_skill_resource(&uri, result.contents, config.limits.message_bytes)?;
        if let Some(entry) = manifest_entry {
            entry.verify(&bytes)?;
        }
        Ok(bytes)
    }
}

fn validate_skill_limits(skill: &Skill, limits: &McpLimits) -> Result<(), BoxError> {
    if skill.uri.len() > limits.cursor_bytes {
        return Err("MCP skill URI limit exceeded".into());
    }
    if skill.frontmatter.description.len() > limits.description_bytes {
        return Err("MCP skill description limit exceeded".into());
    }
    let frontmatter_bytes = serde_json::to_vec(&skill.frontmatter)?.len();
    if frontmatter_bytes > limits.server_metadata_bytes {
        return Err("MCP skill frontmatter metadata limit exceeded".into());
    }
    if let SkillResources::Files(files) = &skill.resources {
        if files.len() > limits.catalog_items {
            return Err("MCP skill manifest file limit exceeded".into());
        }
        for file in files {
            if file.uri.len() > limits.cursor_bytes {
                return Err("MCP skill resource URI limit exceeded".into());
            }
        }
    }
    Ok(())
}

fn decode_single_skill_resource(
    expected_uri: &str,
    contents: Vec<ResourceContents>,
    max_bytes: usize,
) -> Result<Vec<u8>, BoxError> {
    if contents.len() != 1 {
        return Err(format!(
            "MCP skill resource {expected_uri} returned {} content items, expected 1",
            contents.len()
        )
        .into());
    }
    let item = contents.into_iter().next().expect("checked length 1");
    let bytes = match item {
        ResourceContents::TextResourceContents { uri, text, .. } => {
            if uri != expected_uri {
                return Err(format!(
                    "MCP skill resource URI mismatch: expected {expected_uri}, got {uri}"
                )
                .into());
            }
            text.into_bytes()
        }
        ResourceContents::BlobResourceContents { uri, blob, .. } => {
            if uri != expected_uri {
                return Err(format!(
                    "MCP skill resource URI mismatch: expected {expected_uri}, got {uri}"
                )
                .into());
            }
            if blob.starts_with("b64:") {
                return Err("MCP skill resource has invalid base64 payload".into());
            }
            let max_encoded = max_bytes
                .saturating_mul(4)
                .saturating_div(3)
                .saturating_add(4);
            if blob.len() > max_encoded {
                return Err("MCP skill resource exceeds message byte budget".into());
            }
            ByteBufB64::from_str(&blob)
                .map_err(|err| format!("MCP skill resource has invalid base64 payload: {err}"))?
                .as_ref()
                .to_vec()
        }
        _ => return Err("MCP skill resource returned an unsupported content variant".into()),
    };
    if bytes.len() > max_bytes {
        return Err("MCP skill resource exceeds message byte budget".into());
    }
    Ok(bytes)
}

/// Verifies that `resource_uri` resolves to a file strictly inside `skill`'s
/// directory (mirroring SEP-2640 / rmcp manifest containment rules).
pub(super) fn is_within_skill_directory(skill: &Skill, resource_uri: &str) -> bool {
    // Reuse `Skill::validate`'s exact RFC 3986 percent-encoding + dot-segment
    // containment check by testing a synthetic manifest containing `SKILL.md`
    // and `resource_uri`.
    let Some(root) = skill.uri.strip_suffix(SKILL_MD) else {
        return false;
    };
    if !root.ends_with('/') {
        return false;
    }
    let dummy_digest = "sha256:0000000000000000000000000000000000000000000000000000000000000000";
    let resources = if resource_uri == skill.uri {
        vec![SkillResource::new(skill.uri.clone(), dummy_digest, 0)]
    } else {
        vec![
            SkillResource::new(skill.uri.clone(), dummy_digest, 0),
            SkillResource::new(resource_uri, dummy_digest, 0),
        ]
    };
    let probe = Skill::new(
        skill.uri.clone(),
        rmcp::model::SkillFrontmatter::new(skill.frontmatter.name.clone(), "probe"),
        SkillResources::Files(resources),
    );
    match probe.validate() {
        Ok(()) => true,
        // `DuplicateResource` means `resource_uri` normalized onto `skill.uri`
        // (same file inside the skill directory); only `ResourceOutsideSkill`
        // or URI errors indicate an escape.
        Err(rmcp::model::SkillValidationError::DuplicateResource(_)) => true,
        Err(_) => false,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn dynamic_skill_directory_containment_rejects_escapes() {
        let skill = Skill::new(
            "skill://acme/billing/SKILL.md",
            rmcp::model::SkillFrontmatter::new("billing", "Billing"),
            SkillResources::Dynamic,
        );
        assert!(is_within_skill_directory(&skill, &skill.uri));
        assert!(is_within_skill_directory(
            &skill,
            "skill://acme/billing/references/tax.md"
        ));
        assert!(is_within_skill_directory(
            &skill,
            "skill://acme/billing/a/../b.md"
        ));
        assert!(!is_within_skill_directory(
            &skill,
            "skill://acme/billing/../other/secret.md"
        ));
        assert!(!is_within_skill_directory(
            &skill,
            "skill://acme/billing-other/SKILL.md"
        ));
        assert!(!is_within_skill_directory(&skill, "skill://acme/billing/"));
        assert!(!is_within_skill_directory(
            &skill,
            "skill://acme/billing/%2e%2e/other/secret.md"
        ));
    }
}