multicast 2.0.0

A declarative CLI framework for Rust with typed commands, agent discovery, HTTP, and MCP
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
//! Remote Agent Skills published through the `io.modelcontextprotocol/skills`
//! extension.
//!
//! [`McpHttpClient::list_skills`] reads the complete manifest once.
//! [`McpHttpClient::read_skill_file`] (text) and
//! [`McpHttpClient::read_skill_file_bytes`] (text or binary) read one listed
//! file on demand and
//! accepts it only when its size, SHA-256 digest, and (for `SKILL.md`)
//! frontmatter match the manifest. Nothing is prefetched, and a file the
//! manifest does not list is never requested.

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,
};

/// Most skills one remote manifest may list.
pub const MAX_REMOTE_SKILLS: usize = 1024;

/// One skill from a remote manifest.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RemoteSkill {
    /// The skill's name, from its frontmatter and its directory URI.
    pub name: String,
    /// The `skill://<name>/SKILL.md` URI.
    pub uri: String,
    /// The frontmatter the server declared for `SKILL.md`.
    pub frontmatter: Map<String, Value>,
    /// Every file in the skill, including `SKILL.md`.
    pub files: Vec<RemoteSkillFile>,
}

/// One file listed for a remote skill.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RemoteSkillFile {
    /// The file's `skill://` URI.
    pub uri: String,
    /// The declared digest, `sha256:<64 lowercase hex digits>`.
    pub digest: String,
    /// The declared size in bytes.
    pub size: u64,
}

impl McpHttpClient {
    /// Whether the server advertised the skills extension in
    /// `server/discover`. Legacy sessions never do.
    pub fn skills_enabled(&self) -> bool {
        self.skills
    }

    /// Lists every skill the server publishes, following every page.
    ///
    /// A skill whose files are `dynamic` is left out: its contents cannot be
    /// checked against a manifest. A malformed entry, a duplicate name, a
    /// non-advancing cursor, or a listing past [`MAX_REMOTE_SKILLS`],
    /// [`MAX_SKILL_FILES`], [`MAX_SKILL_BYTES`], or
    /// [`MAX_REMOTE_TOOL_PAGES`] pages fails the whole listing.
    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 {
                // Follow-up page.
                Some(cursor) => serde_json::json!({ "cursor": cursor }),
                // First page.
                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) {
                // The server repeated a cursor; paging would never end.
                Some(next) if cursor.as_deref() == Some(next) => {
                    return Err(protocol("skills/list returned a non-advancing cursor"));
                }
                // The server keeps paging past the cap.
                Some(_) if pages >= MAX_REMOTE_TOOL_PAGES => {
                    return Err(protocol(format!(
                        "skills/list returned more than {MAX_REMOTE_TOOL_PAGES} pages"
                    )));
                }
                // Another page.
                Some(next) => cursor = Some(next.to_string()),
                // Last page.
                None => return Ok(skills),
            }
        }
    }

    /// Reads one text file of `skill` and returns its text.
    ///
    /// Applies every check of [`Self::read_skill_file_bytes`]. A file served
    /// as binary, or whose bytes are not UTF-8, fails with a protocol error.
    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"
            ))
        })
    }

    /// Reads one file of `skill`, text or binary, and returns its bytes.
    ///
    /// `uri` must be one of the skill's listed files; any other URI fails
    /// before a request is sent. The response must carry exactly one of
    /// `text` and base64 `blob`, and the decoded bytes must match exactly
    /// the declared size and digest. A `SKILL.md` must be text carrying
    /// exactly the declared frontmatter. Any difference fails with
    /// [`McpClientError::SkillIntegrity`].
    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")) {
            // Text content.
            (Some(Value::String(text)), None) => (text.as_bytes().to_vec(), true),
            // Binary content; a blob that is not strict base64 cannot match.
            (None, Some(Value::String(blob))) => (
                decode_base64(blob)
                    .ok_or_else(|| integrity("the blob is not valid base64".to_string()))?,
                false,
            ),
            // Neither, both, or a non-string value.
            _ => {
                return Err(protocol(format!(
                    "resources/read returned neither text nor blob for {uri}"
                )));
            }
        };
        verify(skill, file, &bytes, is_text)?;
        Ok(bytes)
    }

    /// Reads one file of `skill` through `cache`.
    ///
    /// A cached copy is used only when its bytes still match the file's
    /// declared size and digest and, for `SKILL.md`, the manifest's
    /// frontmatter; then no request is sent. Otherwise the file is read with
    /// [`Self::read_skill_file_bytes`], and only bytes that passed every check
    /// are stored. A cache that fails to store does not fail the read.
    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)
    }
}

/// Checks bytes against a manifest file: exact size, SHA-256 digest, and for
/// `SKILL.md`, text whose frontmatter equals the manifest's. `is_text` is
/// false for content that arrived as a blob.
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(())
}

/// A user's approval of one remote skill, bound to its exact manifest entry.
///
/// Approval covers the skill's name, its `SKILL.md` URI, the declared
/// frontmatter, and every file's URI, size, and digest. Any change to the
/// published skill, such as an edited, added, or removed file, makes
/// [`Self::covers`] false, so the changed skill needs a new approval. The
/// value serializes so a host can keep approvals with its own state; bind
/// stored approvals to the server they came from.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ApprovedSkill {
    /// The approved skill's name.
    pub name: String,
    /// The approved `SKILL.md` URI.
    pub uri: String,
    /// The approved frontmatter.
    pub frontmatter: Map<String, Value>,
    /// Every approved file as `(uri, size, digest)`, sorted by URI.
    pub files: Vec<(String, u64, String)>,
}

impl ApprovedSkill {
    /// Whether this approval covers `skill` exactly as it is listed now.
    pub fn covers(&self, skill: &RemoteSkill) -> bool {
        *self == skill.approve()
    }
}

impl RemoteSkill {
    /// Records approval of this skill as it is listed now.
    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,
        }
    }
}

/// Content-addressed storage for verified remote skill files.
///
/// Keys are manifest digests (`sha256:<hex>`). Because a key names its
/// content, an entry never goes stale; the client still checks every cached
/// copy against the manifest before using it. Keep a cache in the host's own
/// state, never in a directory agents scan for skills: only an approved skill
/// should reach an agent.
pub trait McpSkillCache: Send + Sync {
    /// The bytes stored under `digest`, if any.
    fn get(&self, digest: &str) -> Option<Vec<u8>>;
    /// Stores `bytes` under `digest`.
    fn put(&self, digest: &str, bytes: &[u8]) -> Result<(), String>;
}

/// A [`McpSkillCache`] in a directory: one file per digest, written to a
/// temporary file and renamed into place, so a reader never sees a partial
/// file. Stored bytes whose hash no longer matches their name are ignored.
#[cfg(not(target_arch = "wasm32"))]
#[derive(Debug, Clone)]
pub struct McpSkillDirectoryCache {
    directory: std::path::PathBuf,
}

#[cfg(not(target_arch = "wasm32"))]
impl McpSkillDirectoryCache {
    /// Uses `directory`, creating it when missing.
    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())
}

/// Validates one manifest entry. `None` is a dynamic skill, which is left out.
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") {
        // A fixed file list.
        Some(Value::Array(resources)) => resources,
        // Contents that change cannot be checked against a manifest.
        Some(Value::String(kind)) if kind == "dynamic" => return Ok(None),
        // Anything else is malformed.
        _ => 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,
    })
}

/// One non-empty path segment that cannot step out of its directory.
fn valid_segment(segment: &str) -> bool {
    !segment.is_empty() && segment != "." && segment != ".." && !segment.contains(['/', '\\'])
}