use std::collections::HashSet;
use serde_json::{Map, Value};
use sha2::{Digest, Sha256};
use super::{McpClientError, McpHttpClient, with_deadline};
use crate::mcp::{
MAX_REMOTE_TOOL_PAGES, MAX_SKILL_BYTES, MAX_SKILL_FILES, SKILLS_EXTENSION, decode_base64,
parse_frontmatter, sha256_hex,
};
pub const MAX_REMOTE_SKILLS: usize = 1024;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RemoteSkill {
pub name: String,
pub uri: String,
pub frontmatter: Map<String, Value>,
pub files: Vec<RemoteSkillFile>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RemoteSkillFile {
pub uri: String,
pub digest: String,
pub size: u64,
}
impl McpHttpClient {
pub fn skills_enabled(&self) -> bool {
self.skills
}
pub async fn list_skills(&self) -> Result<Vec<RemoteSkill>, McpClientError> {
if !self.skills {
return Err(McpClientError::Protocol(format!(
"the server does not advertise {SKILLS_EXTENSION}"
)));
}
let (http, limits) = self.http_limits();
with_deadline(http, limits.timeout, self.list_skills_unbounded()).await
}
async fn list_skills_unbounded(&self) -> Result<Vec<RemoteSkill>, McpClientError> {
let mut skills = Vec::new();
let mut names = HashSet::new();
let mut cursor: Option<String> = None;
let mut pages = 0_usize;
loop {
pages += 1;
let params = match &cursor {
Some(cursor) => serde_json::json!({ "cursor": cursor }),
None => Value::Object(Map::new()),
};
let result = self.request("skills/list", params).await?;
let page = result
.get("skills")
.and_then(Value::as_array)
.ok_or_else(|| protocol("skills/list result has no skills array"))?;
for entry in page {
let Some(skill) = parse_entry(entry)? else {
continue;
};
if !names.insert(skill.name.clone()) {
return Err(protocol(format!(
"skills/list repeated the skill {}",
skill.name
)));
}
if skills.len() >= MAX_REMOTE_SKILLS {
return Err(protocol(format!(
"skills/list returned more than {MAX_REMOTE_SKILLS} skills"
)));
}
skills.push(skill);
}
match result.get("nextCursor").and_then(Value::as_str) {
Some(next) if cursor.as_deref() == Some(next) => {
return Err(protocol("skills/list returned a non-advancing cursor"));
}
Some(_) if pages >= MAX_REMOTE_TOOL_PAGES => {
return Err(protocol(format!(
"skills/list returned more than {MAX_REMOTE_TOOL_PAGES} pages"
)));
}
Some(next) => cursor = Some(next.to_string()),
None => return Ok(skills),
}
}
}
pub async fn read_skill_file(
&self,
skill: &RemoteSkill,
uri: &str,
) -> Result<String, McpClientError> {
let bytes = self.read_skill_file_bytes(skill, uri).await?;
String::from_utf8(bytes).map_err(|_| {
protocol(format!(
"{uri} is not UTF-8 text; read it with read_skill_file_bytes"
))
})
}
pub async fn read_skill_file_bytes(
&self,
skill: &RemoteSkill,
uri: &str,
) -> Result<Vec<u8>, McpClientError> {
let Some(file) = skill.files.iter().find(|file| file.uri == uri) else {
return Err(protocol(format!(
"{uri} is not a listed file of the skill {}",
skill.name
)));
};
let result = self
.request("resources/read", serde_json::json!({ "uri": uri }))
.await?;
let content = result
.get("contents")
.and_then(Value::as_array)
.and_then(|contents| {
contents
.iter()
.find(|content| content.get("uri").and_then(Value::as_str) == Some(uri))
})
.ok_or_else(|| protocol(format!("resources/read returned no content for {uri}")))?;
let integrity = |reason: String| McpClientError::SkillIntegrity {
uri: uri.to_string(),
reason,
};
let (bytes, is_text) = match (content.get("text"), content.get("blob")) {
(Some(Value::String(text)), None) => (text.as_bytes().to_vec(), true),
(None, Some(Value::String(blob))) => (
decode_base64(blob)
.ok_or_else(|| integrity("the blob is not valid base64".to_string()))?,
false,
),
_ => {
return Err(protocol(format!(
"resources/read returned neither text nor blob for {uri}"
)));
}
};
verify(skill, file, &bytes, is_text)?;
Ok(bytes)
}
pub async fn read_skill_file_cached(
&self,
skill: &RemoteSkill,
uri: &str,
cache: &dyn McpSkillCache,
) -> Result<Vec<u8>, McpClientError> {
let Some(file) = skill.files.iter().find(|file| file.uri == uri) else {
return Err(protocol(format!(
"{uri} is not a listed file of the skill {}",
skill.name
)));
};
if let Some(bytes) = cache.get(&file.digest)
&& verify(skill, file, &bytes, true).is_ok()
{
return Ok(bytes);
}
let bytes = self.read_skill_file_bytes(skill, uri).await?;
let _ = cache.put(&file.digest, &bytes);
Ok(bytes)
}
}
fn verify(
skill: &RemoteSkill,
file: &RemoteSkillFile,
bytes: &[u8],
is_text: bool,
) -> Result<(), McpClientError> {
let integrity = |reason: String| McpClientError::SkillIntegrity {
uri: file.uri.clone(),
reason,
};
if bytes.len() as u64 != file.size {
return Err(integrity(format!(
"declared {} bytes, received {}",
file.size,
bytes.len()
)));
}
let digest = format!("sha256:{}", sha256_hex(Sha256::digest(bytes)));
if digest != file.digest {
return Err(integrity(format!(
"declared digest {}, received {digest}",
file.digest
)));
}
if file.uri == skill.uri {
let text = std::str::from_utf8(bytes)
.ok()
.filter(|_| is_text)
.ok_or_else(|| integrity("SKILL.md is not text".to_string()))?;
let frontmatter = parse_frontmatter(text).map_err(integrity)?;
if frontmatter != skill.frontmatter {
return Err(integrity(
"the frontmatter differs from the manifest".to_string(),
));
}
}
Ok(())
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ApprovedSkill {
pub name: String,
pub uri: String,
pub frontmatter: Map<String, Value>,
pub files: Vec<(String, u64, String)>,
}
impl ApprovedSkill {
pub fn covers(&self, skill: &RemoteSkill) -> bool {
*self == skill.approve()
}
}
impl RemoteSkill {
pub fn approve(&self) -> ApprovedSkill {
let mut files: Vec<_> = self
.files
.iter()
.map(|file| (file.uri.clone(), file.size, file.digest.clone()))
.collect();
files.sort();
ApprovedSkill {
name: self.name.clone(),
uri: self.uri.clone(),
frontmatter: self.frontmatter.clone(),
files,
}
}
}
pub trait McpSkillCache: Send + Sync {
fn get(&self, digest: &str) -> Option<Vec<u8>>;
fn put(&self, digest: &str, bytes: &[u8]) -> Result<(), String>;
}
#[cfg(not(target_arch = "wasm32"))]
#[derive(Debug, Clone)]
pub struct McpSkillDirectoryCache {
directory: std::path::PathBuf,
}
#[cfg(not(target_arch = "wasm32"))]
impl McpSkillDirectoryCache {
pub fn open(directory: impl Into<std::path::PathBuf>) -> std::io::Result<Self> {
let directory = directory.into();
std::fs::create_dir_all(&directory)?;
Ok(Self { directory })
}
fn path(&self, digest: &str) -> Option<std::path::PathBuf> {
let hex = digest.strip_prefix("sha256:")?;
(hex.len() == 64
&& hex
.bytes()
.all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f')))
.then(|| self.directory.join(hex))
}
}
#[cfg(not(target_arch = "wasm32"))]
impl McpSkillCache for McpSkillDirectoryCache {
fn get(&self, digest: &str) -> Option<Vec<u8>> {
let bytes = std::fs::read(self.path(digest)?).ok()?;
(format!("sha256:{}", sha256_hex(Sha256::digest(&bytes))) == digest).then_some(bytes)
}
fn put(&self, digest: &str, bytes: &[u8]) -> Result<(), String> {
let target = self
.path(digest)
.ok_or_else(|| format!("{digest:?} is not a sha256 digest"))?;
if format!("sha256:{}", sha256_hex(Sha256::digest(bytes))) != digest {
return Err(format!("the bytes do not match {digest}"));
}
let temporary = target.with_extension("tmp");
std::fs::write(&temporary, bytes).map_err(|error| error.to_string())?;
std::fs::rename(&temporary, &target).map_err(|error| error.to_string())
}
}
fn protocol(message: impl Into<String>) -> McpClientError {
McpClientError::Protocol(message.into())
}
fn parse_entry(entry: &Value) -> Result<Option<RemoteSkill>, McpClientError> {
let uri = entry
.get("uri")
.and_then(Value::as_str)
.ok_or_else(|| protocol("a skills/list entry has no uri"))?;
let name = uri
.strip_prefix("skill://")
.and_then(|rest| rest.strip_suffix("/SKILL.md"))
.filter(|name| valid_segment(name))
.ok_or_else(|| protocol(format!("{uri} is not a skill://<name>/SKILL.md URI")))?;
let frontmatter = entry
.get("frontmatter")
.and_then(Value::as_object)
.ok_or_else(|| protocol(format!("{uri} has no frontmatter object")))?;
if frontmatter.get("name").and_then(Value::as_str) != Some(name) {
return Err(protocol(format!(
"{uri} declares a frontmatter name other than {name}"
)));
}
let resources = match entry.get("resources") {
Some(Value::Array(resources)) => resources,
Some(Value::String(kind)) if kind == "dynamic" => return Ok(None),
_ => return Err(protocol(format!("{uri} has no resources list"))),
};
if resources.len() > MAX_SKILL_FILES {
return Err(protocol(format!(
"{uri} lists more than {MAX_SKILL_FILES} files"
)));
}
let prefix = format!("skill://{name}/");
let mut files = Vec::with_capacity(resources.len());
let mut seen = HashSet::new();
let mut total = 0_u64;
for resource in resources {
let file = parse_file(resource, &prefix)?;
if !seen.insert(file.uri.clone()) {
return Err(protocol(format!("{uri} lists {} twice", file.uri)));
}
total = total.saturating_add(file.size);
if total > MAX_SKILL_BYTES as u64 {
return Err(protocol(format!(
"{uri} declares more than {MAX_SKILL_BYTES} bytes"
)));
}
files.push(file);
}
if !seen.contains(uri) {
return Err(protocol(format!("{uri} does not list its own SKILL.md")));
}
Ok(Some(RemoteSkill {
name: name.to_string(),
uri: uri.to_string(),
frontmatter: frontmatter.clone(),
files,
}))
}
fn parse_file(resource: &Value, prefix: &str) -> Result<RemoteSkillFile, McpClientError> {
let uri = resource
.get("uri")
.and_then(Value::as_str)
.ok_or_else(|| protocol("a skill file has no uri"))?;
let inside = uri
.strip_prefix(prefix)
.is_some_and(|path| path.split('/').all(valid_segment));
if !inside {
return Err(protocol(format!("{uri} is outside {prefix}")));
}
let digest = resource
.get("digest")
.and_then(Value::as_str)
.filter(|digest| {
digest.strip_prefix("sha256:").is_some_and(|hex| {
hex.len() == 64 && hex.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
})
})
.ok_or_else(|| protocol(format!("{uri} has no sha256 digest")))?;
let size = resource
.get("size")
.and_then(Value::as_u64)
.ok_or_else(|| protocol(format!("{uri} has no size")))?;
Ok(RemoteSkillFile {
uri: uri.to_string(),
digest: digest.to_string(),
size,
})
}
fn valid_segment(segment: &str) -> bool {
!segment.is_empty() && segment != "." && segment != ".." && !segment.contains(['/', '\\'])
}