diff --git a/crates/agent/ARCHITECTURE.md b/crates/agent/ARCHITECTURE.md index 2f6dccfb..6e8762b5 100644 --- a/crates/agent/ARCHITECTURE.md +++ b/crates/agent/ARCHITECTURE.md @@ -6070,12 +6070,27 @@ context. Only host-authored records count: a skill-tool result (matched to its ` leaves the notice pending. - **One loading tool per server, `mcp____skill__read({uri})`.** A `SKILL.md` URI loads (activates) the skill — `skills/get` first for a URI never listed; a file URI reads a file of a skill - this session loaded; a directory URI is listed from the held manifest. Per-server is what binds every + this session loaded; a directory URI is the server's live listing when it declared `directoryRead` + (below), else the held manifest's. Per-server is what binds every read to the skill's origin (a skill from A can never cause a read against B), and the `mcp____` prefix is what `set_mcp_enabled` gates. A file of a skill the session has not loaded is refused without a request. A `SKILL.md` URI inside a loaded skill is a load request first (an unlisted nested skill activates by URI); only if `skills/get` answers `-32602` is it read as the enclosing skill's ordinary file. +- **Directories (`directoryRead`).** A server that declares the extension's one setting, + `directoryRead: true`, promises `resources/directory/read` for every directory in the skill + namespaces it serves as individual files; the spec forbids calling the method otherwise, so a server + without the setting is never asked and its directories stay answered from the held manifest. With + it, a directory URI of a loaded skill is the server's live view — the freshest view of the + skill's directories, and the one a skill whose manifest names no files would need — paged (at + most 32 pages / 2000 children) + and sorted, with subdirectories recognized by `mimeType: "inode/directory"` and the two + disagreements the spec distinguishes: a child the held manifest does not list is named as the skill + having changed and is **not** readable under the snapshot held (the loader refuses it without a + request), and a manifest file the server no longer lists is named as gone. The live view never + extends the manifest — that is the spec's MUST — so it is a report, not a second registry. A + `-32602` ("not a directory I serve") falls back to the manifest path, which names the failure + precisely; any other failure keeps the manifest answer with the error annotated. - **Every read is verified** against the entry the skill was loaded under: byte length, then SHA-256 of the raw bytes, and for `SKILL.md` a field-by-field comparison of its YAML frontmatter with the entry's — equality of YAML values, not of one JSON rendering (`1` = `1.0`, a YAML 1.1 boolean word = the boolean, null spellings = null), so an honest skill rendered by a YAML 1.1 parser is not refused. This deliberately loosens the spec's "identical in content" from bytes-of-a-rendering to values, and the host reads the fields it acts on (`disable-model-invocation`) with the same normalization, so what verifies as `true` is treated as `true`. @@ -6794,10 +6809,10 @@ backend an operator points it at. | `src/bin/mcp_fixture_stdio_server.rs` | Test fixture only, not a real MCP server: a ~150-line hand-rolled MCP server speaking newline-delimited JSON-RPC over stdio, with zero new dependencies (`tokio`/`serde_json`, already ordinary deps of this crate) rather than pulling in `rmcp`'s own server-side machinery just for a test double. Auto-discovered by Cargo as a sibling `[[bin]]` of this same package (any `.rs` file under `src/bin/` becomes its own binary target), so `tests/mcp_client.rs` locates it via `env!("CARGO_BIN_EXE_mcp_fixture_stdio_server")` exactly like every other e2e test locates the real `agent` binary. Tools include `echo`/`add`/`ping`/`fail`/`echo_env`/`image`/`slow_progress`/`ask_user`/`ask_user_mrtr`/`slow_task`, each proving one distinct thing the real client code must handle (see the file's own module doc comment). | | `src/bin/mcp_apps_fixture_server.rs` | Test fixture only: a hand-rolled MCP Apps (SEP-1865) server over stdio (`tokio`/`serde_json`, no `rmcp` server side) for `tests/mcp_apps*.rs`. Lists `app_only_always` (`visibility: ["app"]`) unconditionally, as the official SDK does, and the rest of its UI metadata (`_meta.ui.resourceUri`, `visibility`, an app-only `refresh_weather`, an oversized `huge_view`, a non-`ui://` `bad_uri_view`) only when the client advertised `io.modelcontextprotocol/ui` — read per request under `2026-07-28` or from `initialize` (`MCP_APPS_FIXTURE_LEGACY=1` forces the latter) — and serves a `ui://` view that speaks the iframe bridge in plain JavaScript, so it also renders in a real browser. `MCP_APPS_FIXTURE_LOG` records every request (with its `uri`) and whether its client advertised the extension; `change_view` bumps the view's version and sends `notifications/resources/list_changed`; `MCP_APPS_FIXTURE_UI_META` puts the view's `_meta.ui` on the content item, the listing, both or neither; `MCP_APPS_FIXTURE_FAIL_FIRST_UI`, `_UI_DELAY_MS` and `_VIEW_DELAY_MS` make the first apps dial fail, the apps dial slow, and the view read slow. | | `src/bin/mcp_fixture_events_server.rs` | Hand-rolled MCP Events **server** fixture (stdio or streamable HTTP) with a control API for tests: emits events, signs webhook deliveries (Standard Webhooks, dual-signing after a rotation, tamper modes), runs the verification challenge, grants TTLs, terminates subscriptions, and records what it observed | -| `src/tools/mcp_skills.rs` | SEP-2640 Skills extension, client side: entry validation (incl. the 512-file / 16 MiB per-skill limits), `ServerSkills` (per connection: listing with `ttlMs`/list-changed refresh, learned entries), `SkillSession` (per session, on `McpEnabledSet`: loaded skills, content-bound approvals, the activation and code-execution approval gate, `--approve-mcp-skills`), the per-server loading tool `mcp____skill__read` rebound to each session, `RunHooks`, and `McpSkills` — the session's gated view: ``, `get_commands` entries, diagnostics, `/skill::` expansion. See "MCP skills (SEP-2640)" | +| `src/tools/mcp_skills.rs` | SEP-2640 Skills extension, client side: entry validation (incl. the 512-file / 16 MiB per-skill limits), `ServerSkills` (per connection: listing with `ttlMs`/list-changed refresh, learned entries, and the `directoryRead` live directory listing of a loaded skill's directories), `SkillSession` (per session, on `McpEnabledSet`: loaded skills, content-bound approvals, the activation and code-execution approval gate, `--approve-mcp-skills`), the per-server loading tool `mcp____skill__read` rebound to each session, `RunHooks`, and `McpSkills` — the session's gated view: ``, `get_commands` entries, diagnostics, `/skill::` expansion. See "MCP skills (SEP-2640)" | | `src/tools/mcp_view_http.rs` | The streamable-HTTP client an apps connection dials through: `ViewCappedHttp` sends a `ui://` `resources/read` through `mcp_wire::HttpClient::post_bounded` (rmcp's auth and session status handling, SSE handed to rmcp as a stream) and refuses its response over `MAX_VIEW_BYTES` by `Content-Length` before the body, or as soon as the streamed body or one SSE event passes it; everything else goes to `mcp_wire::HttpClient` | | `src/tools/mcp_wire.rs` | Works around rust-sdk#1197 over streamable HTTP, and caps every streamable-HTTP message: `HttpClient` (a `StreamableHttpClient` that answers **every** POST itself through `post_bounded` (rmcp's own `reqwest` `post_message` is never called: the request headers it sends — bearer, `Mcp-Session-Id`, `Accept`, protocol version, custom headers — and the response shapes it acts on — `401`/`403` `WWW-Authenticate`, a `404` on a session, `202`, JSON with its session id, SSE — are pinned against rmcp's client by the differential tests `an_ordinary_request_is_sent_as_rmcps_own_client_would` / `…_answered_as_rmcps_own_client_would`) — applying `mcp_stdio::rescue` to the JSON body or to each SSE event, and holding each to the one per-message cap, `mcp_stdio::max_message_bytes`: a request's over-cap answer becomes that request's JSON-RPC error; MCP App view reads, for `mcp_view_http`, get the tighter view cap; the GET stream is capped through `rmcp`'s SSE-event limit). A unit test pins the upstream bug | -| `src/bin/mcp_skills_fixture_server.rs` | Hand-rolled SEP-2640 server for `tests/mcp_skills*.rs` (stdio, or `--http`): an ordinary skill with a supporting file and a nested skill, a same-name pair, a `disable-model-invocation` skill, a tampered one, a dynamic one, an unlisted one, two over the per-skill limits, and a late one published by its `publish_late` tool (with `notifications/resources/list_changed`); caching hints from env; `_meta` on every result like a `2026-07-28` server; logs every request so tests assert what was (not) fetched | +| `src/bin/mcp_skills_fixture_server.rs` | Hand-rolled SEP-2640 server for `tests/mcp_skills*.rs` (stdio, or `--http`): an ordinary skill with a supporting file and a nested skill, a same-name pair, a `disable-model-invocation` skill, a tampered one, a dynamic one, an unlisted one, two over the per-skill limits, and a late one published by its `publish_late` tool (with `notifications/resources/list_changed`); `resources/directory/read` when `directoryRead` is declared (with paging, and drift mode's added/withdrawn child); caching hints from env; `_meta` on every result like a `2026-07-28` server; logs every request so tests assert what was (not) fetched | | `src/serve_ws.rs`, `src/serve_ws/browser_guard.rs`, `src/serve_ws/tls.rs` | `serve --listen`/`--listen-uds`: the `serve` control protocol over a WebSocket or a one-shot HTTP POST at `/_beyond/agent?session_id=`, a thin transport over `serve::serve_session`. The supervisor owns the `session id → running session` map, so a connection is a view and a dropped socket does not stop a run; it also holds the idle reaper, the service-mode grant check, `/livez`/`/readyz`, draining and the MCP Events webhook route. `tls` loads the `--tls-listen` certificate and runs each handshake under a deadline; `browser_guard` refuses browser-originated requests on the TCP and TLS listeners outside service mode (a foreign `Origin`, a non-loopback `Host`, a POST that is not `application/json`) | | `src/serve_ws/job_ended.rs` | The `job_ended` receiver: `classify` tells a callback apart by its `Authorization` header alone, before `Content-Length` is read; `serve` checks it in the spec's order (path, query, body, service mode, token, scope), looks only for a session already held here (`503` otherwise), and answers through the request's own path. Fixed refusal bodies. See "Job-end notify". | | `src/metrics.rs` | Prometheus metrics for `serve --service` (`--metrics-listen`): a registry of its own, closed-set labels only (no tenant, session or shard id), served on a loopback-only listener. See "Metrics" | diff --git a/crates/agent/src/bin/mcp_skills_fixture_server.rs b/crates/agent/src/bin/mcp_skills_fixture_server.rs index dc2c5bb9..d7bc834a 100644 --- a/crates/agent/src/bin/mcp_skills_fixture_server.rs +++ b/crates/agent/src/bin/mcp_skills_fixture_server.rs @@ -27,6 +27,12 @@ //! - `MCP_SKILLS_FIXTURE_LOG=`: append ` ` per request, so a test can prove what //! was (and was not) fetched, and when the server was started at all. //! - `MCP_SKILLS_FIXTURE_NO_EXTENSION=1`: don't declare the extension (`skills/*` → -32601). +//! - `MCP_SKILLS_FIXTURE_NO_DIRECTORY_READ=1`: declare the extension with empty settings, i.e. +//! without the `directoryRead` promise — so `resources/directory/read` is not offered (-32601) and +//! a host must not call it. +//! - `MCP_SKILLS_FIXTURE_DIR_DRIFT=1`: `resources/directory/read` of `skill://git-workflow/references` +//! drops `GUIDE.md` (every manifest still lists it) and gains `LIVE-ONLY.md` (no manifest does). +//! - `MCP_SKILLS_FIXTURE_DIR_PAGE_SIZE=`: page `resources/directory/read` at `n` children. //! - `MCP_SKILLS_FIXTURE_VERSION=2`: serve a changed `git-workflow` `SKILL.md` (with an honest new //! manifest), to prove a stale cached manifest is refreshed rather than trusted. //! - `MCP_SKILLS_FIXTURE_LATE_FLAG=`: while that file exists, `skill://late/SKILL.md` is @@ -415,6 +421,15 @@ fn extension_declared() -> bool { std::env::var("MCP_SKILLS_FIXTURE_NO_EXTENSION").as_deref() != Ok("1") } +/// Whether the extension is declared with `directoryRead: true` (the spec's one setting), promising +/// `resources/directory/read` for every directory in the skill namespaces. Setting +/// `MCP_SKILLS_FIXTURE_NO_DIRECTORY_READ=1` declares the extension without it, so a test can prove +/// the host then never calls the method. +fn directory_read_declared() -> bool { + extension_declared() + && std::env::var("MCP_SKILLS_FIXTURE_NO_DIRECTORY_READ").as_deref() != Ok("1") +} + /// Whether a `subscriptions/listen` stream asked for `resourcesListChanged`, and whether the client /// fell back to the legacy `initialize` handshake (where `list_changed` is unrequested). static LISTEN_RESOURCES: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); @@ -423,7 +438,11 @@ static LEGACY_SESSION: std::sync::atomic::AtomicBool = std::sync::atomic::Atomic fn capabilities() -> Value { let mut caps = json!({ "tools": {}, "resources": { "listChanged": true } }); if extension_declared() { - caps["extensions"] = json!({ (SKILLS_EXTENSION_ID): {} }); + let settings = match directory_read_declared() { + true => json!({ "directoryRead": true }), + false => json!({}), + }; + caps["extensions"] = json!({ (SKILLS_EXTENSION_ID): settings }); } caps } @@ -446,6 +465,72 @@ fn invalid_params(message: String) -> Result { Err((-32602, message)) } +/// Whether `MCP_SKILLS_FIXTURE_DIR_DRIFT=1`: the live directory listing of +/// `skill://git-workflow/references` drops `GUIDE.md` (which every manifest still promises) and gains +/// `LIVE-ONLY.md` (which no manifest lists) — the two directions the spec's stale-snapshot rules +/// distinguish. +fn dir_drift() -> bool { + std::env::var("MCP_SKILLS_FIXTURE_DIR_DRIFT").as_deref() == Ok("1") +} + +/// The direct children of `uri`, as `resources/directory/read` reports them; `None` when `uri` is not +/// a directory this server serves (a file, or nothing at all — both `-32602`). +fn dir_children(uri: &str) -> Option> { + let prefix = format!("{}/", uri.trim_end_matches('/')); + let all = skills(); + let mut children: Vec<(String, bool)> = Vec::new(); + let mut any = false; + for file in all.iter().flat_map(|s| s.files.iter()) { + let Some(rest) = file.uri.strip_prefix(&prefix) else { + continue; + }; + if rest.is_empty() { + continue; + } + any = true; + let child = match rest.split_once('/') { + Some((sub, _)) => (format!("{prefix}{sub}"), true), + None => (file.uri.to_string(), false), + }; + if !children.contains(&child) { + children.push(child); + } + } + // `docs://unlisted/notes.md` is a resource too, under a directory of its own. + if let Some(rest) = "docs://unlisted/notes.md".strip_prefix(&prefix) + && !rest.is_empty() + && !rest.contains('/') + { + any = true; + children.push(("docs://unlisted/notes.md".to_string(), false)); + } + if dir_drift() && uri.trim_end_matches('/') == "skill://git-workflow/references" { + children.retain(|(uri, _)| uri != "skill://git-workflow/references/GUIDE.md"); + children.push(( + "skill://git-workflow/references/LIVE-ONLY.md".to_string(), + false, + )); + any = true; + } + if !any { + return None; + } + children.sort(); + Some( + children + .into_iter() + .map(|(uri, directory)| { + let name = uri.rsplit('/').next().unwrap_or(&uri).to_string(); + let mime = match directory { + true => "inode/directory", + false => "text/markdown", + }; + json!({ "uri": uri, "name": name, "mimeType": mime }) + }) + .collect(), + ) +} + fn handle(method: &str, params: &Value) -> Result { let all = skills(); match method { @@ -527,6 +612,11 @@ fn handle(method: &str, params: &Value) -> Result { if uri == "skill://git-workflow/unlisted.md" { return Ok(json!({ "contents": [{ "uri": uri, "text": "UNLISTED-BODY" }] })); } + // Served by drift mode's live directory listing, and deliberately absent from every + // manifest: a host acting on git-workflow must refuse it without ever reading it. + if uri == "skill://git-workflow/references/LIVE-ONLY.md" { + return Ok(json!({ "contents": [{ "uri": uri, "text": "LIVE-ONLY-BODY" }] })); + } for skill in &all { for file in &skill.files { if file.uri == uri { @@ -542,6 +632,42 @@ fn handle(method: &str, params: &Value) -> Result { } invalid_params(format!("unknown resource {uri}")) } + "resources/directory/read" if directory_read_declared() => { + let uri = params + .get("uri") + .and_then(Value::as_str) + .unwrap_or_default(); + let Some(children) = dir_children(uri) else { + return invalid_params(format!("not a directory: {uri}")); + }; + let (ttl, scope) = cache_hints(); + // `MCP_SKILLS_FIXTURE_DIR_PAGE_SIZE=`: one page per n children, cursor-paged. + let size = std::env::var("MCP_SKILLS_FIXTURE_DIR_PAGE_SIZE") + .ok() + .and_then(|v| v.parse::().ok()) + .filter(|n| *n > 0); + let start = match (size, params.get("cursor").and_then(Value::as_str)) { + (Some(_), Some(cursor)) => cursor.parse::().unwrap_or(0), + _ => 0, + }; + let end = match size { + Some(size) => (start + size).min(children.len()), + None => children.len(), + }; + let page = children + .get(start.min(children.len())..end) + .unwrap_or_default(); + let mut result = json!({ + "resultType": "complete", + "ttlMs": ttl, + "cacheScope": scope, + "resources": page, + }); + if end < children.len() { + result["nextCursor"] = json!(end.to_string()); + } + Ok(result) + } "skills/list" if extension_declared() => { let (ttl, scope) = cache_hints(); // `MCP_SKILLS_FIXTURE_FAIL_LIST_FILE`: while that file exists, the listing fails. diff --git a/crates/agent/src/tools/mcp_skills.rs b/crates/agent/src/tools/mcp_skills.rs index 14ce3664..52af7b31 100644 --- a/crates/agent/src/tools/mcp_skills.rs +++ b/crates/agent/src/tools/mcp_skills.rs @@ -15,9 +15,10 @@ //! here. The body is fetched when the skill is loaded and not before. //! - **One loading tool per server**, `mcp____skill__read` (`McpSkillTool`). It is the //! host's skill-loading path: a `SKILL.md` URI loads (activates) the skill, a file URI reads a file -//! of an already-loaded skill, a directory URI lists one from the held manifest. Being per server is -//! what binds every read to the skill's own origin (a skill served by A can never cause a -//! `resources/read` against B), and it rides the existing machinery for free: the +//! of an already-loaded skill, a directory URI lists one — from the server's own live listing +//! (`resources/directory/read`) when it declared `directoryRead`, else from the held manifest. +//! Being per server is what binds every read to the skill's own origin (a skill served by A can +//! never cause a `resources/read` against B), and it rides the existing machinery for free: the //! `mcp____` prefix is what `set_mcp_enabled` gates on, and the tool owns the server's //! reapable [`McpConnection`](super::mcp) like every other tool of that server. //! - **Every read is verified** against the entry it was loaded under: byte length and SHA-256 of @@ -72,6 +73,11 @@ pub const SKILLS_EXTENSION_ID: &str = "io.modelcontextprotocol/skills"; /// Upper bound on `skills/list` pages: a server whose cursor never ends must not wedge a connect. const MAX_LIST_PAGES: usize = 64; +/// Upper bound on `resources/directory/read` pages of one listing, and on the children kept from it — +/// a cursor loop or a directory that never ends must not wedge a tool call. +const MAX_DIR_PAGES: usize = 32; +const MAX_DIR_CHILDREN: usize = 2000; + /// How long a `/skill:name` expansion may wait on the server before the message goes through with an /// error note instead. Expansion sits on the command path, where an unresponsive server would /// otherwise stall the session. @@ -318,6 +324,29 @@ pub(crate) fn declared(client: &McpClient) -> bool { .is_some_and(|ext| ext.contains_key(SKILLS_EXTENSION_ID)) } +/// Whether the server declared the extension's one setting, `directoryRead` — its promise to answer +/// [`DIRECTORY_READ_METHOD`] for every directory in the skill namespaces it serves. The spec allows a +/// client to call that method only against a server that has declared it. +fn directory_read(client: &McpClient) -> bool { + client + .peer_info() + .and_then(|info| info.capabilities.extensions.clone()) + .and_then(|ext| ext.get(SKILLS_EXTENSION_ID).cloned()) + .and_then(|settings| settings.get("directoryRead").and_then(Value::as_bool)) + .unwrap_or(false) +} + +/// `resources/directory/read`: one directory's direct children, as the server currently sees them. +const DIRECTORY_READ_METHOD: &str = "resources/directory/read"; + +/// One child of a directory, as [`DIRECTORY_READ_METHOD`] returns it. +#[derive(Debug, Clone, PartialEq, Eq)] +struct DirChild { + uri: String, + /// `mimeType: "inode/directory"` — descend by listing this one in turn. + directory: bool, +} + /// One server's skills listing, as last fetched. #[derive(Debug, Clone, Default)] pub(crate) struct Listing { @@ -961,6 +990,142 @@ impl ServerSkills { )) } + /// What the server currently says one directory of a skill holds — [`DIRECTORY_READ_METHOD`], + /// paged. Only ever called for a server that declared `directoryRead`, which the spec requires + /// before the method may be used at all. + /// + /// The error carries whether the server answered `-32602` (Invalid params): its "that URI is not a + /// directory I serve", which is not a failure but an answer this host acts on. + async fn live_dir( + &self, + client: &McpClient, + dir: &str, + ) -> Result, (String, bool)> { + let mut children: Vec = Vec::new(); + let mut seen: HashSet = HashSet::new(); + let mut cursor: Option = None; + for _ in 0..MAX_DIR_PAGES { + let mut params = json!({ "uri": dir }); + if let Some(cursor) = &cursor { + params["cursor"] = json!(cursor); + } + let page = custom_request_typed(client, DIRECTORY_READ_METHOD, params).await?; + let list = page + .get("resources") + .and_then(Value::as_array) + .ok_or_else(|| (format!("`{dir}`: result has no `resources` array"), false))?; + for child in list { + let Some(uri) = child.get("uri").and_then(Value::as_str) else { + continue; + }; + if !seen.insert(uri.to_string()) { + continue; + } + children.push(DirChild { + uri: uri.to_string(), + directory: child.get("mimeType").and_then(Value::as_str) + == Some("inode/directory"), + }); + if children.len() >= MAX_DIR_CHILDREN { + break; + } + } + if children.len() >= MAX_DIR_CHILDREN { + break; + } + cursor = page + .get("nextCursor") + .and_then(Value::as_str) + .map(str::to_string); + if cursor.is_none() { + break; + } + } + children.sort_by(|a, b| a.uri.cmp(&b.uri)); + Ok(children) + } + + /// The server's live view of one directory of a loaded skill, with the manifest still governing + /// what may be read: a child the held entry does not list is named as changed and unreadable, + /// never offered as a file of the skill ([`McpSkillTool::read_file`] would refuse it anyway). + fn render_live_dir(&self, entry: &SkillEntry, dir: &str, children: &[DirChild]) -> String { + let prefix = format!("{dir}/"); + let held: HashSet<&str> = entry.files.iter().map(|f| f.uri.as_str()).collect(); + let (mut listed, mut unlisted): (Vec, Vec) = (Vec::new(), Vec::new()); + let mut live_files: HashSet<&str> = HashSet::new(); + let mut live_dirs: Vec<&str> = Vec::new(); + for child in children { + let rel = child.uri.strip_prefix(&prefix).unwrap_or(&child.uri); + let name = match child.directory { + true => format!("{rel}/"), + false => rel.to_string(), + }; + // A subdirectory is part of the snapshot when the manifest holds a file under it. + let inside = format!("{}/", child.uri); + let known = match child.directory { + true => held + .iter() + .any(|f| f.starts_with(inside.as_str()) || *f == child.uri), + false => held.contains(child.uri.as_str()), + }; + match (known, child.directory) { + (true, true) => { + live_dirs.push(child.uri.as_str()); + listed.push(name) + } + (true, false) => { + live_files.insert(child.uri.as_str()); + listed.push(name) + } + (false, _) => unlisted.push(name), + } + } + // Manifest files of this directory the server no longer reports, as paths relative to it — + // the same names the listing above uses. + let mut gone: Vec<&str> = held + .iter() + .filter(|f| f.starts_with(prefix.as_str())) + .filter(|f| !live_files.contains(**f)) + .filter(|f| !live_dirs.iter().any(|d| f.starts_with(&format!("{d}/")))) + .map(|f| f.trim_start_matches(prefix.as_str())) + .collect(); + gone.sort_unstable(); + + let mut blocks: Vec = Vec::new(); + if !listed.is_empty() { + blocks.push(listed.join("\n")); + } + if !unlisted.is_empty() { + blocks.push(format!( + "Listed by the server but not in your loaded snapshot (the skill has changed; \ + load `{}` again to refresh and re-approve it — these are not readable under the \ + snapshot you hold):\n{}", + entry.uri, + unlisted.join("\n") + )); + } + if !gone.is_empty() { + blocks.push(format!( + "In your snapshot but no longer served (a read would fail; load `{}` again to \ + refresh):\n{}", + entry.uri, + gone.join("\n") + )); + } + format!( + "Directory {dir} of skill `{}` (MCP server `{}`) — the server's live listing, which may \ + be ahead of or behind your loaded snapshot:\n{}\n", + entry.name(), + self.server, + match (blocks.is_empty(), listed.is_empty()) { + (true, _) => "(empty)".to_string(), + // A plain name list follows the header directly; a section needs its own paragraph. + (false, false) => blocks.join("\n\n"), + (false, true) => format!("\n{}", blocks.join("\n\n")), + } + ) + } + /// One call of the loading tool, on behalf of `session`. See [`McpSkillTool`]'s description. async fn handle( &self, @@ -996,6 +1161,33 @@ impl ServerSkills { if listed { return self.read_file(&entry, uri).await; } + // A directory of a loaded skill. A server that declared `directoryRead` is asked what it + // currently holds, which is the freshest view of the skill's directories. The manifest + // still governs what may be read — see [`Self::render_live_dir`]. A server that did not + // declare it must not be asked at all. + let live = match self.client().await { + Ok(client) if directory_read(&client) => Some(self.live_dir(&client, uri).await), + _ => None, + }; + match live { + Some(Ok(children)) => { + return Ok(text_output(self.render_live_dir(&entry, uri, &children))); + } + // `-32602` is the server saying this URI is not a directory it serves: the manifest + // path below names that failure precisely, so it is not a "live listing failed". + Some(Err((_, true))) | None => {} + Some(Err((e, false))) => { + return Ok(text_output(match self.list_dir(&entry, uri) { + Some(listing) => format!( + "{listing}\n\n(the server's live listing of `{uri}` failed: {e})" + ), + None => format!( + "`{uri}` could not be listed from skill `{}`: {e}", + entry.uri + ), + })); + } + } if let Some(listing) = self.list_dir(&entry, uri) { return Ok(text_output(listing)); } diff --git a/crates/agent/tests/it.rs b/crates/agent/tests/it.rs index c3e902f7..9a06f4df 100644 --- a/crates/agent/tests/it.rs +++ b/crates/agent/tests/it.rs @@ -104,6 +104,7 @@ mod mcp_sandbox_connector; mod mcp_sandbox_stdio; mod mcp_skills; mod mcp_skills_approval; +mod mcp_skills_directory; mod mcp_skills_integrity; mod mcp_skills_listing; mod mcp_skills_resume; diff --git a/crates/agent/tests/mcp_skills_directory.rs b/crates/agent/tests/mcp_skills_directory.rs new file mode 100644 index 00000000..4447940a --- /dev/null +++ b/crates/agent/tests/mcp_skills_directory.rs @@ -0,0 +1,140 @@ +//! SEP-2640 `directoryRead`, end to end against the fixture: a server that declares the setting +//! answers `resources/directory/read`, and the host must use that live view — while the held manifest +//! still governs what may be read. A server that does not declare it must never see the method. +//! +//! Asserted against the wire, not the client's opinion of itself: the fixture logs every request it +//! receives, so "the live listing was read" and "the unlisted child was never fetched" are facts about +//! what reached the server. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use crate::common; + +use common::skills_env::{Env, last_message_text, read_skill}; +use common::turn_text; +use serde_json::json; + +const GIT: &str = "skill://git-workflow/SKILL.md"; +const REFS: &str = "skill://git-workflow/references"; + +#[test] +fn a_declaring_server_answers_the_directory_from_its_live_view() { + let env = Env::new(json!({})); + let bodies = env.run( + "list the skill's files", + vec![ + read_skill("t1", GIT), + read_skill("t2", REFS), + read_skill("t3", "skill://git-workflow"), + turn_text("done"), + ], + ); + + let refs = last_message_text(&bodies[2]); + assert!(refs.contains("the server's live listing"), "{refs}"); + assert!(refs.contains("GUIDE.md"), "{refs}"); + + let root = last_message_text(&bodies[3]); + assert!(root.contains("references/"), "{root}"); + assert!(root.contains("nested-helper/"), "{root}"); + assert!(root.contains("SKILL.md"), "{root}"); + // A nested skill's directory is part of the enclosing manifest (completeness extends to nested + // skills), so it is an ordinary child here, never a disagreement. + assert!(root.contains("hidden-nested/"), "{root}"); + assert!(!root.contains("not in your loaded snapshot"), "{root}"); + + assert_eq!( + env.log_of("resources/directory/read"), + vec![ + format!("resources/directory/read {REFS}"), + "resources/directory/read skill://git-workflow".to_string(), + ], + "one live listing per directory asked for, and nothing else" + ); +} + +#[test] +fn a_server_without_the_setting_is_answered_from_the_manifest_and_never_asked() { + let env = Env::new(json!({ "MCP_SKILLS_FIXTURE_NO_DIRECTORY_READ": "1" })); + let bodies = env.run( + "list the skill's files", + vec![ + read_skill("t1", GIT), + read_skill("t2", REFS), + turn_text("done"), + ], + ); + + let refs = last_message_text(&bodies[2]); + assert!(refs.contains("GUIDE.md"), "{refs}"); + assert!(!refs.contains("live listing"), "{refs}"); + assert!( + env.log_of("resources/directory/read").is_empty(), + "the spec forbids the method without the declaration: {:?}", + env.log() + ); +} + +#[test] +fn a_live_child_no_manifest_lists_is_named_changed_and_never_read() { + let env = Env::new(json!({ "MCP_SKILLS_FIXTURE_DIR_DRIFT": "1" })); + let bodies = env.run( + "list the skill's files", + vec![ + read_skill("t1", GIT), + read_skill("t2", REFS), + read_skill("t3", "skill://git-workflow/references/LIVE-ONLY.md"), + turn_text("done"), + ], + ); + + let refs = last_message_text(&bodies[2]); + assert!(refs.contains("not in your loaded snapshot"), "{refs}"); + assert!(refs.contains("LIVE-ONLY.md"), "{refs}"); + assert!(refs.contains("no longer served"), "{refs}"); + assert!(refs.contains("GUIDE.md"), "{refs}"); + + // The live view may not extend the manifest: a child only the server lists is still unreadable + // under the held entry, and the host must not fetch it to find out. + let refused = last_message_text(&bodies[3]); + assert!( + refused.contains("is not listed in the manifest"), + "{refused}" + ); + assert!(!refused.contains("LIVE-ONLY-BODY"), "{refused}"); + assert!( + env.log_of("resources/read skill://git-workflow/references/LIVE-ONLY.md") + .is_empty(), + "an unlisted child must not be read: {:?}", + env.log() + ); +} + +#[test] +fn every_page_of_a_paged_live_listing_reaches_the_model() { + let env = Env::new(json!({ "MCP_SKILLS_FIXTURE_DIR_PAGE_SIZE": "1" })); + let bodies = env.run( + "list the skill's files", + vec![ + read_skill("t1", GIT), + read_skill("t2", "skill://git-workflow"), + turn_text("done"), + ], + ); + + let root = last_message_text(&bodies[2]); + for child in [ + "SKILL.md", + "references/", + "nested-helper/", + "hidden-nested/", + ] { + assert!(root.contains(child), "missing {child:?} in:\n{root}"); + } + assert_eq!( + env.log_of("resources/directory/read").len(), + 4, + "four children, one page each (a client that ignored `nextCursor` would stop at one): {:?}", + env.log() + ); +}