From 8e43376f1e3da9d0aac2c4bc4e9e714853e23b6d Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Thu, 3 Dec 2026 20:50:11 +0800 Subject: [PATCH] =?UTF-8?q?feat(agents):=20=E8=B5=84=E6=BA=90=E5=BA=93=20M?= =?UTF-8?q?CP=20=E6=9C=8D=E5=8A=A1=E5=99=A8=E8=A1=A5=E9=BD=90=E5=AD=97?= =?UTF-8?q?=E6=AE=B5=E5=B9=B6=E5=AD=98=E5=8F=98=E9=87=8F=E5=80=BC=EF=BC=8C?= =?UTF-8?q?Agent=20=E4=B8=AD=E7=9A=84=E5=90=8C=E9=A1=B9=E7=94=B1=20Core=20?= =?UTF-8?q?=E5=88=86=E7=BB=84=EF=BC=8C=E7=B2=98=E8=B4=B4=20JSON=20?= =?UTF-8?q?=E7=94=B1=20Core=20=E8=A7=A3=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CONTRIBUTING.md | 4 +- rust/Cargo.lock | 1 + rust/contracts/rust-core-api.md | 7 +- rust/crates/agent-runtime/Cargo.toml | 3 +- rust/crates/agent-runtime/src/lib.rs | 1 + rust/crates/agent-runtime/src/library.rs | 527 ++++++---- .../crates/agent-runtime/src/library/found.rs | 319 ++++++ .../crates/agent-runtime/src/library/paste.rs | 477 +++++++++ .../agent-runtime/src/library/servers.rs | 905 +++++++++++++++++ rust/crates/agent-runtime/src/live.rs | 2 +- .../crates/agent-runtime/src/tests/library.rs | 31 +- .../src/tests/library/servers.rs | 909 ++++++++++++++++++ rust/crates/core/src/protocol/command.rs | 5 + .../core/src/tests/declarative_plugins.rs | 3 +- rust/crates/plugin-agents/src/lib.rs | 132 +++ rust/crates/plugin-agents/src/tests.rs | 93 +- shared/plugins/contract/v1/README.md | 301 +++++- .../v1/fixtures/agents/agents.plugin.json | 12 + .../fixtures/manifest/invalid-manifests.json | 5 + .../contract/v1/plugin-manifest.schema.json | 23 +- shared/plugins/reference/api-catalog.md | 4 +- .../reference/capabilities-and-versions.md | 4 +- shared/plugins/reference/domains/agents.md | 44 +- .../plugins/reference/protocol-changelog.md | 3 +- shared/plugins/sdk/go/README.md | 9 +- shared/plugins/sdk/java/README.md | 9 +- shared/plugins/sdk/node/README.md | 9 +- shared/plugins/sdk/rust/README.md | 9 +- 28 files changed, 3567 insertions(+), 284 deletions(-) create mode 100644 rust/crates/agent-runtime/src/library/found.rs create mode 100644 rust/crates/agent-runtime/src/library/paste.rs create mode 100644 rust/crates/agent-runtime/src/library/servers.rs create mode 100644 rust/crates/agent-runtime/src/tests/library/servers.rs diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 83a768df..c44a7d58 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -63,7 +63,7 @@ node --test scripts/rust-core/*.test.mjs # CI 脚本自己的 cargo test --manifest-path rust/Cargo.toml -p lithe-platform -p lithe-platform-tests # 在 macOS 或 Windows 上运行平台测试 ``` -手边没有 Windows 时,至少运行一次 `LIBSQLITE3_SYS_USE_PKG_CONFIG=1 cargo clippy --manifest-path rust/Cargo.toml --workspace --all-targets --target x86_64-pc-windows-msvc -- -D warnings`,确认 Windows 代码能编译。环境变量让 SQLite 改为链接系统库、不编译自带的 C 源码:编译它需要 MSVC 工具,macOS 和 Linux 上没有;clippy 只检查不链接,不受影响。 +手边没有 Windows 时,至少运行一次 `LIBSQLITE3_SYS_USE_PKG_CONFIG=1 ZSTD_SYS_USE_PKG_CONFIG=1 PKG_CONFIG_ALLOW_CROSS=1 cargo clippy --manifest-path rust/Cargo.toml --workspace --all-targets --target x86_64-pc-windows-msvc -- -D warnings`,确认 Windows 代码能编译。前两个环境变量让 SQLite 和 zstd(插件市场经 `zstd` crate 依赖它)改为链接系统库、不编译自带的 C 源码:编译它们需要 MSVC 工具和 Windows 头文件,macOS 和 Linux 上没有;第三个允许交叉目标使用 pkg-config。clippy 只检查不链接,不受影响。本机要装有 SQLite 和 zstd 的 pkg-config 文件(macOS 用 Homebrew 的 `sqlite`、`zstd`)。 --- @@ -132,4 +132,4 @@ node --test scripts/rust-core/*.test.mjs # the CI scripts' own cargo test --manifest-path rust/Cargo.toml -p lithe-platform -p lithe-platform-tests # platform tests on macOS or Windows ``` -Without a Windows host, at least run `LIBSQLITE3_SYS_USE_PKG_CONFIG=1 cargo clippy --manifest-path rust/Cargo.toml --workspace --all-targets --target x86_64-pc-windows-msvc -- -D warnings` to confirm the Windows code compiles. The variable makes SQLite link a system library instead of compiling its bundled C source, which needs the MSVC tools that macOS and Linux do not have; clippy only checks and never links, so this does not matter. +Without a Windows host, at least run `LIBSQLITE3_SYS_USE_PKG_CONFIG=1 ZSTD_SYS_USE_PKG_CONFIG=1 PKG_CONFIG_ALLOW_CROSS=1 cargo clippy --manifest-path rust/Cargo.toml --workspace --all-targets --target x86_64-pc-windows-msvc -- -D warnings` to confirm the Windows code compiles. The first two variables make SQLite and zstd (which the plugin marketplace reaches through the `zstd` crate) link a system library instead of compiling their bundled C sources, which need the MSVC tools and Windows headers that macOS and Linux do not have; the third lets pkg-config answer for a cross target. Clippy only checks and never links, so this does not matter. The machine needs pkg-config files for SQLite and zstd (Homebrew's `sqlite` and `zstd` on macOS). diff --git a/rust/Cargo.lock b/rust/Cargo.lock index cd2cf758..5944be46 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -939,6 +939,7 @@ checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" name = "lithe-agent-runtime" version = "0.1.0" dependencies = [ + "base64", "lithe-agent-sessions", "lithe-diagnostics", "lithe-lsp-engine", diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index bfec6cc5..1d46e702 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -504,9 +504,10 @@ or removing a command fails until the table changes in the same commit. | `agentSessions.export` | Export a recorded session as Markdown of at most `maxBytes`: messages, replies, one line per tool call and their times, keeping the start or the end, in words the host passes in `labels` | | `agentSessions.subagents` | List a recorded session's subagents, as the plugin's scan reports them, with their calls and each one's usage; empty when the plugin reports none | | `agentLibrary.configure` | Open the agent library in the platform's application data | -| `agentLibrary.read` | Read the library and what each configurable agent's instructions, skills, MCP servers and hooks hold, with the agent's `backup: {savedAtMs, modifiedSince}` while Core keeps one; an agent's `instructions` is `{path, state, ownLines?}`, `state` comparing Lithe's block in the file with the library (`absent`, `noBlock`, `current`, `stale`, `edited`, `tooLarge`, `unreadable`) and `ownLines` counting the user's own lines outside it; a library saved with `active` reads as that set `on`; optional `query`, `agent` with `presence`, and `sort` add the keys of the matching items as `matches` | -| `agentLibrary.save` | Replace the library the user edited if it is still at the revision read (instruction sets each with `on` and `agents`; `active` is refused), then write Lithe's block in the instruction file of every agent that follows the library, never over a block edited outside Lithe, and answer each agent's `written`, `unchanged`, `skipped` or `failed` with its reason in `instructions` | -| `agentLibrary.apply` | Apply one library change the user chose to one agent's configuration, backing up the configuration or instruction file it replaces first; an instruction `write` changes only Lithe's block and needs `replace` over an edited one, and `import` moves the user's own text outside the block into a new or existing set at the library revision read, leaving only the block, and answers `{changed, revision, instructions}` | +| `agentLibrary.read` | Read the library `directory`, the library and what each configurable agent's instructions, skills, MCP servers and hooks hold, with the agent's `backup: {savedAtMs, modifiedSince}` while Core keeps one and its `mcpServerSupport` (the transports and server fields its plugin declares); MCP server variables and headers are `{name, valueSet}`, never a value; each server's state per agent compares what a put writes, and `stateDetails` gives the reason an item cannot be put and the server fields the agent does not keep; `found` groups the servers, hooks and skills agents hold outside the library, marking distinct copies, differences from the library and whether and from which agent each group can be imported; an agent's `instructions` is `{path, state, ownLines?}`, `state` comparing Lithe's block in the file with the library (`absent`, `noBlock`, `current`, `stale`, `edited`, `tooLarge`, `unreadable`) and `ownLines` counting the user's own lines outside it; a library saved with `active` reads as that set `on`; optional `query`, `agent` with `presence`, and `sort` add the keys of the matching items as `matches` | +| `agentLibrary.save` | Replace the library the user edited if it is still at the revision read (instruction sets each with `on` and `agents`; `active` is refused; a server variable without a value keeps the value the library has, a renamed server naming its old name in `renamedFrom`), writing `library.json` owner-only, then write Lithe's block in the instruction file of every agent that follows the library, never over a block edited outside Lithe, and answer each agent's `written`, `unchanged`, `skipped` or `failed` with its reason in `instructions` | +| `agentLibrary.parseServers` | Read the MCP servers a pasted JSON text describes (common client shapes, comments and trailing commas allowed) into the shape `save` takes, values included, without saving; answer `{servers, problems}`, a syntax error with its line and character column and each unreadable entry with its JSON pointer and reason | +| `agentLibrary.apply` | Apply one library change the user chose to one agent's configuration, backing up the configuration or instruction file it replaces first; a server `put` writes only the fields the agent's plugin declares, values included, and is refused for a transport, variables or a switched-off server the agent cannot keep; a server `import` takes the agent's server with its values into the library at the revision read without changing the agent, answering `{changed, revision}`; an instruction `write` changes only Lithe's block and needs `replace` over an edited one, and `import` moves the user's own text outside the block into a new or existing set at the library revision read, leaving only the block, and answers `{changed, revision, instructions}` | | `agentLibrary.importSkill` | Copy a skill from an agent or a directory the user chose into the library | | `agentLibrary.removeSkill` | Remove a library skill and its links from agents | | `agentProviders.read` | Read each agent's model, model providers, profiles and account label through its plugin, with a key reported only as `keySet` and other secrets as variable names; adds the providers Lithe saved (`listKeptBy: "lithe"`) and the agent's `backup: {savedAtMs, modifiedSince}`; always answers `models`, the models the plugin lists (none when it lists none), each with `shown`, beside the `efforts`, `speeds`, `effort` and `speed` it reports | diff --git a/rust/crates/agent-runtime/Cargo.toml b/rust/crates/agent-runtime/Cargo.toml index 3f44c14e..4f65eaaf 100644 --- a/rust/crates/agent-runtime/Cargo.toml +++ b/rust/crates/agent-runtime/Cargo.toml @@ -7,6 +7,7 @@ description = "Agent CLI sessions Core runs for agent plugins (plan API-45): the publish = false [dependencies] +base64 = "0.22" lithe-agent-sessions = { path = "../agent-sessions" } lithe-diagnostics = { path = "../diagnostics" } lithe-lsp-engine = { path = "../lsp-engine" } @@ -19,7 +20,7 @@ lithe-protocol = { path = "../protocol" } lithe-request-context = { path = "../request-context" } lithe-workspace = { path = "../workspace" } serde = { version = "1.0", features = ["derive"] } -serde_json = { version = "1.0", features = ["raw_value"] } +serde_json = { version = "1.0", features = ["preserve_order", "raw_value"] } sha2 = "0.10" url = "2.5" diff --git a/rust/crates/agent-runtime/src/lib.rs b/rust/crates/agent-runtime/src/lib.rs index 2ae3836b..f54d5d20 100644 --- a/rust/crates/agent-runtime/src/lib.rs +++ b/rust/crates/agent-runtime/src/lib.rs @@ -132,6 +132,7 @@ impl Runtime { "agentLibrary.configure" => self.library.configure(payload), "agentLibrary.read" => self.library.read(self, payload), "agentLibrary.save" => self.library.save(self, payload), + "agentLibrary.parseServers" => self.library.parse_servers(payload), "agentLibrary.apply" => self.library.apply(self, payload), "agentLibrary.importSkill" => self.library.import_skill(self, payload), "agentLibrary.removeSkill" => self.library.remove_skill(self, payload), diff --git a/rust/crates/agent-runtime/src/library.rs b/rust/crates/agent-runtime/src/library.rs index 9f416ad3..09788e42 100644 --- a/rust/crates/agent-runtime/src/library.rs +++ b/rust/crates/agent-runtime/src/library.rs @@ -3,7 +3,9 @@ //! //! The library is Lithe's own data, in a directory of the platform's //! application data that the host names with `agentLibrary.configure`: -//! `library.json` holds the servers, hooks and instruction sets, +//! `library.json`, owner-only, holds the servers with the values of their +//! environment variables and headers (`servers` module), the hooks and the +//! instruction sets, //! `skills//` holds one directory per skill, `state.json` records what //! Core last wrote to each agent's instruction file, `staging/` holds the //! copies plugins edit, `backups/` the agents' files as they were before @@ -42,13 +44,22 @@ //! replaces nothing. A restore puts the agent's files back whichever kind of //! change wrote them. //! +//! `agentLibrary.read` also answers, for the host to show without rules of +//! its own, why a server cannot be put into an agent and which of its +//! fields the agent does not keep, and the items agents hold that the +//! library does not, grouped (`found` module). `agentLibrary.parseServers` +//! reads servers out of JSON the user pasted (`paste` module). +//! //! Logs carry plugin and agent IDs, categories, counts and codes, never -//! names, commands, paths or text. +//! names, commands, paths, text or a variable's value. mod backups; +mod found; mod instructions; +mod paste; mod providers; mod saved; +mod servers; #[cfg(test)] pub(crate) use providers::is_endpoint_for_test; @@ -56,11 +67,12 @@ pub(crate) use providers::is_endpoint_for_test; use crate::backend::BackendLink; use crate::catalog::CatalogAgent; use crate::{log, Runtime}; -use lithe_plugin_agents::{resolve_root, ConfigurationDeclaration}; +use lithe_plugin_agents::{resolve_root, ConfigurationDeclaration, McpServerSupport}; use lithe_protocol::{CoreError, ErrorCode}; use lithe_request_context::Source; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; +use servers::{AgentServer, Blocked, Plan, Server}; use sha2::{Digest, Sha256}; use std::collections::{BTreeMap, BTreeSet}; use std::fs; @@ -130,31 +142,6 @@ pub(crate) struct Library { // --------------------------------------------------------------------------- // The library's data. -/// How a client reaches an MCP server. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "lowercase")] -enum Transport { - Stdio, - Http, - Sse, -} - -/// An MCP server of the library. A server with environment variables or -/// headers is not kept in version 0: their values are secrets Lithe does not -/// store. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -struct Server { - name: String, - transport: Transport, - #[serde(default, skip_serializing_if = "Option::is_none")] - command: Option, - #[serde(default, skip_serializing_if = "Vec::is_empty")] - args: Vec, - #[serde(default, skip_serializing_if = "Option::is_none")] - url: Option, -} - /// A hook command as the agents run it. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -330,42 +317,6 @@ enum Origin { Agent, } -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] -struct AgentServer { - name: String, - transport: Transport, - #[serde(default, skip_serializing_if = "Option::is_none")] - command: Option, - #[serde(default, skip_serializing_if = "Vec::is_empty")] - args: Vec, - #[serde(default, skip_serializing_if = "Option::is_none")] - url: Option, - /// Names of the environment variables the server is given; never values. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - environment_names: Vec, - /// Names of the HTTP headers the server is sent; never values. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - header_names: Vec, - origin: Origin, - /// What installed it when `origin` is `agent`, such as a CLI plugin. - #[serde(default, skip_serializing_if = "Option::is_none")] - provider: Option, -} - -impl AgentServer { - /// Whether it is exactly `server`, with nothing Lithe does not keep. - fn is(&self, server: &Server) -> bool { - self.environment_names.is_empty() - && self.header_names.is_empty() - && self.name == server.name - && self.transport == server.transport - && self.command == server.command - && self.args == server.args - && self.url == server.url - } -} - #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct AgentHook { @@ -517,38 +468,6 @@ fn is_skill_name(name: &str) -> bool { .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '_' || c == '-') } -fn check_transport( - transport: Transport, - command: Option<&str>, - args: &[String], - url: Option<&str>, - field: &str, -) -> Check { - check_optional_text(command, &format!("{field}.command"))?; - check_optional_text(url, &format!("{field}.url"))?; - if args.len() > MAX_ARGUMENTS { - return Err(format!("{field}.args")); - } - for (index, argument) in args.iter().enumerate() { - check_text(argument, &format!("{field}.args[{index}]"), false)?; - } - match transport { - Transport::Stdio => { - if command.is_none_or(|command| command.trim().is_empty()) || url.is_some() { - return Err(format!("{field}.command")); - } - } - Transport::Http | Transport::Sse => { - let web = - url.is_some_and(|url| url.starts_with("http://") || url.starts_with("https://")); - if !web || command.is_some() || !args.is_empty() { - return Err(format!("{field}.url")); - } - } - } - Ok(()) -} - fn check_hook_fields( event: &str, matcher: Option<&str>, @@ -567,20 +486,18 @@ fn check_hook_fields( Ok(()) } -impl Server { - fn check(&self, field: &str) -> Check { - check_name(&self.name, &format!("{field}.name"))?; - check_transport( - self.transport, - self.command.as_deref(), - &self.args, - self.url.as_deref(), - field, - ) +impl LibraryData { + /// The library as `agentLibrary.read` answers it: what a save sends + /// back, with each variable's name and whether it has a value in place + /// of the value. + fn answer(&self) -> Value { + json!({ + "mcpServers": self.mcp_servers.iter().map(Server::answer).collect::>(), + "hooks": self.hooks, + "instructions": self.instructions, + }) } -} -impl LibraryData { fn check(&self) -> Check { if self.mcp_servers.len() > MAX_SERVERS { return Err("mcpServers".into()); @@ -698,24 +615,7 @@ impl Snapshot { return Err("mcpServers".into()); } for (index, server) in self.mcp_servers.iter().enumerate() { - let field = format!("mcpServers[{index}]"); - check_name(&server.name, &format!("{field}.name"))?; - check_transport( - server.transport, - server.command.as_deref(), - &server.args, - server.url.as_deref(), - &field, - )?; - for (list, names) in [ - ("environmentNames", &server.environment_names), - ("headerNames", &server.header_names), - ] { - if names.len() > MAX_VARIABLE_NAMES || !names.iter().all(|n| is_variable_name(n)) { - return Err(format!("{field}.{list}")); - } - } - check_optional_name(server.provider.as_deref(), &format!("{field}.provider"))?; + server.check(&format!("mcpServers[{index}]"))?; } if self.hooks.len() > MAX_HOOKS { return Err("hooks".into()); @@ -825,9 +725,20 @@ fn sibling_temporary(target: &Path, purpose: &str) -> Option { /// then renamed over it. `target` is never a link; callers resolve links /// first. fn write_replacing(target: &Path, bytes: &[u8]) -> io::Result<()> { + write_new_file(target, bytes, fs::metadata(target).ok()) +} + +/// Replaces the file at `target` with `bytes` like [`write_replacing`], but +/// owner-only whatever the old file allowed: the file holds secrets. +fn write_owner_only(target: &Path, bytes: &[u8]) -> io::Result<()> { + write_new_file(target, bytes, None) +} + +/// Writes `bytes` to a new file next to `target` with the permissions of +/// `existing`, owner-only without one, and renames it over `target`. +fn write_new_file(target: &Path, bytes: &[u8], existing: Option) -> io::Result<()> { let temporary = sibling_temporary(target, "write") .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidInput))?; - let existing = fs::metadata(target).ok(); let mut options = fs::OpenOptions::new(); options.write(true).create_new(true); #[cfg(unix)] @@ -1039,24 +950,53 @@ fn unquote(value: &str) -> String { value.to_string() } -/// The description in the `SKILL.md` of `directory`, if it has one; `None` -/// as the outer value when there is no readable `SKILL.md`. -fn skill_description(directory: &Path) -> Option> { +/// What Core reads of a skill directory's `SKILL.md`. +struct SkillFile { + description: Option, + /// SHA-256 of the file, which tells two copies of a skill apart; `None` + /// for a file too large to read. + digest: Option, +} + +/// The `SKILL.md` of `directory`; `None` when there is no readable one. +fn skill_file(directory: &Path) -> Option { let bytes = match read_bounded(&directory.join(SKILL_FILE), MAX_SKILL_FILE_BYTES) { Ok(Some(bytes)) => bytes, Ok(None) | Err(ReadFailure::Io) => return None, // A skill too large to read for its description is still a skill. - Err(ReadFailure::TooLarge) => return Some(None), + Err(ReadFailure::TooLarge) => { + return Some(SkillFile { + description: None, + digest: None, + }) + } }; - Some(front_matter(&String::from_utf8_lossy(&bytes)).1) + Some(SkillFile { + description: front_matter(&String::from_utf8_lossy(&bytes)).1, + digest: Some(digest(&bytes)), + }) +} + +/// The description in the `SKILL.md` of `directory`, if it has one; `None` +/// as the outer value when there is no readable `SKILL.md`. +fn skill_description(directory: &Path) -> Option> { + skill_file(directory).map(|file| file.description) +} + +/// A skill of the library. +struct LibrarySkill { + name: String, + description: Option, + /// SHA-256 of its `SKILL.md`, as [`SkillFile::digest`]. + digest: Option, } /// The skills of the library, by name. -fn library_skills(directory: &Path) -> Vec<(String, Option)> { +fn library_skills(directory: &Path) -> Vec { let Ok(entries) = fs::read_dir(directory.join(SKILLS_DIRECTORY)) else { return Vec::new(); }; - let mut skills: Vec<(String, Option)> = entries + let mut skills: Vec = entries .filter_map(Result::ok) .filter(|entry| entry.file_type().is_ok_and(|kind| kind.is_dir())) .filter_map(|entry| { @@ -1064,11 +1004,16 @@ fn library_skills(directory: &Path) -> Vec<(String, Option)> { if !is_skill_name(&name) { return None; } - Some((name, skill_description(&entry.path())?)) + let file = skill_file(&entry.path())?; + Some(LibrarySkill { + name, + description: file.description, + digest: file.digest, + }) }) .take(MAX_SKILLS) .collect(); - skills.sort_by(|left, right| left.0.cmp(&right.0)); + skills.sort_by(|left, right| left.name.cmp(&right.name)); skills } @@ -1096,6 +1041,8 @@ impl SkillKind { struct AgentSkill { name: String, description: Option, + /// SHA-256 of its `SKILL.md`, as [`SkillFile::digest`]. + digest: Option, kind: SkillKind, } @@ -1130,12 +1077,13 @@ fn agent_skills(root: &Path, library: &Path) -> Result, ReadFail } else { continue; }; - let Some(description) = skill_description(&path) else { + let Some(file) = skill_file(&path) else { continue; }; skills.push(AgentSkill { name, - description, + description: file.description, + digest: file.digest, kind, }); if skills.len() == MAX_SKILLS { @@ -1402,9 +1350,14 @@ fn read_snapshot( "The agent plugin returned an invalid configuration.", ) }; - let snapshot: Snapshot = serde_json::from_value(answer).map_err(|_| invalid())?; + // The answer may hold the values of environment variables and headers: + // a refusal never carries the decoder's message, which can quote one. + let mut snapshot: Snapshot = serde_json::from_value(answer).map_err(|_| invalid())?; let ids: BTreeSet<&str> = configuration.files.iter().map(|f| f.id.as_str()).collect(); snapshot.check(&ids).map_err(|_| invalid())?; + for server in &mut snapshot.mcp_servers { + server.normalize(); + } Ok(snapshot) } @@ -1415,6 +1368,8 @@ struct AgentView { entry: Value, snapshot: Option, skills: Option>, + /// What the agent's MCP servers take, as its plugin declares. + support: McpServerSupport, } // --------------------------------------------------------------------------- @@ -1687,7 +1642,7 @@ impl Library { "The agent library file is not a library Lithe reads.", ) }; - let mut file: LibraryFile = serde_json::from_slice(&bytes).map_err(|_| invalid())?; + let mut file = Self::parse_library(&bytes).ok_or_else(invalid)?; if file.version != 0 || file.library.instructions.migrate_active().is_err() || file.library.check().is_err() @@ -1697,16 +1652,38 @@ impl Library { Ok((file.library, digest(&bytes))) } + /// `library.json` as written, if it decodes. A file holding the + /// `renamedFrom` only a save may give is not one Core wrote. + fn parse_library(bytes: &[u8]) -> Option { + serde_json::from_slice::(bytes) + .ok() + .filter(|file| { + file.library + .mcp_servers + .iter() + .all(|server| server.renamed_from.is_none()) + }) + } + /// Replaces `library.json` with `library` and answers its new revision. - /// Callers hold the writing lock. + /// The file is owner-only, since it holds the values of servers' + /// environment variables and headers, and never larger than Core reads + /// back (`agentLibrary.libraryTooLarge`). Callers hold the writing lock. fn store_library(config: &Config, library: &LibraryData) -> Result { - ensure_private_directory(&config.directory)?; let file = LibraryFileOut { version: 0, library, }; let bytes = serde_json::to_vec_pretty(&file).map_err(|_| write_failed())?; - write_replacing(&config.directory.join(LIBRARY_FILE), &bytes) + if bytes.len() as u64 > MAX_LIBRARY_FILE_BYTES { + return Err(refusal( + ErrorCode::InvalidRequest, + "agentLibrary.libraryTooLarge", + "The library would be larger than Lithe reads back.", + )); + } + ensure_private_directory(&config.directory)?; + write_owner_only(&config.directory.join(LIBRARY_FILE), &bytes) .map_err(|_| write_failed())?; Ok(digest(&bytes)) } @@ -1771,57 +1748,68 @@ impl Library { .collect(); Value::Object(map) }; - let server_states: serde_json::Map = library - .mcp_servers - .iter() - .map(|server| { - let states = states_of(&|view| { - let snapshot = view.snapshot.as_ref()?; - Some( - match snapshot.mcp_servers.iter().find(|s| s.name == server.name) { - Some(found) if found.is(server) => "on", - Some(_) => "conflict", - None if snapshot.targets.mcp_servers.is_none() => "unsupported", - None => "off", - }, - ) - }); - (server.name.clone(), states) - }) - .collect(); - let hook_states: serde_json::Map = library - .hooks - .iter() - .map(|hook| { - let wanted = hook.hook(); - let states = states_of(&|view| { - let snapshot = view.snapshot.as_ref()?; - Some(if snapshot.hooks.iter().any(|h| h.is(&wanted)) { - "on" - } else if snapshot.targets.hooks.is_none() - || !snapshot.supports_event(&hook.event) - { - "unsupported" - } else { - "off" - }) - }); - (hook.id.clone(), states) - }) - .collect(); + let mut server_states = serde_json::Map::new(); + let mut server_details = serde_json::Map::new(); + for server in &library.mcp_servers { + let mut states = serde_json::Map::new(); + let mut details = serde_json::Map::new(); + for view in &views { + let Some(snapshot) = &view.snapshot else { + continue; + }; + let (state, detail) = servers::state(server, &view.support, snapshot); + states.insert(view.key.clone(), json!(state)); + if let Some(detail) = detail { + details.insert(view.key.clone(), detail); + } + } + server_states.insert(server.name.clone(), Value::Object(states)); + if !details.is_empty() { + server_details.insert(server.name.clone(), Value::Object(details)); + } + } + let mut hook_states = serde_json::Map::new(); + let mut hook_details = serde_json::Map::new(); + for hook in &library.hooks { + let wanted = hook.hook(); + let mut states = serde_json::Map::new(); + let mut details = serde_json::Map::new(); + for view in &views { + let Some(snapshot) = &view.snapshot else { + continue; + }; + let (state, reason) = if snapshot.hooks.iter().any(|h| h.is(&wanted)) { + ("on", None) + } else if snapshot.targets.hooks.is_none() { + ("unsupported", Some("agentLibrary.noTarget")) + } else if !snapshot.supports_event(&hook.event) { + ("unsupported", Some("agentLibrary.unsupportedEvent")) + } else { + ("off", None) + }; + states.insert(view.key.clone(), json!(state)); + if let Some(reason) = reason { + details.insert(view.key.clone(), json!({ "reason": reason })); + } + } + hook_states.insert(hook.id.clone(), Value::Object(states)); + if !details.is_empty() { + hook_details.insert(hook.id.clone(), Value::Object(details)); + } + } let skill_rows: Vec = skills .iter() - .map(|(name, description)| { + .map(|kept| { let states = states_of(&|view| { let skills = view.skills.as_ref()?; - Some(match skills.iter().find(|skill| skill.name == *name) { + Some(match skills.iter().find(|skill| skill.name == kept.name) { Some(skill) if skill.kind == SkillKind::Library => "on", Some(_) => "conflict", None => "off", }) }); - let mut row = json!({ "name": name, "agents": states }); - if let Some(description) = description { + let mut row = json!({ "name": kept.name, "agents": states }); + if let Some(description) = &kept.description { row["description"] = json!(description); } row @@ -1845,10 +1833,14 @@ impl Library { let servers = library .mcp_servers .iter() - .map(|server| Candidate { - key: &server.name, - texts: vec![&server.name], - states: &server_states[&server.name], + .map(|server| { + let mut texts = vec![server.name.as_str()]; + texts.extend(server.note.as_deref()); + Candidate { + key: &server.name, + texts, + states: &server_states[&server.name], + } }) .collect(); let hooks = library @@ -1882,11 +1874,15 @@ impl Library { "skills": matching(&request, skills), }) }); + let found = found::found(&library, &skills, &views); let mut answer = json!({ + "directory": path_text(&config.directory), "revision": revision, - "library": library, + "library": library.answer(), "skills": skill_rows, "states": { "mcpServers": server_states, "hooks": hook_states }, + "stateDetails": { "mcpServers": server_details, "hooks": hook_details }, + "found": found, "agents": views.into_iter().map(|view| view.entry).collect::>(), }); if let Some(matches) = matches { @@ -1925,10 +1921,14 @@ impl Library { entry, snapshot: None, skills: None, + support: configuration.mcp_server_support(), }; if !agent.may_configure { return view; } + if configuration.read.is_some() { + view.entry["mcpServerSupport"] = json!(view.support); + } let paths = agent_paths(config, &configuration); // The same backup `agentProviders.read` reports: an agent without // providers has one too once the library changed its files. @@ -1970,9 +1970,12 @@ impl Library { .mcp_servers .iter() .map(|server| { - let mut row = json!(server); - row["inLibrary"] = - json!(library.mcp_servers.iter().any(|kept| server.is(kept))); + let mut row = server.answer(); + row["inLibrary"] = json!(servers::in_library( + server, + &library.mcp_servers, + &view.support + )); row }) .collect(); @@ -2018,48 +2021,91 @@ impl Library { /// `agentLibrary.save`: replaces the library if it is still at /// `revision`, then brings the instruction block of every agent that - /// follows the library up to date (`instructions` module). + /// follows the library up to date (`instructions` module). A variable + /// sent without a value keeps the value the library had for it + /// ([`Server::keep_values`]). pub fn save(&self, runtime: &Runtime, payload: Value) -> Result { #[derive(Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct SaveRequest { revision: String, - library: LibraryData, + library: Value, } require_user()?; let request: SaveRequest = crate::decode(payload)?; + // The library may hold the values of environment variables and + // headers: the refusal never carries the decoder's message, which + // can quote one. + let mut library: LibraryData = serde_json::from_value(request.library).map_err(|_| { + refusal( + ErrorCode::InvalidRequest, + "agents.invalidPayload", + "Invalid agent command payload: the library does not have the fields a library takes.", + ) + })?; let config = self.config()?; - if let Err(field) = request.library.check() { - return Err(invalid_library(&field)); - } let path = config.directory.join(LIBRARY_FILE); let revision = { let _writing = self.lock_writing(); let current = match read_bounded(&path, MAX_LIBRARY_FILE_BYTES) { - Ok(Some(bytes)) => digest(&bytes), - Ok(None) => EMPTY_REVISION.to_string(), + Ok(Some(bytes)) => Some(bytes), + Ok(None) => None, // An unreadable library is replaced only by a save that read it. Err(_) => return Err(unreadable_file()), }; - if current != request.revision { + let current_revision = current + .as_deref() + .map_or_else(|| EMPTY_REVISION.to_string(), digest); + if current_revision != request.revision { return Err(revision_changed()); } - Self::store_library(&config, &request.library)? + // A library Core cannot read keeps no values to carry over. + let kept = current + .as_deref() + .and_then(Self::parse_library) + .map(|file| file.library.mcp_servers) + .unwrap_or_default(); + for server in &mut library.mcp_servers { + server.keep_values(&kept); + } + if let Err(field) = library.check() { + return Err(invalid_library(&field)); + } + Self::store_library(&config, &library)? }; log( "agent.library.updated", [ - ("servers", json!(request.library.mcp_servers.len())), - ("hooks", json!(request.library.hooks.len())), - ("sets", json!(request.library.instructions.sets.len())), + ("servers", json!(library.mcp_servers.len())), + ("hooks", json!(library.hooks.len())), + ("sets", json!(library.instructions.sets.len())), ], ); // Each agent is written under the writing lock of its own, so a // change elsewhere never waits for every agent's file. - let instructions = self.sync_instructions(runtime, &config, &request.library, None); + let instructions = self.sync_instructions(runtime, &config, &library, None); Ok(json!({ "revision": revision, "instructions": instructions })) } + /// `agentLibrary.parseServers`: the MCP servers a text the user pasted + /// describes, in the shape a save takes, without saving them. + pub fn parse_servers(&self, payload: Value) -> Result { + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct ParseRequest { + text: String, + } + // The text may hold values: the refusal never quotes the decoder. + let request: ParseRequest = serde_json::from_value(payload).map_err(|_| { + refusal( + ErrorCode::InvalidRequest, + "agents.invalidPayload", + "Invalid agent command payload: parseServers takes the text alone.", + ) + })?; + paste::parse(&request.text) + } + /// `agentLibrary.apply`: one change to one agent's configuration. pub fn apply(&self, runtime: &Runtime, payload: Value) -> Result { require_user()?; @@ -2139,12 +2185,68 @@ impl Library { (Category::Instructions, Operation::Import) => { self.import_instructions(runtime, &config, agent, &paths, change) } + (Category::McpServers, Operation::Import) => { + self.import_server(runtime, &config, agent, configuration, &paths, change) + } _ => Err(invalid_change( - "MCP servers and hooks take put and remove, skills link and unlink, instructions write and import.", + "MCP servers take put, remove and import, hooks put and remove, skills link and unlink, instructions write and import.", )), } } + /// Takes the agent's MCP server `name` into the library, values + /// included: the agent's fittest copy of the name + /// ([`servers::import_rank`]), if the library is still at `revision` and + /// holds no server of the name. The agent's files are not changed. + fn import_server( + &self, + runtime: &Runtime, + config: &Config, + agent: &CatalogAgent, + configuration: &ConfigurationDeclaration, + paths: &AgentPaths, + change: &Change, + ) -> Result { + let (Some(name), Some(revision)) = (change.name.as_deref(), change.revision.as_deref()) + else { + return Err(invalid_change( + "Importing an MCP server names the server and the library revision.", + )); + }; + let snapshot = read_snapshot(&*runtime.link, agent, configuration, &paths.files)?; + let copy = snapshot + .mcp_servers + .iter() + .filter(|copy| copy.name == name) + .min_by_key(|copy| servers::import_rank(copy)) + .ok_or_else(not_in_agent)?; + let _writing = self.lock_writing(); + let (mut library, current) = self.load(config)?; + if current != revision { + return Err(revision_changed()); + } + if library.mcp_servers.iter().any(|server| server.name == name) { + return Err(refusal( + ErrorCode::InvalidRequest, + "agentLibrary.serverExists", + "The library already has an MCP server of this name.", + )); + } + if library.mcp_servers.len() >= MAX_SERVERS { + return Err(refusal( + ErrorCode::InvalidRequest, + "agentLibrary.libraryFull", + "The library holds as many items of this kind as it can.", + )); + } + library.mcp_servers.push(copy.library_server()); + if let Err(field) = library.check() { + return Err(invalid_library(&field)); + } + let revision = Self::store_library(config, &library)?; + Ok(json!({ "changed": true, "revision": revision })) + } + /// Changes an MCP server or hook through the plugin, on a staged copy. fn apply_file( &self, @@ -2190,11 +2292,16 @@ impl Library { .find(|server| server.name == name) .cloned() .ok_or_else(unknown_item)?; - let wanted = server.clone(); + let support = configuration.mcp_server_support(); + let written = Plan::of(&server, &support) + .map_err(Blocked::refusal)? + .change(); ( - json!({ "category": "mcpServers", "op": "put", "server": server }), + json!({ "category": "mcpServers", "op": "put", "server": written }), Box::new(move |snapshot: &Snapshot| { - snapshot.mcp_servers.iter().any(|s| s.is(&wanted)) + Plan::of(&server, &support).is_ok_and(|plan| { + snapshot.mcp_servers.iter().any(|copy| plan.holds(copy)) + }) }), ) } diff --git a/rust/crates/agent-runtime/src/library/found.rs b/rust/crates/agent-runtime/src/library/found.rs new file mode 100644 index 00000000..3a2b113d --- /dev/null +++ b/rust/crates/agent-runtime/src/library/found.rs @@ -0,0 +1,319 @@ +//! The items agents hold that the library does not hold the same: the +//! groups `agentLibrary.read` answers as `found`, so the host shows one row +//! per item, whichever agents hold it, without rules of its own. +//! +//! - MCP servers are grouped by name. Two copies are the same when they +//! start the server the same way: transport, command, arguments, URL, +//! variables with their values, the switch, the tools left out and the +//! timeouts. A copy is found when no library server of its name writes +//! exactly it into its agent. +//! - Hooks are grouped by event, matcher, command and timeout, so every +//! copy of a group is the same hook. A hook is found when no library hook +//! has its event, matcher and command. +//! - Skills are grouped by name: the agents' own skill directories and +//! links elsewhere, then the skills their CLIs installed themselves. Two +//! copies are the same when their `SKILL.md` bytes are; a skill a CLI +//! installed has no file Core reads and is compared by its description. +//! +//! Each copy names its agent and its place in that agent's entry, and the +//! number of the distinct copy it is (`variant`, from 0 in the order the +//! copies come). Each group says whether the library holds an item of the +//! same key, which differs from every copy found, whether the library can +//! import one and from which agent, or why it cannot, and for a server +//! whether the copy it would import lacks a variable's value +//! (`valuesMissing`). Answers never carry a variable's value: two copies +//! that differ only in a value are two variants. + +use super::servers::{import_rank, in_library, AgentServer}; +use super::{AgentView, LibraryData, LibrarySkill, SkillKind, MAX_HOOKS, MAX_SERVERS}; +use serde_json::{json, Value}; +use std::collections::BTreeMap; + +/// Groups `items` by `key`, in the order the first item of each comes. +fn grouped(items: Vec, key: impl Fn(&T) -> K) -> Vec<(K, Vec)> { + let mut groups: Vec<(K, Vec)> = Vec::new(); + let mut at: BTreeMap = BTreeMap::new(); + for item in items { + let key = key(&item); + let index = *at.entry(key.clone()).or_insert_with(|| { + groups.push((key, Vec::new())); + groups.len() - 1 + }); + groups[index].1.push(item); + } + groups +} + +/// The variant of each of `copies`: the index, among the distinct copies +/// in order, of the first that `same` says it is; and how many there are. +fn variants(copies: &[T], same: impl Fn(&T, &T) -> bool) -> (Vec, usize) { + let mut firsts: Vec<&T> = Vec::new(); + let numbers = copies + .iter() + .map( + |copy| match firsts.iter().position(|first| same(first, copy)) { + Some(number) => number, + None => { + firsts.push(copy); + firsts.len() - 1 + } + }, + ) + .collect(); + (numbers, firsts.len()) +} + +/// Adds what a group says about importing: `importable`, and `importFrom` +/// or the `reason` it cannot be. +fn import(group: &mut Value, from: Result, &'static str>) { + match from { + Ok(agent) => { + group["importable"] = json!(true); + if let Some(agent) = agent { + group["importFrom"] = json!(agent); + } + } + Err(reason) => { + group["importable"] = json!(false); + group["reason"] = json!(reason); + } + } +} + +/// One MCP server an agent holds that the library does not. +struct FoundServer<'a> { + agent: &'a str, + index: usize, + copy: &'a AgentServer, +} + +fn servers(library: &LibraryData, views: &[AgentView]) -> Vec { + let mut found = Vec::new(); + for view in views { + let Some(snapshot) = &view.snapshot else { + continue; + }; + for (index, copy) in snapshot.mcp_servers.iter().enumerate() { + if !in_library(copy, &library.mcp_servers, &view.support) { + found.push(FoundServer { + agent: &view.key, + index, + copy, + }); + } + } + } + grouped(found, |server| server.copy.name.clone()) + .into_iter() + .map(|(name, copies)| { + let (numbers, count) = variants(&copies, |left, right| left.copy.same_as(right.copy)); + let held = library.mcp_servers.iter().any(|server| server.name == name); + let mut group = json!({ + "name": name, + "copies": copies + .iter() + .zip(&numbers) + .map(|(found, variant)| { + let mut copy = json!({ + "agent": found.agent, + "index": found.index, + "variant": variant, + }); + if held { + copy["differsFromLibrary"] = json!(true); + } + copy + }) + .collect::>(), + "variants": count, + "inLibrary": held, + }); + // The copy an import takes from its agent is that agent's best; + // the group offers the best agent. + let best = copies + .iter() + .min_by_key(|found| import_rank(found.copy)) + .expect("a group has a copy"); + let from = if held { + Err("agentLibrary.serverExists") + } else if library.mcp_servers.len() >= MAX_SERVERS { + Err("agentLibrary.libraryFull") + } else if best.copy.library_server().check("server").is_err() { + Err("agentLibrary.invalidLibrary") + } else { + Ok(Some(best.agent)) + }; + if from.is_ok() && !best.copy.values_known() { + group["valuesMissing"] = json!(true); + } + import(&mut group, from); + group + }) + .collect() +} + +/// A hook as its group knows it: event, matcher (none when empty), +/// command and timeout. +type HookKey = (String, Option, String, Option); + +fn hooks(library: &LibraryData, views: &[AgentView]) -> Vec { + let mut found = Vec::new(); + for view in views { + let Some(snapshot) = &view.snapshot else { + continue; + }; + for (index, hook) in snapshot.hooks.iter().enumerate() { + if !library.hooks.iter().any(|kept| hook.is(&kept.hook())) { + found.push((view.key.as_str(), index, hook)); + } + } + } + grouped(found, |(_, _, hook)| -> HookKey { + ( + hook.event.clone(), + hook.matcher.clone().filter(|matcher| !matcher.is_empty()), + hook.command.clone(), + hook.timeout_seconds, + ) + }) + .into_iter() + .map(|((event, matcher, command, timeout), copies)| { + let mut group = json!({ + "event": event, + "command": command, + "copies": copies + .iter() + .map(|(agent, index, _)| json!({ "agent": agent, "index": index })) + .collect::>(), + }); + if let Some(matcher) = matcher { + group["matcher"] = json!(matcher); + } + if let Some(timeout) = timeout { + group["timeoutSeconds"] = json!(timeout); + } + let from = if library.hooks.len() >= MAX_HOOKS { + Err("agentLibrary.libraryFull") + } else { + Ok(None) + }; + import(&mut group, from); + group + }) + .collect() +} + +/// What a found skill is compared by. +#[derive(Clone, PartialEq, Eq)] +enum SkillContent<'a> { + /// The digest of a skill directory's `SKILL.md`; `None` when Core could + /// not read it, and then the copy is like no other. + File(Option<&'a str>), + /// The description of a skill the CLI installed itself. + Provided(Option<&'a str>), +} + +impl SkillContent<'_> { + fn same(&self, other: &Self) -> bool { + match (self, other) { + (SkillContent::File(Some(left)), SkillContent::File(Some(right))) => left == right, + (SkillContent::Provided(left), SkillContent::Provided(right)) => left == right, + _ => false, + } + } +} + +/// One skill an agent has outside the library. +struct FoundSkill<'a> { + agent: &'a str, + /// `skills` for the agent's skills directory, `providedSkills` for what + /// its CLI installed. + source: &'static str, + index: usize, + name: &'a str, + content: SkillContent<'a>, + own: bool, +} + +fn skills(library: &[LibrarySkill], views: &[AgentView]) -> Vec { + let mut found = Vec::new(); + for view in views { + for (index, skill) in view.skills.iter().flatten().enumerate() { + if skill.kind != SkillKind::Library { + found.push(FoundSkill { + agent: &view.key, + source: "skills", + index, + name: &skill.name, + content: SkillContent::File(skill.digest.as_deref()), + own: skill.kind == SkillKind::Own, + }); + } + } + } + for view in views { + for (index, skill) in view.snapshot.iter().flat_map(|s| &s.skills).enumerate() { + found.push(FoundSkill { + agent: &view.key, + source: "providedSkills", + index, + name: &skill.name, + content: SkillContent::Provided(skill.description.as_deref()), + own: false, + }); + } + } + grouped(found, |skill| skill.name.to_string()) + .into_iter() + .map(|(name, copies)| { + let (numbers, count) = + variants(&copies, |left, right| left.content.same(&right.content)); + let kept = library.iter().find(|skill| skill.name == name); + let mut group = json!({ + "name": name, + "copies": copies + .iter() + .zip(&numbers) + .map(|(found, variant)| { + let mut copy = json!({ + "agent": found.agent, + "source": found.source, + "index": found.index, + "variant": variant, + }); + if let Some(kept) = kept { + let same = kept.digest.as_deref().is_some_and(|digest| { + found.content.same(&SkillContent::File(Some(digest))) + }); + copy["differsFromLibrary"] = json!(!same); + } + copy + }) + .collect::>(), + "variants": count, + "inLibrary": kept.is_some(), + }); + let from = match copies.iter().find(|found| found.own) { + _ if kept.is_some() => Err("agentLibrary.skillExists"), + Some(own) => Ok(Some(own.agent)), + None => Err("agentLibrary.notOwnSkill"), + }; + import(&mut group, from); + group + }) + .collect() +} + +/// `found` of `agentLibrary.read`: `{mcpServers, hooks, skills}`, the +/// groups of each category in the order their first copy comes. +pub(super) fn found( + library: &LibraryData, + skills_kept: &[LibrarySkill], + views: &[AgentView], +) -> Value { + json!({ + "mcpServers": servers(library, views), + "hooks": hooks(library, views), + "skills": skills(skills_kept, views), + }) +} diff --git a/rust/crates/agent-runtime/src/library/paste.rs b/rust/crates/agent-runtime/src/library/paste.rs new file mode 100644 index 00000000..4d130b86 --- /dev/null +++ b/rust/crates/agent-runtime/src/library/paste.rs @@ -0,0 +1,477 @@ +//! `agentLibrary.parseServers`: the MCP servers a text the user pasted +//! describes, in the shape `agentLibrary.save` takes. Nothing is saved, and +//! nothing is read or fetched beyond the text. +//! +//! The text is JSON, with `//` and `/* */` comments and trailing commas +//! allowed. Text that is not JSON on its own is tried once more between +//! `{` and `}`, so one pasted `"name": {…}` member reads too; a syntax error +//! is reported where the text as pasted has it. Servers are found in the +//! first of these shapes the text has: +//! +//! - an object whose `mcpServers`, `servers`, `context_servers` or `mcp` +//! (or `mcp.servers`) member maps names to servers; +//! - one server object, which has `command`, `url`, `serverUrl` or +//! `httpUrl`, named by its `name` member when it has one; +//! - an array of server objects, each named by its `name`; +//! - an object mapping names to servers. +//! +//! A server entry may give its command as a string, as an array of the +//! command and its arguments, or as `{path, args, env}`; its URL as `url`, +//! `serverUrl`, `httpUrl` or `uri`; its variables as `env` or `environment` +//! and headers as `headers` or `http_headers`; tools left out as +//! `disabledTools` or `excludeTools`; and switches it off with +//! `disabled: true` or `enabled: false`. `type` or `transport` names the +//! transport (`stdio` or `local`; `http`, `streamable-http`, +//! `streamableHttp` or `remote`; `sse`); without one a command is `stdio`, a +//! URL whose path ends in `/sse` is `sse` and any other URL `http`. Numbers +//! and booleans where text belongs read as text. Other members are ignored. +//! +//! The answer carries the values of the variables the text gave, since the +//! host sent them; nothing here logs them or puts them in an error. + +use super::servers::{SecretValue, Server, Transport, Variable}; +use super::{check_name, refusal, MAX_SERVERS}; +use lithe_protocol::{CoreError, ErrorCode}; +use serde_json::{json, Map, Value}; +use std::collections::BTreeSet; + +/// Longest text a paste may be, in bytes. +const MAX_TEXT_BYTES: usize = 256 * 1024; + +/// Members a server map may be under, in the order they are looked for. +const MAP_MEMBERS: [&str; 4] = ["mcpServers", "servers", "context_servers", "mcp"]; + +/// Members that make an object one server rather than a map of them. +const URL_MEMBERS: [&str; 4] = ["url", "serverUrl", "httpUrl", "uri"]; + +/// The text with comments and trailing commas outside strings turned into +/// spaces, one for each character, so every other character keeps its line +/// and column. +fn clean(text: &str) -> String { + let chars: Vec = text.chars().collect(); + let mut out: Vec = Vec::with_capacity(chars.len()); + let mut index = 0; + let mut in_string = false; + while index < chars.len() { + let c = chars[index]; + if in_string { + out.push(c); + if c == '\\' && index + 1 < chars.len() { + out.push(chars[index + 1]); + index += 1; + } else if c == '"' { + in_string = false; + } + index += 1; + continue; + } + match (c, chars.get(index + 1)) { + ('"', _) => { + in_string = true; + out.push(c); + index += 1; + } + ('/', Some('/')) => { + while index < chars.len() && chars[index] != '\n' { + out.push(if chars[index] == '\r' { '\r' } else { ' ' }); + index += 1; + } + } + ('/', Some('*')) => { + out.extend([' ', ' ']); + index += 2; + while index < chars.len() { + if chars[index] == '*' && chars.get(index + 1) == Some(&'/') { + out.extend([' ', ' ']); + index += 2; + break; + } + out.push(if matches!(chars[index], '\n' | '\r') { + chars[index] + } else { + ' ' + }); + index += 1; + } + } + _ => { + out.push(c); + index += 1; + } + } + } + // A comma is trailing when only white space comes before a closing + // bracket or the end of the text; comments are spaces by now. + let mut in_string = false; + let mut escaped = false; + for at in 0..out.len() { + let c = out[at]; + if in_string { + match c { + _ if escaped => escaped = false, + '\\' => escaped = true, + '"' => in_string = false, + _ => {} + } + continue; + } + if c == '"' { + in_string = true; + } else if c == ',' + && out[at + 1..] + .iter() + .find(|next| !next.is_whitespace()) + .is_none_or(|next| matches!(next, '}' | ']')) + { + out[at] = ' '; + } + } + out.into_iter().collect() +} + +/// Where a syntax error is in `text`: serde_json's line, and its column +/// counted in characters rather than bytes. +fn position(text: &str, error: &serde_json::Error) -> Value { + let line = error.line(); + let bytes = error.column(); + let column = text + .split('\n') + .nth(line.saturating_sub(1)) + .map_or(bytes, |row| { + let mut end = bytes.min(row.len()); + while !row.is_char_boundary(end) { + end -= 1; + } + row[..end].chars().count() + }); + let reason = match error.classify() { + serde_json::error::Category::Eof => "end", + _ => "syntax", + }; + json!({ "reason": reason, "line": line, "column": column.max(1) }) +} + +/// A JSON pointer member: `~` and `/` escaped. +fn pointer_member(name: &str) -> String { + name.replace('~', "~0").replace('/', "~1") +} + +/// Whether `value` is an object that describes one server. +fn is_server(value: &Value) -> bool { + value.as_object().is_some_and(|object| { + object.contains_key("command") || URL_MEMBERS.iter().any(|key| object.contains_key(*key)) + }) +} + +/// The servers the parsed text holds: each with its name when the text +/// gives one and its JSON pointer. +fn entries(root: &Value) -> Vec<(Option, String, &Value)> { + if let Some(object) = root.as_object() { + for member in MAP_MEMBERS { + let Some(Value::Object(map)) = object.get(member) else { + continue; + }; + // `mcp` may hold the map itself or a `servers` member with it. + if member == "mcp" { + if let Some(Value::Object(servers)) = map.get("servers") { + return named(servers, "/mcp/servers"); + } + } + return named(map, &format!("/{member}")); + } + if is_server(root) { + return vec![(name_member(root), String::new(), root)]; + } + if object.values().any(is_server) { + return named(object, ""); + } + return Vec::new(); + } + if let Some(items) = root.as_array() { + if items.iter().any(is_server) { + return items + .iter() + .enumerate() + .map(|(index, item)| (name_member(item), format!("/{index}"), item)) + .collect(); + } + } + Vec::new() +} + +fn named<'a>(map: &'a Map, path: &str) -> Vec<(Option, String, &'a Value)> { + map.iter() + .map(|(name, value)| { + ( + Some(name.clone()), + format!("{path}/{}", pointer_member(name)), + value, + ) + }) + .collect() +} + +fn name_member(value: &Value) -> Option { + value + .get("name") + .and_then(Value::as_str) + .map(str::to_string) +} + +/// Why one entry gives no server: the problem's `reason`, and the field +/// that is wrong. +struct Unread { + reason: &'static str, + field: Option, +} + +impl Unread { + fn field(field: impl Into) -> Self { + Self { + reason: "invalidField", + field: Some(field.into()), + } + } +} + +/// Text where text belongs: a string, or a number or boolean as written. +fn text(value: &Value) -> Option { + match value { + Value::String(text) => Some(text.clone()), + Value::Number(number) => Some(number.to_string()), + Value::Bool(flag) => Some(flag.to_string()), + _ => None, + } +} + +fn texts(value: &Value, field: &str) -> Result, Unread> { + value + .as_array() + .ok_or_else(|| Unread::field(field))? + .iter() + .enumerate() + .map(|(index, item)| text(item).ok_or_else(|| Unread::field(format!("{field}[{index}]")))) + .collect() +} + +/// The variables of a `{name: value}` object, values included. +fn variables(value: &Value, field: &str, into: &mut Vec) -> Result<(), Unread> { + let map = value.as_object().ok_or_else(|| Unread::field(field))?; + for (name, value) in map { + let value = text(value).ok_or_else(|| Unread::field(field))?; + into.retain(|variable| variable.name != *name); + into.push(Variable { + name: name.clone(), + value: Some(SecretValue::new(value)), + }); + } + Ok(()) +} + +/// The value of the first of `members` the object has, and which it is. +fn first<'a>( + object: &'a Map, + members: &[&'static str], +) -> Option<(&'a Value, &'static str)> { + members + .iter() + .find_map(|member| Some((object.get(*member)?, *member))) +} + +fn seconds(value: &Value, field: &str) -> Result { + value + .as_u64() + .and_then(|seconds| u32::try_from(seconds).ok()) + .ok_or_else(|| Unread::field(field)) +} + +/// The library server an entry describes, named `name` (a stand-in when +/// the text names none), checked as the library checks it. +fn server(name: &str, entry: &Value) -> Result { + let object = entry.as_object().ok_or(Unread { + reason: "noCommandOrUrl", + field: None, + })?; + let mut command = None; + let mut args = Vec::new(); + let mut environment = Vec::new(); + match object.get("command") { + None | Some(Value::Null) => {} + Some(Value::Array(_)) => { + let mut parts = texts(&object["command"], "command")?.into_iter(); + command = parts.next(); + args.extend(parts); + } + Some(Value::Object(zed)) => { + command = zed.get("path").and_then(text); + if let Some(more) = zed.get("args") { + args.extend(texts(more, "args")?); + } + if let Some(env) = zed.get("env") { + variables(env, "environment", &mut environment)?; + } + } + Some(value) => command = Some(text(value).ok_or_else(|| Unread::field("command"))?), + } + if let Some(more) = object.get("args") { + args.extend(texts(more, "args")?); + } + for member in ["env", "environment"] { + if let Some(value) = object.get(member) { + variables(value, "environment", &mut environment)?; + } + } + let (url, named_http) = match first(object, &URL_MEMBERS) { + Some((value, member)) => ( + Some(text(value).ok_or_else(|| Unread::field("url"))?), + member == "httpUrl", + ), + None => (None, false), + }; + let mut headers = Vec::new(); + for member in ["headers", "http_headers"] { + if let Some(value) = object.get(member) { + variables(value, "headers", &mut headers)?; + } + } + let kind = first(object, &["type", "transport"]).and_then(|(value, _)| value.as_str()); + let transport = match kind { + Some("stdio" | "local") => Transport::Stdio, + Some("sse") => Transport::Sse, + Some("http" | "streamable-http" | "streamableHttp" | "streamable_http") => Transport::Http, + Some(_) | None if command.is_some() && url.is_none() => Transport::Stdio, + _ => match &url { + Some(url) if !named_http && ends_in_sse(url) => Transport::Sse, + Some(_) => Transport::Http, + None => { + return Err(Unread { + reason: "noCommandOrUrl", + field: None, + }) + } + }, + }; + let enabled = match (object.get("enabled"), object.get("disabled")) { + (Some(value), _) => value.as_bool().ok_or_else(|| Unread::field("enabled"))?, + (None, Some(value)) => !value.as_bool().ok_or_else(|| Unread::field("enabled"))?, + (None, None) => true, + }; + let disabled_tools = match first(object, &["disabledTools", "excludeTools", "disabled_tools"]) { + Some((value, _)) => texts(value, "disabledTools")?, + None => Vec::new(), + }; + let startup_timeout_seconds = + match first(object, &["startupTimeoutSeconds", "startup_timeout_sec"]) { + Some((value, _)) => Some(seconds(value, "startupTimeoutSeconds")?), + None => None, + }; + let call_timeout_seconds = match first(object, &["callTimeoutSeconds", "tool_timeout_sec"]) { + Some((value, _)) => Some(seconds(value, "callTimeoutSeconds")?), + None => None, + }; + let note = match first(object, &["note", "description"]) { + Some((value, _)) => Some(text(value).ok_or_else(|| Unread::field("note"))?), + None => None, + }; + let server = Server { + name: name.to_string(), + transport, + command, + args, + url, + environment, + headers, + note, + enabled, + paused_agents: Vec::new(), + disabled_tools, + startup_timeout_seconds, + call_timeout_seconds, + icon: None, + renamed_from: None, + }; + server.check("server").map_err(|field| { + let field = field.strip_prefix("server.").unwrap_or(&field).to_string(); + if field == "name" { + Unread { + reason: "invalidName", + field: None, + } + } else { + Unread::field(field) + } + })?; + Ok(server) +} + +/// Whether the path of `url` ends in `/sse`, ignoring a query or fragment. +fn ends_in_sse(url: &str) -> bool { + let path = url.split(['?', '#']).next().unwrap_or(url); + path.trim_end_matches('/').ends_with("/sse") +} + +/// `agentLibrary.parseServers`'s answer for `text`: +/// `{servers, problems}`. +pub(super) fn parse(text: &str) -> Result { + if text.len() > MAX_TEXT_BYTES { + return Err(refusal( + ErrorCode::InvalidRequest, + "agentLibrary.textTooLarge", + "The pasted text is larger than 256 KiB.", + )); + } + // Cleaning keeps every line and column, so an error in the cleaned + // text is where the pasted text has it. + let cleaned = clean(text); + let root = match serde_json::from_str::(&cleaned) { + Ok(root) => root, + Err(error) => match serde_json::from_str::(&clean(&format!("{{{text}\n}}"))) { + Ok(root) => root, + Err(_) => { + return Ok(json!({ "servers": [], "problems": [position(&cleaned, &error)] })); + } + }, + }; + let found = entries(&root); + if found.is_empty() { + return Ok(json!({ "servers": [], "problems": [{ "reason": "noServers" }] })); + } + let mut servers = Vec::new(); + let mut problems = Vec::new(); + let mut names = BTreeSet::new(); + let count = found.len(); + for (name, path, entry) in found.into_iter().take(MAX_SERVERS) { + let named = name.is_some(); + let problem = |unread: Unread| { + let mut problem = json!({ "reason": unread.reason, "path": path }); + if let Some(field) = unread.field { + problem["field"] = json!(field); + } + problem + }; + if let Some(name) = &name { + if check_name(name, "name").is_err() { + problems.push(problem(Unread { + reason: "invalidName", + field: None, + })); + continue; + } + if !names.insert(name.clone()) { + problems.push(problem(Unread { + reason: "duplicateName", + field: None, + })); + continue; + } + } + match server(name.as_deref().unwrap_or("server"), entry) { + Ok(server) => servers.push(server.pasted(named)), + Err(unread) => problems.push(problem(unread)), + } + } + if count > MAX_SERVERS { + problems.push(json!({ "reason": "tooMany" })); + } + Ok(json!({ "servers": servers, "problems": problems })) +} diff --git a/rust/crates/agent-runtime/src/library/servers.rs b/rust/crates/agent-runtime/src/library/servers.rs new file mode 100644 index 00000000..6d7417ad --- /dev/null +++ b/rust/crates/agent-runtime/src/library/servers.rs @@ -0,0 +1,905 @@ +//! The MCP servers of the agent library: what the library keeps, what an +//! agent plugin reports, how a library server is written into one agent, +//! and the states and imports `agentLibrary.read` answers about them. +//! +//! An agent plugin declares which transports its CLI's servers connect with +//! and which further fields of [`MCP_SERVER_FIELDS`] it keeps +//! (`configuration.mcpServers`). Core writes a server into an agent only in +//! a form the agent keeps whole: +//! +//! - A server whose transport the agent does not take, or whose environment +//! variables or headers it cannot keep, is not written at all: without +//! them the server would not start or not authenticate. +//! - A server switched off is written switched off into an agent that keeps +//! the switch, and not at all into one that does not. +//! - Tools left out and timeouts the agent does not keep are left out of the +//! agent, and the read reports them as unsupported fields. +//! - A note and an icon are the library's own and never reach an agent. +//! +//! The values of environment variables and headers are secrets. The library +//! keeps them in `library.json`, which Core writes owner-only; a put hands +//! them to the plugin's `edit` in memory, and the plugin's `read` reports +//! them so Core can tell whether an agent holds the library's server and can +//! import one. Answers carry a variable's name and whether it has a value, +//! never the value, and no log, error or debug output shows one. + +use super::{ + check_name, check_optional_name, check_optional_text, check_text, is_agent_key, + is_variable_name, refusal, Check, Origin, Snapshot, MAX_AGENT_ENTRIES, MAX_ARGUMENTS, + MAX_HOOK_TIMEOUT_SECONDS, MAX_NAME_CHARS, MAX_VARIABLE_NAMES, +}; +use base64::Engine as _; +use lithe_plugin_agents::{McpServerSupport, MCP_SERVER_FIELDS}; +use lithe_protocol::{CoreError, ErrorCode}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::collections::{BTreeMap, BTreeSet}; +use std::fmt; + +/// Longest value of an environment variable or header, in bytes. +const MAX_VALUE_BYTES: usize = 32 * 1024; +/// Longest note, in characters. +const MAX_NOTE_CHARS: usize = 1024; +/// Most tools a server leaves out. +const MAX_DISABLED_TOOLS: usize = 256; +/// Largest icon, decoded, in bytes. +const MAX_ICON_BYTES: usize = 32 * 1024; + +const FIELD_ENVIRONMENT: &str = MCP_SERVER_FIELDS[0]; +const FIELD_HEADERS: &str = MCP_SERVER_FIELDS[1]; +const FIELD_ENABLED: &str = MCP_SERVER_FIELDS[2]; +const FIELD_DISABLED_TOOLS: &str = MCP_SERVER_FIELDS[3]; +const FIELD_STARTUP_TIMEOUT: &str = MCP_SERVER_FIELDS[4]; +const FIELD_CALL_TIMEOUT: &str = MCP_SERVER_FIELDS[5]; + +/// How a client reaches an MCP server. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub(super) enum Transport { + Stdio, + Http, + Sse, +} + +impl Transport { + /// The transport as the manifest's `mcpServers.transports` names it. + fn token(self) -> &'static str { + match self { + Transport::Stdio => "stdio", + Transport::Http => "http", + Transport::Sse => "sse", + } + } +} + +// --------------------------------------------------------------------------- +// Variables and their values. + +/// The value of an environment variable or header. Its `Debug` output is +/// redacted; only `library.json`, the plugin's `edit` and a paste the host +/// sent receive it. +#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(transparent)] +pub(super) struct SecretValue(String); + +impl fmt::Debug for SecretValue { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("SecretValue()") + } +} + +impl SecretValue { + pub(super) fn new(value: String) -> Self { + Self(value) + } + + /// At most [`MAX_VALUE_BYTES`] without NUL; a header value also has no + /// line break, which would split the header. + fn is_valid(&self, place: Place) -> bool { + self.0.len() <= MAX_VALUE_BYTES + && !self.0.contains('\0') + && (place == Place::Environment || !self.0.contains(['\r', '\n'])) + } +} + +/// Where a variable goes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Place { + /// An environment variable of a `stdio` server. + Environment, + /// An HTTP header of an `http` or `sse` server; names compare ignoring + /// ASCII case, as HTTP does. + Headers, +} + +impl Place { + fn field(self) -> &'static str { + match self { + Place::Environment => FIELD_ENVIRONMENT, + Place::Headers => FIELD_HEADERS, + } + } + + /// The name as two variables of this place are told apart. + fn key(self, name: &str) -> String { + match self { + Place::Environment => name.to_string(), + Place::Headers => name.to_ascii_lowercase(), + } + } +} + +/// An environment variable or header of a server: its name and, when known, +/// its value. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(from = "VariableIn")] +pub(super) struct Variable { + pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub value: Option, +} + +/// A variable as a save or a plugin gives it. `valueSet` is what a read +/// answered and is ignored, so the host can send back what it read. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct VariableIn { + name: String, + #[serde(default)] + value: Option, + #[serde(default, rename = "valueSet")] + _value_set: Option, +} + +impl From for Variable { + fn from(variable: VariableIn) -> Self { + Self { + name: variable.name, + value: variable.value, + } + } +} + +/// Variables as an answer shows them: each name and whether it has a value. +fn names_answer(variables: &[Variable]) -> Value { + json!(variables + .iter() + .map(|variable| json!({ "name": variable.name, "valueSet": variable.value.is_some() })) + .collect::>()) +} + +/// Variables as the plugin's `edit` and a paste receive them, values +/// included. +fn values_answer(variables: &[Variable]) -> Value { + json!(variables + .iter() + .map(|variable| { + let mut entry = json!({ "name": variable.name }); + if let Some(value) = &variable.value { + entry["value"] = json!(value.0); + } + entry + }) + .collect::>()) +} + +/// Each variable's value by the name `place` tells them apart by; `None` +/// for a variable without a known value. +fn values_of(variables: &[Variable], place: Place) -> BTreeMap> { + variables + .iter() + .map(|variable| { + ( + place.key(&variable.name), + variable.value.as_ref().map(|value| value.0.as_str()), + ) + }) + .collect() +} + +fn check_variables( + variables: &[Variable], + place: Place, + transport: Transport, + field: &str, +) -> Check { + if variables.is_empty() { + return Ok(()); + } + let list = format!("{field}.{}", place.field()); + let belongs = match place { + Place::Environment => transport == Transport::Stdio, + Place::Headers => transport != Transport::Stdio, + }; + if !belongs || variables.len() > MAX_VARIABLE_NAMES { + return Err(list); + } + let mut seen = BTreeSet::new(); + for (index, variable) in variables.iter().enumerate() { + if !is_variable_name(&variable.name) || !seen.insert(place.key(&variable.name)) { + return Err(format!("{list}[{index}].name")); + } + if variable + .value + .as_ref() + .is_some_and(|value| !value.is_valid(place)) + { + return Err(format!("{list}[{index}].value")); + } + } + Ok(()) +} + +// --------------------------------------------------------------------------- +// The library's servers. + +/// A picture the user gave a server, kept inline in `library.json`. It is +/// the library's own: no agent receives it and Core never fetches one. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(super) struct Icon { + /// `image/png`, `image/jpeg`, `image/gif` or `image/webp`, which the + /// decoded bytes must start as. + #[serde(rename = "type")] + kind: String, + /// The picture's bytes in standard Base64, at most [`MAX_ICON_BYTES`] + /// decoded. + data: String, +} + +impl Icon { + fn is_valid(&self) -> bool { + let Ok(bytes) = base64::engine::general_purpose::STANDARD.decode(&self.data) else { + return false; + }; + !bytes.is_empty() + && bytes.len() <= MAX_ICON_BYTES + && crate::live::image_type(&bytes) == Some(self.kind.as_str()) + } +} + +fn is_true(value: &bool) -> bool { + *value +} + +fn yes() -> bool { + true +} + +/// An MCP server of the library. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(super) struct Server { + pub name: String, + pub transport: Transport, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub command: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub args: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub url: Option, + /// A `stdio` server's environment variables. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub environment: Vec, + /// An `http` or `sse` server's headers. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub headers: Vec, + /// The user's own word on what the server is for; never written into + /// an agent. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub note: Option, + /// Off, the server is written switched off into agents that keep the + /// switch and not into the others. + #[serde(default = "yes", skip_serializing_if = "is_true")] + pub enabled: bool, + /// Agent keys that held the server when it was switched off but cannot + /// mark one off, so the host gave them none; they get it back when it + /// is switched on. Only a server that is off has them. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub paused_agents: Vec, + /// The server's tools, by the names the server gives them, that agents + /// leave out. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub disabled_tools: Vec, + /// Seconds an agent waits for the server to start. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub startup_timeout_seconds: Option, + /// Seconds one call of a tool of the server may take. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub call_timeout_seconds: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub icon: Option, + /// The name the server had in the library a save was read at, so the + /// save keeps the values of a renamed server. Only a save may hold it: + /// it is never written, and `load` refuses a `library.json` that has it. + #[serde(default, skip_serializing)] + pub renamed_from: Option, +} + +fn check_tools(tools: &[String], field: &str) -> Check { + if tools.len() > MAX_DISABLED_TOOLS { + return Err(field.to_string()); + } + let mut seen = BTreeSet::new(); + for (index, tool) in tools.iter().enumerate() { + check_name(tool, &format!("{field}[{index}]"))?; + if !seen.insert(tool.as_str()) { + return Err(format!("{field}[{index}]")); + } + } + Ok(()) +} + +fn check_timeout(seconds: Option, field: String) -> Check { + if seconds.is_some_and(|seconds| seconds == 0 || seconds > MAX_HOOK_TIMEOUT_SECONDS) { + return Err(field); + } + Ok(()) +} + +pub(super) fn check_transport( + transport: Transport, + command: Option<&str>, + args: &[String], + url: Option<&str>, + field: &str, +) -> Check { + check_optional_text(command, &format!("{field}.command"))?; + check_optional_text(url, &format!("{field}.url"))?; + if args.len() > MAX_ARGUMENTS { + return Err(format!("{field}.args")); + } + for (index, argument) in args.iter().enumerate() { + check_text(argument, &format!("{field}.args[{index}]"), false)?; + } + match transport { + Transport::Stdio => { + if command.is_none_or(|command| command.trim().is_empty()) || url.is_some() { + return Err(format!("{field}.command")); + } + } + Transport::Http | Transport::Sse => { + let web = + url.is_some_and(|url| url.starts_with("http://") || url.starts_with("https://")); + if !web || command.is_some() || !args.is_empty() { + return Err(format!("{field}.url")); + } + } + } + Ok(()) +} + +impl Server { + /// Checks the server as the library keeps it; the error names the + /// field, never a value. + pub(super) fn check(&self, field: &str) -> Check { + check_name(&self.name, &format!("{field}.name"))?; + check_transport( + self.transport, + self.command.as_deref(), + &self.args, + self.url.as_deref(), + field, + )?; + check_variables(&self.environment, Place::Environment, self.transport, field)?; + check_variables(&self.headers, Place::Headers, self.transport, field)?; + if self + .note + .as_deref() + .is_some_and(|note| note.chars().count() > MAX_NOTE_CHARS || note.contains('\0')) + { + return Err(format!("{field}.note")); + } + let mut paused = BTreeSet::new(); + if (self.enabled && !self.paused_agents.is_empty()) + || self.paused_agents.len() > MAX_AGENT_ENTRIES + || !self + .paused_agents + .iter() + .all(|key| is_agent_key(key) && paused.insert(key.as_str())) + { + return Err(format!("{field}.pausedAgents")); + } + check_tools(&self.disabled_tools, &format!("{field}.disabledTools"))?; + check_timeout( + self.startup_timeout_seconds, + format!("{field}.startupTimeoutSeconds"), + )?; + check_timeout( + self.call_timeout_seconds, + format!("{field}.callTimeoutSeconds"), + )?; + if self.icon.as_ref().is_some_and(|icon| !icon.is_valid()) { + return Err(format!("{field}.icon")); + } + Ok(()) + } + + /// The server as `agentLibrary.read` answers it: each variable's name + /// and whether it has a value, never the value. + pub(super) fn answer(&self) -> Value { + let mut row = json!(Server { + environment: Vec::new(), + headers: Vec::new(), + ..self.clone() + }); + if !self.environment.is_empty() { + row["environment"] = names_answer(&self.environment); + } + if !self.headers.is_empty() { + row["headers"] = names_answer(&self.headers); + } + row + } + + /// The server as a paste answers it: what the host sent, values + /// included, and no `name` when the paste gave none. + pub(super) fn pasted(&self, named: bool) -> Value { + let mut row = self.answer(); + if !self.environment.is_empty() { + row["environment"] = values_answer(&self.environment); + } + if !self.headers.is_empty() { + row["headers"] = values_answer(&self.headers); + } + if !named { + if let Some(row) = row.as_object_mut() { + row.remove("name"); + } + } + row + } + + /// Gives each variable a save left without a value the value `kept`, the + /// library the save replaces, has for it: in the server of the same + /// name, or of `renamedFrom`, under the same name. `renamedFrom` goes. + pub(super) fn keep_values(&mut self, kept: &[Server]) { + let from = self + .renamed_from + .take() + .unwrap_or_else(|| self.name.clone()); + let Some(old) = kept.iter().find(|server| server.name == from) else { + return; + }; + for (variables, old, place) in [ + (&mut self.environment, &old.environment, Place::Environment), + (&mut self.headers, &old.headers, Place::Headers), + ] { + for variable in variables.iter_mut().filter(|v| v.value.is_none()) { + let key = place.key(&variable.name); + variable.value = old + .iter() + .find(|old| place.key(&old.name) == key) + .and_then(|old| old.value.clone()); + } + } + } + + /// The fields of [`MCP_SERVER_FIELDS`] the server uses that an agent + /// with `support` does not keep, in the contract's order. + fn unkept(&self, support: &McpServerSupport) -> Vec<&'static str> { + [ + (FIELD_ENVIRONMENT, !self.environment.is_empty()), + (FIELD_HEADERS, !self.headers.is_empty()), + (FIELD_ENABLED, !self.enabled), + (FIELD_DISABLED_TOOLS, !self.disabled_tools.is_empty()), + ( + FIELD_STARTUP_TIMEOUT, + self.startup_timeout_seconds.is_some(), + ), + (FIELD_CALL_TIMEOUT, self.call_timeout_seconds.is_some()), + ] + .into_iter() + .filter(|(field, used)| *used && !support.keeps(field)) + .map(|(field, _)| field) + .collect() + } +} + +// --------------------------------------------------------------------------- +// What a plugin reports. + +/// An MCP server an agent's configuration holds, as the plugin's `read` +/// reports it. Variables are reported with their values, or by name alone +/// (`environmentNames`, `headerNames`), which [`AgentServer::normalize`] +/// turns into variables without a value. +#[derive(Debug, Clone, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(super) struct AgentServer { + pub name: String, + pub transport: Transport, + #[serde(default)] + pub command: Option, + #[serde(default)] + pub args: Vec, + #[serde(default)] + pub url: Option, + #[serde(default)] + pub environment: Vec, + #[serde(default)] + pub headers: Vec, + /// Names of environment variables, for a plugin that reports no values. + #[serde(default)] + environment_names: Vec, + /// Names of headers, for a plugin that reports no values. + #[serde(default)] + header_names: Vec, + /// `false` when the CLI keeps the server switched off; absent is on. + #[serde(default)] + pub enabled: Option, + #[serde(default)] + pub disabled_tools: Vec, + #[serde(default)] + pub startup_timeout_seconds: Option, + #[serde(default)] + pub call_timeout_seconds: Option, + pub origin: Origin, + /// What installed it when `origin` is `agent`, such as a CLI plugin. + #[serde(default)] + pub provider: Option, +} + +impl AgentServer { + /// Checks what bounds Core's memory and what Core compares. Values, + /// tools and timeouts the library would not take are only shown, and + /// make the server one the library cannot import. + pub(super) fn check(&self, field: &str) -> Check { + check_name(&self.name, &format!("{field}.name"))?; + check_transport( + self.transport, + self.command.as_deref(), + &self.args, + self.url.as_deref(), + field, + )?; + for (list, variables, names) in [ + ("environment", &self.environment, &self.environment_names), + ("headers", &self.headers, &self.header_names), + ] { + let count = variables.len() + names.len(); + if (!variables.is_empty() && !names.is_empty()) + || count > MAX_VARIABLE_NAMES + || !variables + .iter() + .map(|variable| &variable.name) + .chain(names.iter()) + .all(|name| is_variable_name(name)) + { + return Err(format!("{field}.{list}")); + } + } + if self.disabled_tools.len() > MAX_DISABLED_TOOLS + || !self.disabled_tools.iter().all(|tool| { + !tool.is_empty() + && tool.chars().count() <= MAX_NAME_CHARS + && !tool.chars().any(char::is_control) + }) + { + return Err(format!("{field}.disabledTools")); + } + check_optional_name(self.provider.as_deref(), &format!("{field}.provider")) + } + + /// Turns variables reported by name into variables without a value. + pub(super) fn normalize(&mut self) { + for (variables, names) in [ + (&mut self.environment, &mut self.environment_names), + (&mut self.headers, &mut self.header_names), + ] { + variables.extend(names.drain(..).map(|name| Variable { name, value: None })); + } + } + + /// The server as `agentLibrary.read` answers it, with `inLibrary` + /// added by the caller: each variable's name and whether the plugin + /// reported its value, never the value. + pub(super) fn answer(&self) -> Value { + let mut row = json!({ + "name": self.name, + "transport": self.transport, + "origin": self.origin, + }); + if let Some(command) = &self.command { + row["command"] = json!(command); + } + if !self.args.is_empty() { + row["args"] = json!(self.args); + } + if let Some(url) = &self.url { + row["url"] = json!(url); + } + if !self.environment.is_empty() { + row["environment"] = names_answer(&self.environment); + } + if !self.headers.is_empty() { + row["headers"] = names_answer(&self.headers); + } + if let Some(enabled) = self.enabled { + row["enabled"] = json!(enabled); + } + if !self.disabled_tools.is_empty() { + row["disabledTools"] = json!(self.disabled_tools); + } + if let Some(seconds) = self.startup_timeout_seconds { + row["startupTimeoutSeconds"] = json!(seconds); + } + if let Some(seconds) = self.call_timeout_seconds { + row["callTimeoutSeconds"] = json!(seconds); + } + if let Some(provider) = &self.provider { + row["provider"] = json!(provider); + } + row + } + + /// Whether two agents' copies start the same server the same way: + /// everything but where each came from, values included. + pub(super) fn same_as(&self, other: &AgentServer) -> bool { + self.name == other.name + && self.transport == other.transport + && self.command == other.command + && self.args == other.args + && self.url == other.url + && values_of(&self.environment, Place::Environment) + == values_of(&other.environment, Place::Environment) + && values_of(&self.headers, Place::Headers) == values_of(&other.headers, Place::Headers) + && self.enabled.unwrap_or(true) == other.enabled.unwrap_or(true) + && sorted(&self.disabled_tools) == sorted(&other.disabled_tools) + && self.startup_timeout_seconds == other.startup_timeout_seconds + && self.call_timeout_seconds == other.call_timeout_seconds + } + + /// Whether the plugin reported the value of every variable. + pub(super) fn values_known(&self) -> bool { + self.environment + .iter() + .chain(&self.headers) + .all(|variable| variable.value.is_some()) + } + + /// The library server an import of this copy makes. + pub(super) fn library_server(&self) -> Server { + Server { + name: self.name.clone(), + transport: self.transport, + command: self.command.clone(), + args: self.args.clone(), + url: self.url.clone(), + environment: self.environment.clone(), + headers: self.headers.clone(), + note: None, + enabled: self.enabled.unwrap_or(true), + paused_agents: Vec::new(), + disabled_tools: self.disabled_tools.clone(), + startup_timeout_seconds: self.startup_timeout_seconds, + call_timeout_seconds: self.call_timeout_seconds, + icon: None, + renamed_from: None, + } + } +} + +fn sorted(values: &[String]) -> Vec<&str> { + let mut values: Vec<&str> = values.iter().map(String::as_str).collect(); + values.sort_unstable(); + values +} + +// --------------------------------------------------------------------------- +// Writing a library server into one agent. + +/// Why a library server cannot be written into an agent; its code is the +/// refusal of a put and the `reason` of the server's state. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum Blocked { + /// The agent's CLI does not connect with the server's transport. + Transport, + /// The agent keeps no environment variables, or no headers, and the + /// server needs them. + Field, + /// A variable of the server has no value in the library. + ValueMissing, + /// The server is switched off and the agent cannot mark one off. + ServerOff, +} + +impl Blocked { + pub(super) fn code(self) -> &'static str { + match self { + Blocked::Transport => "agentLibrary.transportUnsupported", + Blocked::Field => "agentLibrary.fieldUnsupported", + Blocked::ValueMissing => "agentLibrary.valueMissing", + Blocked::ServerOff => "agentLibrary.serverOff", + } + } + + pub(super) fn refusal(self) -> CoreError { + let (code, message) = match self { + Blocked::Transport => ( + ErrorCode::NotSupported, + "The agent does not connect to MCP servers this way.", + ), + Blocked::Field => ( + ErrorCode::NotSupported, + "The agent keeps no environment variables or headers, which the server needs.", + ), + Blocked::ValueMissing => ( + ErrorCode::InvalidRequest, + "An environment variable or header of the server has no value.", + ), + Blocked::ServerOff => ( + ErrorCode::NotSupported, + "The server is switched off and the agent cannot keep a server switched off.", + ), + }; + refusal(code, self.code(), message) + } +} + +/// How a library server is written into one agent: the server and which of +/// its optional fields the agent keeps. +pub(super) struct Plan<'a> { + server: &'a Server, + enabled: bool, + disabled_tools: bool, + startup: bool, + call: bool, +} + +impl<'a> Plan<'a> { + /// The plan for an agent with `support`, or why there is none. + pub(super) fn of(server: &'a Server, support: &McpServerSupport) -> Result { + if !support.takes_transport(server.transport.token()) { + return Err(Blocked::Transport); + } + let unkept = server.unkept(support); + if unkept.contains(&FIELD_ENVIRONMENT) || unkept.contains(&FIELD_HEADERS) { + return Err(Blocked::Field); + } + if server + .environment + .iter() + .chain(&server.headers) + .any(|variable| variable.value.is_none()) + { + return Err(Blocked::ValueMissing); + } + if unkept.contains(&FIELD_ENABLED) { + return Err(Blocked::ServerOff); + } + Ok(Self { + server, + enabled: support.keeps(FIELD_ENABLED), + disabled_tools: support.keeps(FIELD_DISABLED_TOOLS), + startup: support.keeps(FIELD_STARTUP_TIMEOUT), + call: support.keeps(FIELD_CALL_TIMEOUT), + }) + } + + /// The `server` of the plugin's `edit` for a put: only fields the agent + /// keeps, values included. `enabled` goes whenever the agent keeps the + /// switch, so a put also switches a server back on. + pub(super) fn change(&self) -> Value { + let server = self.server; + let mut change = json!({ "name": server.name, "transport": server.transport }); + if let Some(command) = &server.command { + change["command"] = json!(command); + } + if !server.args.is_empty() { + change["args"] = json!(server.args); + } + if let Some(url) = &server.url { + change["url"] = json!(url); + } + if !server.environment.is_empty() { + change["environment"] = values_answer(&server.environment); + } + if !server.headers.is_empty() { + change["headers"] = values_answer(&server.headers); + } + if self.enabled { + change["enabled"] = json!(server.enabled); + } + if self.disabled_tools && !server.disabled_tools.is_empty() { + change["disabledTools"] = json!(server.disabled_tools); + } + if let Some(seconds) = server.startup_timeout_seconds.filter(|_| self.startup) { + change["startupTimeoutSeconds"] = json!(seconds); + } + if let Some(seconds) = server.call_timeout_seconds.filter(|_| self.call) { + change["callTimeoutSeconds"] = json!(seconds); + } + change + } + + /// Whether `copy` is what this plan writes: the same server and values, + /// and the same of every optional field the agent keeps. Fields the + /// agent does not keep are not compared. + pub(super) fn holds(&self, copy: &AgentServer) -> bool { + let server = self.server; + copy.name == server.name + && copy.transport == server.transport + && copy.command == server.command + && copy.args == server.args + && copy.url == server.url + && values_of(©.environment, Place::Environment) + == values_of(&server.environment, Place::Environment) + && values_of(©.headers, Place::Headers) + == values_of(&server.headers, Place::Headers) + && (!self.enabled || copy.enabled.unwrap_or(true) == server.enabled) + && (!self.disabled_tools + || sorted(©.disabled_tools) == sorted(&server.disabled_tools)) + && (!self.startup || copy.startup_timeout_seconds == server.startup_timeout_seconds) + && (!self.call || copy.call_timeout_seconds == server.call_timeout_seconds) + } +} + +/// Whether the library holds `copy` for an agent with `support`: a library +/// server of its name whose plan writes exactly it. +pub(super) fn in_library( + copy: &AgentServer, + library: &[Server], + support: &McpServerSupport, +) -> bool { + library.iter().any(|server| { + server.name == copy.name && Plan::of(server, support).is_ok_and(|plan| plan.holds(copy)) + }) +} + +/// The state of the library server `server` for one agent whose plugin +/// read `snapshot`, with its details when there is something to say: +/// `{reason?, unsupportedFields?}`. +/// +/// - `on`: a copy of the name is what the plan writes. +/// - `conflict`: the agent holds a server of the name that differs; the +/// `reason` says why the library's cannot replace it, when it cannot. +/// - `unsupported`: the agent holds none and the library's cannot be put: +/// no file for servers (`agentLibrary.noTarget`), or [`Blocked`]. +/// - `off`: the agent holds none and a put would write it. +pub(super) fn state( + server: &Server, + support: &McpServerSupport, + snapshot: &Snapshot, +) -> (&'static str, Option) { + let unkept = server.unkept(support); + let plan = Plan::of(server, support); + let copies: Vec<&AgentServer> = snapshot + .mcp_servers + .iter() + .filter(|copy| copy.name == server.name) + .collect(); + let held = !copies.is_empty(); + let holds = plan + .as_ref() + .is_ok_and(|plan| copies.iter().any(|copy| plan.holds(copy))); + let (state, reason) = match &plan { + Ok(_) if holds => ("on", None), + Ok(_) if held => ("conflict", None), + Err(blocked) if held => ("conflict", Some(blocked.code())), + _ if snapshot.targets.mcp_servers.is_none() => { + ("unsupported", Some("agentLibrary.noTarget")) + } + Ok(_) => ("off", None), + Err(blocked) => ("unsupported", Some(blocked.code())), + }; + let mut details = serde_json::Map::new(); + if let Some(reason) = reason { + details.insert("reason".into(), json!(reason)); + } + if !unkept.is_empty() { + details.insert("unsupportedFields".into(), json!(unkept)); + } + (state, (!details.is_empty()).then(|| Value::Object(details))) +} + +/// How fit a copy is for an import, lowest first: every value known and the +/// user's own configuration, then every value known, then the user's own. +/// An import from an agent takes its fittest copy of the name. +pub(super) fn import_rank(copy: &AgentServer) -> u8 { + match (copy.values_known(), copy.origin == Origin::User) { + (true, true) => 0, + (true, false) => 1, + (false, true) => 2, + (false, false) => 3, + } +} diff --git a/rust/crates/agent-runtime/src/live.rs b/rust/crates/agent-runtime/src/live.rs index 19b80fb8..e67ced1a 100644 --- a/rust/crates/agent-runtime/src/live.rs +++ b/rust/crates/agent-runtime/src/live.rs @@ -1085,7 +1085,7 @@ fn sniffed_image_type(path: &Path) -> Option<&'static str> { } /// The type an image's first bytes name, if Core knows it. -fn image_type(head: &[u8]) -> Option<&'static str> { +pub(crate) fn image_type(head: &[u8]) -> Option<&'static str> { if head.starts_with(b"\x89PNG\r\n\x1a\n") { Some("image/png") } else if head.starts_with(&[0xFF, 0xD8, 0xFF]) { diff --git a/rust/crates/agent-runtime/src/tests/library.rs b/rust/crates/agent-runtime/src/tests/library.rs index 89ed48d2..b7c0d4f6 100644 --- a/rust/crates/agent-runtime/src/tests/library.rs +++ b/rust/crates/agent-runtime/src/tests/library.rs @@ -1,5 +1,7 @@ //! The agent library: saving with revisions, MCP servers and hooks through a -//! staged copy the synthetic plugin edits, instructions, skills and grants. +//! staged copy the synthetic plugin edits, instructions, skills and grants; +//! the `servers` tests cover server fields, values, imports, found groups +//! and pasted text. use super::*; @@ -54,6 +56,8 @@ fn configuration_read(params: &Value) -> Result { .and_then(|files| files.iter().find(|file| file["id"] == "main")) .ok_or_else(|| failure("plugin.params.invalid"))?; let config = read_file(Path::new(file["path"].as_str().unwrap())); + // `extraServers` lists servers as reported, for a second server of a + // name, which the map cannot hold. let servers: Vec = config["servers"] .as_object() .map(|servers| { @@ -67,9 +71,17 @@ fn configuration_read(params: &Value) -> Result { } row }) - .collect() + .collect::>() }) - .unwrap_or_default(); + .unwrap_or_default() + .into_iter() + .chain( + config["extraServers"] + .as_array() + .cloned() + .unwrap_or_default(), + ) + .collect(); let hooks: Vec = config["hooks"] .as_array() .cloned() @@ -719,6 +731,18 @@ fn malformed_requests_and_a_damaged_library_file_are_refused_each_with_its_own_c .refused("agentLibrary.removeSkill", json!({ "name": "absent" })), "agentLibrary.unknownItem" ); + // A library Core could not read back is never written. + let sets: Vec = (0..33) + .map(|index| json!({ "id": format!("s{index}"), "name": "S", "text": "x".repeat(256 * 1024) })) + .collect(); + assert_eq!( + test.harness.refused( + "agentLibrary.save", + json!({ "revision": "empty", "library": { "instructions": { "sets": sets } } }), + ), + "agentLibrary.libraryTooLarge" + ); + assert!(!test.library.join("library.json").exists()); fs::create_dir_all(&test.library).unwrap(); fs::write( test.library.join("library.json"), @@ -733,3 +757,4 @@ fn malformed_requests_and_a_damaged_library_file_are_refused_each_with_its_own_c mod backups; mod instructions; +mod servers; diff --git a/rust/crates/agent-runtime/src/tests/library/servers.rs b/rust/crates/agent-runtime/src/tests/library/servers.rs new file mode 100644 index 00000000..088f4aa2 --- /dev/null +++ b/rust/crates/agent-runtime/src/tests/library/servers.rs @@ -0,0 +1,909 @@ +//! MCP servers of the library: the fields an agent plugin declares it keeps, +//! the values of environment variables and headers, imports from an agent, +//! the groups of items agents hold outside the library, pasted text, and a +//! `library.json` written before these fields. + +use super::*; + +/// Synthetic values; a test fails if one shows up where values never go. +const SECRET: &str = "test-value-not-real-5c1e"; +const HEADER_SECRET: &str = "Bearer test-value-not-real-9d2b"; +/// The first bytes of a PNG file, in Base64. +const PNG: &str = "iVBORw0KGgoAAAANSUhEUg=="; +const OTHER_KEY: &str = "dev.lithe.test.agents/other"; + +/// The configuration plugin with `declaration` as its agent's +/// `configuration.mcpServers`. +fn declared(declaration: Value) -> Value { + let mut manifest = configuration_manifest(); + manifest["agents"][0]["configuration"]["mcpServers"] = declaration; + manifest +} + +/// The `server` of the plugin's last `edit`. +fn last_edit(test: &LibraryTest) -> Value { + test.harness + .link + .calls_of("configuration.edit") + .last() + .expect("an edit")["change"]["server"] + .clone() +} + +fn server_state(read: &Value, name: &str) -> (Value, Value) { + ( + read["states"]["mcpServers"][name][AGENT_KEY].clone(), + read["stateDetails"]["mcpServers"][name][AGENT_KEY].clone(), + ) +} + +fn put(name: &str) -> Value { + json!({ "category": "mcpServers", "op": "put", "name": name }) +} + +fn assert_no_values(text: &str, place: &str) { + assert!( + !text.contains(SECRET) && !text.contains("test-value-not-real-9d2b"), + "{place} carries no value" + ); +} + +#[test] +fn declared_fields_are_written_and_the_others_reported_unsupported() { + let fields = json!(["environment", "enabled", "disabledTools"]); + let test = LibraryTest::with_manifest( + "library server fields", + CONFIGURATION_GRANTS, + declared(json!({ "transports": ["stdio", "http"], "fields": fields })), + ); + let read = test.read(); + assert_eq!(read["directory"], path_text(&test.library)); + assert_eq!( + read["agents"][0]["mcpServerSupport"], + json!({ "transports": ["stdio", "http"], "fields": fields }) + ); + test.save(library_with( + json!([ + { + "name": "docs", "transport": "stdio", "command": "docs-mcp", + "environment": [{ "name": "DOCS_TOKEN", "value": SECRET }], + "note": "Team docs", "icon": { "type": "image/png", "data": PNG }, + "disabledTools": ["delete_page"], + "startupTimeoutSeconds": 20, "callTimeoutSeconds": 60 + }, + { "name": "events", "transport": "sse", "url": "https://events.example.test/sse" }, + { + "name": "remote", "transport": "http", "url": "https://remote.example.test/mcp", + "headers": [{ "name": "Authorization", "value": HEADER_SECRET }] + } + ]), + json!([]), + )); + let read = test.read(); + assert_eq!( + server_state(&read, "docs"), + ( + json!("off"), + json!({ "unsupportedFields": ["startupTimeout", "callTimeout"] }) + ) + ); + assert_eq!( + server_state(&read, "events"), + ( + json!("unsupported"), + json!({ "reason": "agentLibrary.transportUnsupported" }) + ) + ); + assert_eq!( + server_state(&read, "remote"), + ( + json!("unsupported"), + json!({ "reason": "agentLibrary.fieldUnsupported", "unsupportedFields": ["headers"] }) + ), + "a server whose headers the agent cannot keep would not authenticate" + ); + + assert!(test.apply(put("docs"))); + assert_eq!( + last_edit(&test), + json!({ + "name": "docs", "transport": "stdio", "command": "docs-mcp", + "environment": [{ "name": "DOCS_TOKEN", "value": SECRET }], + "enabled": true, "disabledTools": ["delete_page"] + }), + "the note, the icon and the timeouts the agent does not keep stay in the library" + ); + assert_eq!(server_state(&test.read(), "docs").0, "on"); + assert_eq!( + test.refused_change(put("events")), + "agentLibrary.transportUnsupported" + ); + assert_eq!( + test.refused_change(put("remote")), + "agentLibrary.fieldUnsupported" + ); + + // Switched off, the server is written switched off into an agent that + // keeps the switch. + let mut library = test.read()["library"].clone(); + library["mcpServers"][0]["enabled"] = json!(false); + test.save(library); + assert_eq!(server_state(&test.read(), "docs").0, "conflict"); + assert!(test.apply(put("docs"))); + assert_eq!( + read_file(&test.config_file())["servers"]["docs"]["enabled"], + false + ); + assert_eq!(server_state(&test.read(), "docs").0, "on"); +} + +#[test] +fn an_agent_that_keeps_no_switch_gets_no_switched_off_server() { + let test = LibraryTest::new("library server switch", CONFIGURATION_GRANTS); + assert_eq!( + test.read()["agents"][0]["mcpServerSupport"], + json!({ "transports": ["stdio", "http", "sse"], "fields": [] }), + "a plugin that declares nothing takes every transport and keeps no further field" + ); + test.save(library_with( + json!([ + { + "name": "docs", "transport": "stdio", "command": "docs-mcp", + "disabledTools": ["delete_page"], "callTimeoutSeconds": 30 + }, + { + "name": "paused", "transport": "stdio", "command": "paused-mcp", + "enabled": false, "pausedAgents": [AGENT_KEY] + }, + { + "name": "secret", "transport": "stdio", "command": "secret-mcp", + "environment": [{ "name": "TOKEN", "value": SECRET }] + } + ]), + json!([]), + )); + assert!(test.apply(put("docs"))); + assert_eq!( + last_edit(&test), + json!({ "name": "docs", "transport": "stdio", "command": "docs-mcp" }) + ); + assert_eq!( + server_state(&test.read(), "docs"), + ( + json!("on"), + json!({ "unsupportedFields": ["disabledTools", "callTimeout"] }) + ), + "fields the agent does not keep are not compared" + ); + let read = test.read(); + assert_eq!( + server_state(&read, "paused"), + ( + json!("unsupported"), + json!({ "reason": "agentLibrary.serverOff", "unsupportedFields": ["enabled"] }) + ) + ); + assert_eq!( + server_state(&read, "secret").1["reason"], + "agentLibrary.fieldUnsupported" + ); + assert_eq!(test.refused_change(put("paused")), "agentLibrary.serverOff"); + + // Switching off a server the agent holds: the host takes it out. + let mut library = read["library"].clone(); + library["mcpServers"][0]["enabled"] = json!(false); + library["mcpServers"][0]["pausedAgents"] = json!([AGENT_KEY]); + test.save(library.clone()); + assert_eq!( + server_state(&test.read(), "docs"), + ( + json!("conflict"), + json!({ + "reason": "agentLibrary.serverOff", + "unsupportedFields": ["enabled", "disabledTools", "callTimeout"] + }) + ) + ); + assert!(test.apply(json!({ "category": "mcpServers", "op": "remove", "name": "docs" }))); + assert_eq!(server_state(&test.read(), "docs").0, "unsupported"); + library["mcpServers"][0]["enabled"] = json!(true); + library["mcpServers"][0] + .as_object_mut() + .unwrap() + .remove("pausedAgents"); + test.save(library.clone()); + assert!(test.apply(put("docs"))); + assert_eq!(server_state(&test.read(), "docs").0, "on"); + + let invalid = |change: &dyn Fn(&mut Value)| { + let mut library = library.clone(); + change(&mut library["mcpServers"][0]); + let revision = test.read()["revision"].clone(); + test.harness.refused( + "agentLibrary.save", + json!({ "revision": revision, "library": library }), + ) + }; + for (change, why) in [ + ( + &(|server: &mut Value| server["pausedAgents"] = json!([AGENT_KEY])) + as &dyn Fn(&mut Value), + "only a server switched off has paused agents", + ), + ( + &|server: &mut Value| server["icon"] = json!({ "type": "image/jpeg", "data": PNG }), + "an icon is the type it says", + ), + ( + &|server: &mut Value| server["note"] = json!("n".repeat(1025)), + "a note is at most 1024 characters", + ), + ( + &|server: &mut Value| server["startupTimeoutSeconds"] = json!(0), + "a timeout is at least a second", + ), + ( + &|server: &mut Value| server["disabledTools"] = json!(["a", "a"]), + "a tool is left out once", + ), + ( + &|server: &mut Value| server["headers"] = json!([{ "name": "X", "value": "x" }]), + "a stdio server has no headers", + ), + ] { + assert_eq!(invalid(change), "agentLibrary.invalidLibrary", "{why}"); + } +} + +#[test] +fn values_are_kept_by_saves_and_never_answered_or_logged() { + let test = LibraryTest::with_manifest( + "library server values", + CONFIGURATION_GRANTS, + declared(json!({ "fields": ["environment", "headers"] })), + ); + let ((), logs) = capture::run(false, || { + test.save(library_with( + json!([ + { + "name": "docs", "transport": "stdio", "command": "docs-mcp", + "environment": [{ "name": "DOCS_TOKEN", "value": SECRET }] + }, + { + "name": "remote", "transport": "http", "url": "https://remote.example.test/mcp", + "headers": [{ "name": "Authorization", "value": HEADER_SECRET }] + } + ]), + json!([]), + )); + let read = test.read(); + assert_no_values(&read.to_string(), "a read"); + assert_eq!( + read["library"]["mcpServers"][0]["environment"], + json!([{ "name": "DOCS_TOKEN", "valueSet": true }]) + ); + + // A save of what was read keeps each value; a renamed server names + // the name it had. + let mut library = read["library"].clone(); + library["mcpServers"][0]["name"] = json!("docs-renamed"); + library["mcpServers"][0]["renamedFrom"] = json!("docs"); + library["mcpServers"][0]["environment"] + .as_array_mut() + .unwrap() + .push(json!({ "name": "EMPTY" })); + test.save(library.clone()); + let read = test.read(); + assert_eq!( + read["library"]["mcpServers"][0]["environment"], + json!([{ "name": "DOCS_TOKEN", "valueSet": true }, { "name": "EMPTY", "valueSet": false }]) + ); + assert!(read["library"]["mcpServers"][0] + .get("renamedFrom") + .is_none()); + assert_eq!( + test.refused_change(put("docs-renamed")), + "agentLibrary.valueMissing" + ); + assert_eq!( + server_state(&read, "docs-renamed"), + ( + json!("unsupported"), + json!({ "reason": "agentLibrary.valueMissing" }) + ) + ); + let mut library = read["library"].clone(); + library["mcpServers"][0]["environment"] + .as_array_mut() + .unwrap() + .pop(); + test.save(library); + assert!(test.apply(put("docs-renamed"))); + assert_eq!( + last_edit(&test)["environment"], + json!([{ "name": "DOCS_TOKEN", "value": SECRET }]) + ); + assert!(test.apply(put("remote"))); + assert_eq!( + last_edit(&test)["headers"], + json!([{ "name": "Authorization", "value": HEADER_SECRET }]) + ); + let read = test.read(); + assert_eq!(server_state(&read, "docs-renamed").0, "on"); + assert_eq!(server_state(&read, "remote").0, "on"); + assert_eq!( + read["agents"][0]["mcpServers"][0]["environment"], + json!([{ "name": "DOCS_TOKEN", "valueSet": true }]) + ); + assert_no_values(&read.to_string(), "a read of an agent holding values"); + + // Refusals never quote a value, whatever the decoder would say. + let revision = read["revision"].clone(); + for server in [ + json!({ + "name": "x", "transport": "stdio", "command": "x", + "environment": [{ "name": "T", "value": SECRET }], + "startupTimeoutSeconds": SECRET + }), + json!({ + "name": "x", "transport": "http", "url": "https://x.example.test/mcp", + "headers": [{ "name": "X", "value": format!("line\n{HEADER_SECRET}") }] + }), + ] { + let refusal = test + .harness + .runtime + .execute( + "agentLibrary.save", + json!({ "revision": revision, "library": { "mcpServers": [server] } }), + ) + .unwrap_err(); + assert_no_values(&format!("{refusal:?}"), "a refusal"); + } + let pasted = test + .harness + .runtime + .execute( + "agentLibrary.parseServers", + json!({ "text": 5, "secret": SECRET }), + ) + .unwrap_err(); + assert_no_values(&format!("{pasted:?}"), "a refused paste"); + }); + assert!(logs + .iter() + .any(|log| log.event == "agent.library.change_applied")); + assert_no_values(&format!("{logs:?}"), "the log"); + + let file = test.library.join("library.json"); + let stored = fs::read_to_string(&file).unwrap(); + assert!( + stored.contains(SECRET) && stored.contains(HEADER_SECRET), + "the library keeps the values" + ); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = |path: &Path| fs::metadata(path).unwrap().permissions().mode(); + assert_eq!(mode(&file) & 0o077, 0, "the file is the owner's only"); + assert_eq!(mode(&test.library) & 0o077, 0, "so is its directory"); + } +} + +#[test] +fn an_agent_server_is_imported_with_its_values() { + let test = LibraryTest::with_manifest( + "library server import", + CONFIGURATION_GRANTS, + declared(json!({ "fields": ["environment", "headers"] })), + ); + fs::write( + test.config_file(), + serde_json::to_vec(&json!({ "servers": { + "gh": { + "transport": "stdio", "command": "gh-mcp", + "environment": [{ "name": "GH_TOKEN", "value": SECRET }], + "disabledTools": ["delete_repo"] + }, + "names-only": { "transport": "stdio", "command": "names-mcp", "environmentNames": ["API_KEY"] }, + "zero": { "transport": "stdio", "command": "zero-mcp", "startupTimeoutSeconds": 0 }, + "plugin-tools": { + "transport": "http", "url": "https://tools.example.test/mcp", + "origin": "agent", "provider": "sample-plugin" + } + }})) + .unwrap(), + ) + .unwrap(); + let read = test.read(); + assert_no_values(&read.to_string(), "a read"); + let rows = &read["agents"][0]["mcpServers"]; + assert_eq!( + rows[0]["environment"], + json!([{ "name": "GH_TOKEN", "valueSet": true }]) + ); + assert_eq!( + rows[1]["environment"], + json!([{ "name": "API_KEY", "valueSet": false }]), + "a plugin may still report names alone" + ); + let found = &read["found"]["mcpServers"]; + assert_eq!( + found[0], + json!({ + "name": "gh", + "copies": [{ "agent": AGENT_KEY, "index": 0, "variant": 0 }], + "variants": 1, "inLibrary": false, "importable": true, "importFrom": AGENT_KEY + }) + ); + assert_eq!(found[1]["valuesMissing"], true); + assert_eq!( + (found[2]["importable"].clone(), found[2]["reason"].clone()), + (json!(false), json!("agentLibrary.invalidLibrary")) + ); + assert_eq!( + found[3]["importFrom"], AGENT_KEY, + "what a CLI installed may be imported too" + ); + + let import = |name: &str, revision: &Value| json!({ "category": "mcpServers", "op": "import", "name": name, "revision": revision }); + let answer = test.harness.run( + "agentLibrary.apply", + json!({ "agent": AGENT_KEY, "change": import("gh", &read["revision"]) }), + ); + assert_eq!(answer["changed"], true); + let read = test.read(); + assert_eq!(answer["revision"], read["revision"]); + assert_eq!( + read["library"]["mcpServers"], + json!([{ + "name": "gh", "transport": "stdio", "command": "gh-mcp", + "environment": [{ "name": "GH_TOKEN", "valueSet": true }], + "disabledTools": ["delete_repo"] + }]) + ); + assert!(fs::read_to_string(test.library.join("library.json")) + .unwrap() + .contains(SECRET)); + assert_eq!( + server_state(&read, "gh"), + ( + json!("on"), + json!({ "unsupportedFields": ["disabledTools"] }) + ) + ); + assert!(read["found"]["mcpServers"] + .as_array() + .unwrap() + .iter() + .all(|group| group["name"] != "gh")); + assert!(test.harness.link.calls_of("configuration.edit").is_empty()); + + let revision = read["revision"].clone(); + assert_eq!( + test.refused_change(import("gh", &revision)), + "agentLibrary.serverExists" + ); + assert_eq!( + test.refused_change(import("absent", &revision)), + "agentLibrary.notInAgent" + ); + assert_eq!( + test.refused_change(import("zero", &revision)), + "agentLibrary.invalidLibrary" + ); + assert_eq!( + test.refused_change(import("names-only", &json!("stale"))), + "agentLibrary.revisionChanged" + ); + assert_eq!( + test.refused_change( + json!({ "category": "mcpServers", "op": "import", "name": "names-only" }) + ), + "agentLibrary.invalidChange" + ); + assert!(test.apply(import("names-only", &revision))); + assert_eq!( + server_state(&test.read(), "names-only"), + ( + json!("conflict"), + json!({ "reason": "agentLibrary.valueMissing" }) + ), + "the user gives the value before the library's server can replace the agent's" + ); + + let full: Vec = (0..256) + .map(|index| json!({ "name": format!("s{index}"), "transport": "stdio", "command": "s" })) + .collect(); + test.save(library_with(json!(full), json!([]))); + let read = test.read(); + assert_eq!( + read["found"]["mcpServers"][0]["reason"], + "agentLibrary.libraryFull" + ); + assert_eq!( + test.refused_change(import("gh", &read["revision"])), + "agentLibrary.libraryFull" + ); + + fs::write( + test.config_file(), + br#"{"servers":{"both":{"transport":"stdio","command":"x","environment":[{"name":"A"}],"environmentNames":["B"]}}}"#, + ) + .unwrap(); + assert_eq!( + test.read()["agents"][0]["readError"], + "agentLibrary.invalidSnapshot", + "variables come as one list or the other" + ); +} + +/// The configuration plugin with a second agent, `other`, whose files are +/// under `~/.other`. +fn two_agents() -> Value { + let mut manifest = declared(json!({ "fields": ["environment"] })); + let mut other = manifest["agents"][0].clone(); + other["id"] = json!("other"); + other["displayName"] = json!("Other Agent"); + other.as_object_mut().unwrap().remove("sessionSources"); + other["configuration"] = json!({ + "skills": { "roots": ["${userHome}/.other/skills"] }, + "files": [{ "id": "main", "roots": ["${userHome}/.other/config.json"] }], + "read": "configuration.read", + "edit": "configuration.edit", + "mcpServers": { "fields": ["environment"] } + }); + manifest["agents"].as_array_mut().unwrap().push(other); + manifest["activationEvents"] + .as_array_mut() + .unwrap() + .push(json!("onAgent:other")); + manifest +} + +fn write_skill(directory: &Path, text: &str) { + fs::create_dir_all(directory).unwrap(); + fs::write(directory.join("SKILL.md"), text).unwrap(); +} + +#[test] +fn items_outside_the_library_are_grouped_with_their_differences() { + let test = LibraryTest::with_manifest("library found", CONFIGURATION_GRANTS, two_agents()); + let other = test.home.join(".other"); + fs::create_dir_all(&other).unwrap(); + fs::write( + test.config_file(), + serde_json::to_vec(&json!({ + "servers": { "shared": { "transport": "stdio", "command": "shared-mcp", "args": ["--a"] } }, + "extraServers": [{ + "name": "shared", "transport": "stdio", "command": "shared-mcp", "args": ["--b"], + "origin": "agent", "provider": "sample-plugin" + }], + "hooks": [{ "event": "Stop", "command": "notify" }] + })) + .unwrap(), + ) + .unwrap(); + fs::write( + other.join("config.json"), + serde_json::to_vec(&json!({ + "servers": { + "shared": { "transport": "stdio", "command": "shared-mcp", "args": ["--a"] }, + "kept": { "transport": "stdio", "command": "agent-kept" } + }, + "hooks": [ + { "event": "Stop", "command": "notify" }, + { "event": "PreToolUse", "command": "guard", "matcher": "Write" } + ] + })) + .unwrap(), + ) + .unwrap(); + test.save(library_with( + json!([{ "name": "kept", "transport": "stdio", "command": "library-kept" }]), + json!([]), + )); + let source = test.harness.dir.path().join("source").join("lint"); + write_skill(&source, "---\nname: lint\n---\nLibrary lint\n"); + test.harness.run( + "agentLibrary.importSkill", + json!({ "directory": path_text(&source) }), + ); + let sample_skills = test.home.join(".sample").join("skills"); + let other_skills = other.join("skills"); + write_skill( + &sample_skills.join("lint"), + "---\nname: lint\n---\nLibrary lint\n", + ); + write_skill( + &other_skills.join("lint"), + "---\nname: lint\n---\nOther lint\n", + ); + write_skill(&sample_skills.join("review"), "---\nname: review\n---\nA\n"); + write_skill(&other_skills.join("review"), "---\nname: review\n---\nB\n"); + + // Agents come in the catalog's order, `other` before `sample`. + let found = test.read()["found"].clone(); + assert_eq!( + found["mcpServers"], + json!([ + { + "name": "shared", + "copies": [ + { "agent": OTHER_KEY, "index": 0, "variant": 0 }, + { "agent": AGENT_KEY, "index": 0, "variant": 0 }, + { "agent": AGENT_KEY, "index": 1, "variant": 1 } + ], + "variants": 2, "inLibrary": false, "importable": true, "importFrom": OTHER_KEY + }, + { + "name": "kept", + "copies": [{ "agent": OTHER_KEY, "index": 1, "variant": 0, "differsFromLibrary": true }], + "variants": 1, "inLibrary": true, "importable": false, + "reason": "agentLibrary.serverExists" + } + ]) + ); + assert_eq!( + found["hooks"], + json!([ + { + "event": "Stop", "command": "notify", + "copies": [{ "agent": OTHER_KEY, "index": 0 }, { "agent": AGENT_KEY, "index": 0 }], + "importable": true + }, + { + "event": "PreToolUse", "command": "guard", "matcher": "Write", + "copies": [{ "agent": OTHER_KEY, "index": 1 }], + "importable": true + } + ]) + ); + let skill = |name: &str| { + found["skills"] + .as_array() + .unwrap() + .iter() + .find(|group| group["name"] == name) + .unwrap_or_else(|| panic!("a group for {name}")) + .clone() + }; + let without_index = |group: &Value| -> Vec { + group["copies"] + .as_array() + .unwrap() + .iter() + .map(|copy| { + let mut copy = copy.clone(); + copy.as_object_mut().unwrap().remove("index"); + copy + }) + .collect() + }; + let lint = skill("lint"); + assert_eq!( + without_index(&lint), + vec![ + json!({ "agent": OTHER_KEY, "source": "skills", "variant": 0, "differsFromLibrary": true }), + json!({ "agent": AGENT_KEY, "source": "skills", "variant": 1, "differsFromLibrary": false }) + ] + ); + assert_eq!( + (lint["inLibrary"].clone(), lint["reason"].clone()), + (json!(true), json!("agentLibrary.skillExists")) + ); + let review = skill("review"); + assert_eq!(review["variants"], 2); + assert_eq!(review["importFrom"], OTHER_KEY); + let provided = skill("provided-skill"); + assert_eq!( + without_index(&provided), + vec![ + json!({ "agent": OTHER_KEY, "source": "providedSkills", "variant": 0 }), + json!({ "agent": AGENT_KEY, "source": "providedSkills", "variant": 0 }) + ] + ); + assert_eq!(provided["reason"], "agentLibrary.notOwnSkill"); +} + +#[test] +fn pasted_text_reads_in_the_common_shapes() { + let test = LibraryTest::new("library paste", CONFIGURATION_GRANTS); + let parse = |text: &str| { + test.harness + .run("agentLibrary.parseServers", json!({ "text": text })) + }; + let pasted = parse(&format!( + r#"{{ + // Servers of a desktop client. + "mcpServers": {{ + "github": {{ "command": "npx", "args": ["-y", "github-mcp"], "env": {{ "GITHUB_TOKEN": "{SECRET}", "PORT": 8080 }}, }}, + /* A remote one. */ + "remote": {{ "type": "http", "url": "https://remote.example.test/mcp", "headers": {{ "Authorization": "{HEADER_SECRET}" }} }}, + "events": {{ "url": "https://events.example.test/sse?x=1" }}, + "off": {{ "command": "off-mcp", "disabled": true, "disabledTools": ["write"] }}, + }}, +}}"# + )); + assert_eq!( + pasted, + json!({ + "servers": [ + { + "name": "github", "transport": "stdio", "command": "npx", "args": ["-y", "github-mcp"], + "environment": [{ "name": "GITHUB_TOKEN", "value": SECRET }, { "name": "PORT", "value": "8080" }] + }, + { + "name": "remote", "transport": "http", "url": "https://remote.example.test/mcp", + "headers": [{ "name": "Authorization", "value": HEADER_SECRET }] + }, + { "name": "events", "transport": "sse", "url": "https://events.example.test/sse?x=1" }, + { "name": "off", "transport": "stdio", "command": "off-mcp", "enabled": false, "disabledTools": ["write"] } + ], + "problems": [] + }) + ); + let shapes = [ + ( + r#"{"servers": {"fs": {"type": "stdio", "command": "fs-mcp"}}}"#, + json!([{ "name": "fs", "transport": "stdio", "command": "fs-mcp" }]), + ), + ( + r#"{"context_servers": {"z": {"command": {"path": "z-mcp", "args": ["--x"], "env": {"A": "1"}}}}}"#, + json!([{ + "name": "z", "transport": "stdio", "command": "z-mcp", "args": ["--x"], + "environment": [{ "name": "A", "value": "1" }] + }]), + ), + ( + r#"{"mcp": {"local": {"type": "local", "command": ["l-mcp", "--y"], "environment": {"B": true}, "enabled": false}, + "far": {"type": "remote", "url": "https://far.example.test/mcp"}}}"#, + json!([ + { + "name": "local", "transport": "stdio", "command": "l-mcp", "args": ["--y"], + "environment": [{ "name": "B", "value": "true" }], "enabled": false + }, + { "name": "far", "transport": "http", "url": "https://far.example.test/mcp" } + ]), + ), + ( + r#"{"mcp": {"servers": {"v": {"url": "https://v.example.test/mcp"}}}}"#, + json!([{ "name": "v", "transport": "http", "url": "https://v.example.test/mcp" }]), + ), + ( + r#"{"mcpServers": {"g": {"httpUrl": "https://g.example.test/sse", "excludeTools": ["t"], "startup_timeout_sec": 9}}}"#, + json!([{ + "name": "g", "transport": "http", "url": "https://g.example.test/sse", + "disabledTools": ["t"], "startupTimeoutSeconds": 9 + }]), + ), + ( + r#"{"command": "solo-mcp", "description": "One server"}"#, + json!([{ "transport": "stdio", "command": "solo-mcp", "note": "One server" }]), + ), + ( + "\"frag\": {\"command\": \"frag-mcp\"},", + json!([{ "name": "frag", "transport": "stdio", "command": "frag-mcp" }]), + ), + ( + r#"{"ws": {"serverUrl": "https://ws.example.test/mcp"}}"#, + json!([{ "name": "ws", "transport": "http", "url": "https://ws.example.test/mcp" }]), + ), + ]; + for (text, servers) in shapes { + assert_eq!( + parse(text), + json!({ "servers": servers, "problems": [] }), + "{text}" + ); + } + + assert_eq!( + parse( + r#"{"mcpServers": {"bad": {"args": []}, "neg": {"command": "x", "startupTimeoutSeconds": -1}, + " pad": {"command": "x"}, "a/b": 5, "web": {"url": "ftp://x"}}}"# + ), + json!({ + "servers": [], + "problems": [ + { "reason": "noCommandOrUrl", "path": "/mcpServers/bad" }, + { "reason": "invalidField", "path": "/mcpServers/neg", "field": "startupTimeoutSeconds" }, + { "reason": "invalidName", "path": "/mcpServers/ pad" }, + { "reason": "noCommandOrUrl", "path": "/mcpServers/a~1b" }, + { "reason": "invalidField", "path": "/mcpServers/web", "field": "url" } + ] + }) + ); + assert_eq!( + parse( + r#"[{"name": "a", "command": "a"}, {"name": "a", "command": "b"}, {"command": "c"}]"# + ), + json!({ + "servers": [ + { "name": "a", "transport": "stdio", "command": "a" }, + { "transport": "stdio", "command": "c" } + ], + "problems": [{ "reason": "duplicateName", "path": "/1" }] + }) + ); + // The column counts characters: `é` is one, though two bytes. + assert_eq!( + parse("{\n /* é */ \"mcpServers\": {\n \"x\": { \"command\": \"é\" \"y\" }\n }\n}") + ["problems"], + json!([{ "reason": "syntax", "line": 3, "column": 27 }]) + ); + assert_eq!( + parse("{\"mcpServers\": {")["problems"], + json!([{ "reason": "end", "line": 1, "column": 16 }]) + ); + assert_eq!( + parse(r#"{"theme": "dark"}"#), + json!({ "servers": [], "problems": [{ "reason": "noServers" }] }) + ); + let many: serde_json::Map = (0..257) + .map(|index| (format!("s{index}"), json!({ "command": "s" }))) + .collect(); + let answer = parse(&json!({ "mcpServers": many }).to_string()); + assert_eq!(answer["servers"].as_array().unwrap().len(), 256); + assert_eq!(answer["problems"], json!([{ "reason": "tooMany" }])); + assert_eq!( + test.harness.refused( + "agentLibrary.parseServers", + json!({ "text": " ".repeat(256 * 1024 + 1) }), + ), + "agentLibrary.textTooLarge" + ); + assert!( + !test.library.join("library.json").exists(), + "parsing saves nothing" + ); +} + +#[test] +fn a_library_file_from_before_the_new_fields_reads_and_saves_owner_only() { + let test = LibraryTest::new("library upgrade", CONFIGURATION_GRANTS); + fs::create_dir_all(&test.library).unwrap(); + let file = test.library.join("library.json"); + let servers = json!([ + { "name": "docs", "transport": "stdio", "command": "docs-mcp", "args": ["--stdio"] }, + { "name": "web", "transport": "http", "url": "https://web.example.test/mcp" } + ]); + fs::write( + &file, + serde_json::to_vec( + &json!({ "version": 0, "library": { "mcpServers": servers, "hooks": [] } }), + ) + .unwrap(), + ) + .unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(&file, fs::Permissions::from_mode(0o644)).unwrap(); + } + let read = test.read(); + assert_eq!(read["library"]["mcpServers"], servers); + assert_eq!(server_state(&read, "docs").0, "off"); + test.save(read["library"].clone()); + assert_eq!(test.read()["library"]["mcpServers"], servers); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + assert_eq!( + fs::metadata(&file).unwrap().permissions().mode() & 0o077, + 0, + "the first save makes the file the owner's only" + ); + } + + fs::write( + &file, + br#"{"version":0,"library":{"mcpServers":[{"name":"docs","transport":"stdio","command":"x","renamedFrom":"old"}]}}"#, + ) + .unwrap(); + assert_eq!( + test.harness.refused("agentLibrary.read", json!({})), + "agentLibrary.invalidLibraryFile", + "only a save names a server's old name" + ); +} diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 45cc3444..1339aeac 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -280,6 +280,9 @@ pub enum AgentsCommand { LibraryRead, /// Saves the library if it is unchanged since it was read (`agentLibrary.save`). LibrarySave, + /// Reads the MCP servers a pasted text describes, without saving them + /// (`agentLibrary.parseServers`). + LibraryParseServers, /// Applies one library change to one agent's configuration (`agentLibrary.apply`). LibraryApply, /// Copies a skill into the library (`agentLibrary.importSkill`). @@ -334,6 +337,7 @@ impl AgentsCommand { Self::LibraryConfigure => "agentLibrary.configure", Self::LibraryRead => "agentLibrary.read", Self::LibrarySave => "agentLibrary.save", + Self::LibraryParseServers => "agentLibrary.parseServers", Self::LibraryApply => "agentLibrary.apply", Self::LibraryImportSkill => "agentLibrary.importSkill", Self::LibraryRemoveSkill => "agentLibrary.removeSkill", @@ -1363,6 +1367,7 @@ impl CoreCommand { "agentLibrary.configure" => Some(Self::Agents(AgentsCommand::LibraryConfigure)), "agentLibrary.read" => Some(Self::Agents(AgentsCommand::LibraryRead)), "agentLibrary.save" => Some(Self::Agents(AgentsCommand::LibrarySave)), + "agentLibrary.parseServers" => Some(Self::Agents(AgentsCommand::LibraryParseServers)), "agentLibrary.apply" => Some(Self::Agents(AgentsCommand::LibraryApply)), "agentLibrary.importSkill" => Some(Self::Agents(AgentsCommand::LibraryImportSkill)), "agentLibrary.removeSkill" => Some(Self::Agents(AgentsCommand::LibraryRemoveSkill)), diff --git a/rust/crates/core/src/tests/declarative_plugins.rs b/rust/crates/core/src/tests/declarative_plugins.rs index e534f272..d2965391 100644 --- a/rust/crates/core/src/tests/declarative_plugins.rs +++ b/rust/crates/core/src/tests/declarative_plugins.rs @@ -323,7 +323,8 @@ fn agents_are_reviewed_programs() { "editable": true, "instructions": ["${env:EXAMPLE_HOME}/INSTRUCTIONS.md", "${userHome}/.example/INSTRUCTIONS.md"], "skills": ["${userHome}/.example/skills"], - "providers": {"operations": ["addProvider", "updateProvider", "removeProvider", "setModel", "setEffort", "setSpeed", "setModelMenu", "setProvider"]} + "providers": {"operations": ["addProvider", "updateProvider", "removeProvider", "setModel", "setEffort", "setSpeed", "setModelMenu", "setProvider"]}, + "mcpServers": {"transports": ["stdio", "http"], "fields": ["environment", "headers", "enabled", "disabledTools"]} }), json!({ "kind": "agentSessions", diff --git a/rust/crates/plugin-agents/src/lib.rs b/rust/crates/plugin-agents/src/lib.rs index d97356ab..db24fa87 100644 --- a/rust/crates/plugin-agents/src/lib.rs +++ b/rust/crates/plugin-agents/src/lib.rs @@ -26,6 +26,9 @@ //! applies a change, and only through a staged copy it checks first. //! `configuration.providers` names the backend functions that report and //! change the CLI's model, model providers and profiles in those files. +//! `configuration.mcpServers` says which transports the CLI's MCP servers +//! connect with and which further fields it keeps, so Core writes no +//! field the CLI does not read. //! //! Note: the decision is recorded in .agents/notes/proposed/architecture/2026-11-25-agent-native-cli-and-local-session-records.md @@ -108,6 +111,22 @@ pub const PROVIDER_OPERATIONS: [&str; 10] = [ "setProfile", ]; +/// The transports an MCP server connects with, in the order the contract +/// lists them. An agent that declares no `mcpServers.transports` takes all. +pub const MCP_TRANSPORTS: [&str; 3] = ["stdio", "http", "sse"]; + +/// The MCP server fields, beyond its name, transport, command, arguments and +/// URL, that a CLI can keep, in the order the contract lists them. Core +/// writes a field into an agent only when its plugin declares it. +pub const MCP_SERVER_FIELDS: [&str; 6] = [ + "environment", + "headers", + "enabled", + "disabledTools", + "startupTimeout", + "callTimeout", +]; + /// Template variable of the user's home directory in a session root. const USER_HOME_VARIABLE: &str = "${userHome}"; @@ -172,6 +191,61 @@ pub struct ConfigurationDeclaration { /// providers and profiles kept in `files`. #[serde(default, skip_serializing_if = "Option::is_none")] pub providers: Option, + /// What the CLI's MCP servers can hold, as `read` reports them and + /// `edit` writes them; see [`ConfigurationDeclaration::mcp_server_support`]. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub mcp_servers: Option, +} + +impl ConfigurationDeclaration { + /// What the CLI's MCP servers can hold. Without a declaration they take + /// every transport and none of [`MCP_SERVER_FIELDS`], which is all a + /// plugin written before the declaration reads and writes. + pub fn mcp_server_support(&self) -> McpServerSupport { + let declared = self.mcp_servers.as_ref(); + McpServerSupport { + transports: declared + .and_then(|declared| declared.transports.clone()) + .unwrap_or_else(|| MCP_TRANSPORTS.iter().map(|t| t.to_string()).collect()), + fields: declared.map_or_else(Vec::new, |declared| declared.fields.clone()), + } + } +} + +/// The transports and the fields of [`MCP_SERVER_FIELDS`] the CLI's MCP +/// servers take, as the manifest declares them. +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct McpServersDeclaration { + /// The transports of [`MCP_TRANSPORTS`] the CLI connects with, each once; + /// absent is all of them. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub transports: Option>, + /// The fields of [`MCP_SERVER_FIELDS`] the CLI keeps, each once. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub fields: Vec, +} + +/// What an agent's MCP servers take, with the declaration's defaults +/// applied. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct McpServerSupport { + /// The transports the CLI connects with. + pub transports: Vec, + /// The fields of [`MCP_SERVER_FIELDS`] the CLI keeps. + pub fields: Vec, +} + +impl McpServerSupport { + /// Whether the CLI connects with `transport`. + pub fn takes_transport(&self, transport: &str) -> bool { + self.transports.iter().any(|known| known == transport) + } + + /// Whether the CLI keeps `field`, one of [`MCP_SERVER_FIELDS`]. + pub fn keeps(&self, field: &str) -> bool { + self.fields.iter().any(|known| known == field) + } } /// The model and model providers of an agent, read and changed by backend @@ -729,6 +803,58 @@ fn check_configuration(configuration: &ConfigurationDeclaration, field: &str) -> if let Some(providers) = &configuration.providers { check_providers(providers, configuration, &format!("{field}.providers"))?; } + if let Some(servers) = &configuration.mcp_servers { + check_mcp_servers(servers, configuration, &format!("{field}.mcpServers"))?; + } + Ok(()) +} + +fn check_mcp_servers( + servers: &McpServersDeclaration, + configuration: &ConfigurationDeclaration, + field: &str, +) -> Validation<()> { + if configuration.read.is_none() { + return Err(invalid( + field, + "MCP server support describes the servers the read function reports.", + )); + } + if let Some(transports) = &servers.transports { + if transports.is_empty() { + return Err(invalid( + format!("{field}.transports"), + "A CLI takes at least one transport; leave transports out for all of them.", + )); + } + check_distinct_of( + transports, + &MCP_TRANSPORTS, + &format!("{field}.transports"), + "A transport is stdio, http or sse, listed once.", + )?; + } + check_distinct_of( + &servers.fields, + &MCP_SERVER_FIELDS, + &format!("{field}.fields"), + "A field is one of the contract's MCP server fields, listed once.", + ) +} + +/// Checks that every value of `values` is one of `known`, each once. +fn check_distinct_of( + values: &[String], + known: &[&str], + field: &str, + message: &str, +) -> Validation<()> { + let mut seen = BTreeSet::new(); + for (index, value) in values.iter().enumerate() { + if !known.contains(&value.as_str()) || !seen.insert(value.as_str()) { + return Err(invalid(format!("{field}[{index}]"), message)); + } + } Ok(()) } @@ -970,6 +1096,9 @@ pub fn catalog_entry(plugin_id: &str, agent: &AgentDeclaration) -> Value { if let Some(providers) = &configuration.providers { entry["configuration"]["providers"] = json!({ "operations": providers.operations }); } + if configuration.read.is_some() { + entry["configuration"]["mcpServers"] = json!(configuration.mcp_server_support()); + } } if let Some(icon) = &agent.icon { entry["icon"] = json!(icon); @@ -1061,6 +1190,9 @@ pub fn programs(agent: &AgentDeclaration) -> Vec { if let Some(providers) = &configuration.providers { program["providers"] = json!({ "operations": providers.operations }); } + if let Some(servers) = &configuration.mcp_servers { + program["mcpServers"] = json!(servers); + } programs.push(program); } programs diff --git a/rust/crates/plugin-agents/src/tests.rs b/rust/crates/plugin-agents/src/tests.rs index ad9e4b17..efd854bc 100644 --- a/rust/crates/plugin-agents/src/tests.rs +++ b/rust/crates/plugin-agents/src/tests.rs @@ -298,7 +298,13 @@ fn accepts_configuration_and_reports_it() { let entry = catalog_entry("dev.lithe.test.agents", &agents[0]); assert_eq!( entry["configuration"], - json!({ "instructions": true, "skills": true, "files": true, "editable": true }) + json!({ + "instructions": true, + "skills": true, + "files": true, + "editable": true, + "mcpServers": { "transports": ["stdio", "http", "sse"], "fields": [] } + }) ); assert!(entry["configuration"].get("read").is_none()); @@ -588,3 +594,88 @@ fn resume_arguments_name_the_session_and_reach_the_review() { ); } } + +#[test] +fn mcp_server_support_defaults_to_every_transport_and_no_field() { + let mut agents = [agent(configured())]; + check(&mut agents, true).expect("configuration validates"); + let configuration = agents[0].configuration.as_ref().unwrap(); + let support = configuration.mcp_server_support(); + assert_eq!(support.transports, ["stdio", "http", "sse"]); + assert!(support.fields.is_empty()); + assert_eq!( + catalog_entry("dev.lithe.test.agents", &agents[0])["configuration"]["mcpServers"], + json!({ "transports": ["stdio", "http", "sse"], "fields": [] }) + ); + + let mut value = configured(); + value["configuration"]["mcpServers"] = json!({ + "transports": ["stdio", "http"], + "fields": ["environment", "enabled", "callTimeout"] + }); + let mut agents = [agent(value)]; + check(&mut agents, true).expect("MCP server support validates"); + let support = agents[0] + .configuration + .as_ref() + .unwrap() + .mcp_server_support(); + assert!(support.takes_transport("http")); + assert!(!support.takes_transport("sse")); + assert!(support.keeps("enabled")); + assert!(!support.keeps("headers")); + let programs = programs(&agents[0]); + let program = programs + .iter() + .find(|program| program["kind"] == "agentConfiguration") + .expect("configuration is in the install review"); + assert_eq!(program["mcpServers"]["fields"][0], "environment"); +} + +#[test] +fn mcp_server_support_is_known_distinct_and_read() { + let cases: [(&str, Value, &str); 5] = [ + ( + "no transport", + json!({ "transports": [] }), + "agents[0].configuration.mcpServers.transports", + ), + ( + "an unknown transport", + json!({ "transports": ["websocket"] }), + "agents[0].configuration.mcpServers.transports[0]", + ), + ( + "a repeated transport", + json!({ "transports": ["stdio", "stdio"] }), + "agents[0].configuration.mcpServers.transports[1]", + ), + ( + "an unknown field", + json!({ "fields": ["environment", "secrets"] }), + "agents[0].configuration.mcpServers.fields[1]", + ), + ( + "a repeated field", + json!({ "fields": ["headers", "headers"] }), + "agents[0].configuration.mcpServers.fields[1]", + ), + ]; + for (name, servers, field) in cases { + let mut value = configured(); + value["configuration"]["mcpServers"] = servers; + assert_eq!(rejected_field(value, true), field, "{name}"); + } + + // Without a read function no server is ever reported or written. + let mut value = configured(); + let configuration = value["configuration"].as_object_mut().unwrap(); + configuration.remove("files"); + configuration.remove("read"); + configuration.remove("edit"); + configuration.insert("mcpServers".into(), json!({ "fields": ["headers"] })); + assert_eq!( + rejected_field(value, true), + "agents[0].configuration.mcpServers" + ); +} diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index d429a6ec..343c4f60 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -4640,6 +4640,7 @@ and keeps no name or icon of its own for any agent. "files": [{"id": "main", "roots": ["${userHome}/.sample/config.json"]}], "read": "configuration.read", "edit": "configuration.edit", + "mcpServers": {"transports": ["stdio", "http"], "fields": ["environment", "headers", "enabled", "disabledTools"]}, "providers": { "read": "providers.read", "edit": "providers.edit", @@ -4655,6 +4656,7 @@ and keeps no name or icon of its own for any agent. | `files` | At most 8 `{id, roots}`: the files in the CLI's own format that hold its MCP servers, hooks, model and model providers. `id` is 1–64 bytes of lowercase ASCII letters, digits and `-`, not starting or ending with `-`, unique in the agent. Only the backend reads their format. | | `read` | Backend function that reports the MCP servers and hooks `files` hold. Required with `files`, unless `providers` is declared, and refused without them. | | `edit` | Backend function that applies one change to a staged copy of one of `files`. Needs `read`. Without it the agent's MCP servers and hooks are shown, never changed. | +| `mcpServers` | `{transports?, fields?}`: what the CLI's MCP servers can hold, as `read` reports them and `edit` writes them (see [MCP servers](#mcp-servers)). Needs `read`. `transports` lists the transports the CLI connects with, each of `stdio`, `http` and `sse` at most once and at least one; absent is all three. `fields` lists the server fields the CLI keeps beyond name, transport, command, arguments and URL, each at most once: `environment`, `headers`, `enabled`, `disabledTools`, `startupTimeout` and `callTimeout`; absent is none. Added within `agents` 0. | | `providers` | `{read, edit?, operations?, listKeptBy?}`: backend functions that report and change the CLI's model, model providers and profiles kept in `files`, and may list the models the agent offers (see [Models and providers](#models-and-providers)). Needs `files`. `edit` and `operations` come together; `operations` lists each change `edit` makes at most once, from `addProvider`, `updateProvider`, `removeProvider`, `setProviderEnabled`, `setModel`, `setEffort`, `setSpeed`, `setModelMenu`, `setProvider` and `setProfile`. `listKeptBy` is `cli` (the default) when the CLI's configuration holds every custom provider, or `lithe` when it holds one active custom endpoint and Lithe keeps the list the user saved (see [Providers Lithe keeps](#providers-lithe-keeps)). | - A configuration declares at least one of `instructions`, `skills` and @@ -4689,8 +4691,10 @@ application data, never in the package or the installation, and both paths are absolute (`agentLibrary.invalidDirectory`). `environment` gives the values of the catalog's `sessionRootVariables`: at most 256, each name 1–256 bytes and each value at most 32 KiB (`agentLibrary.invalidEnvironment`). In -`directory`, created owner-only, Core keeps `library.json` (the servers, -hooks and instruction sets), `skills//` (one directory per skill), +`directory`, created owner-only, Core keeps `library.json` (the servers with +the values of their environment variables and headers, the hooks and the +instruction sets; always written owner-only), `skills//` (one +directory per skill), `state.json` (a digest of what Core last put in each agent's instruction block), `staging/` (the copies plugins edit) and `backups/` (each agent's files as they were before Lithe changed them; see @@ -4698,11 +4702,13 @@ files as they were before Lithe changed them; see The library is `{mcpServers, hooks, instructions}`: -- `mcpServers`: at most 256 `{name, transport, command?, args?, url?}`, - names unique. A `stdio` server has a nonblank `command` and at most 64 - `args`; an `http` or `sse` server has an `http://` or `https://` `url` and - neither. Version 0 keeps no environment variables or headers, whose values - are secrets. +- `mcpServers`: at most 256 `{name, transport, command?, args?, url?, + environment?, headers?, note?, enabled?, pausedAgents?, disabledTools?, + startupTimeoutSeconds?, callTimeoutSeconds?, icon?}`, names unique. A + `stdio` server has a nonblank `command`, at most 64 `args` and may have + `environment`; an `http` or `sse` server has an `http://` or `https://` + `url`, neither `command` nor `args`, and may have `headers`. + [MCP servers](#mcp-servers) describes the other fields. - `hooks`: at most 256 `{id, event, matcher?, command, timeoutSeconds?}`. The host chooses `id` (1–64 bytes of lowercase ASCII letters, digits and `-`, unique); `event` is 1–64 ASCII letters, digits and `_`, as the CLIs @@ -4742,15 +4748,17 @@ and its `agents` when not empty. | Command | Payload | Result | | --- | --- | --- | | `agentLibrary.configure` | `{directory, userHome, environment?}` | `{}` | -| `agentLibrary.read` | `{query?, agent?, presence?, sort?}` | `{revision, library, skills, states, agents, matches?}` | +| `agentLibrary.read` | `{query?, agent?, presence?, sort?}` | `{directory, revision, library, skills, states, stateDetails, found, agents, matches?}` | | `agentLibrary.save` | `{revision, library}` | `{revision, instructions}` | -| `agentLibrary.apply` | `{agent, change}` | `{changed}`; `{changed, revision, instructions}` for an `import` | +| `agentLibrary.parseServers` | `{text}` | `{servers, problems}` | +| `agentLibrary.apply` | `{agent, change}` | `{changed}`; `{changed, revision, instructions}` for an instructions `import`, `{changed, revision}` for a server `import` | | `agentLibrary.importSkill` | `{agent, name}` or `{directory}` | `{name, files, skipped}` | | `agentLibrary.removeSkill` | `{name}` | `{unlinked}` | - `save`, `apply`, `importSkill` and `removeSkill` run only for a request whose origin is the user (`agentLibrary.userActionRequired`): a plugin - never changes the library or an agent's configuration. + never changes the library or an agent's configuration. `parseServers` + only reads the text it is given (see [Pasted servers](#pasted-servers)). - `revision` is the SHA-256 of `library.json` in lowercase hex, or `empty` before the first save. `save` replaces the library only while the file is still at `revision` (`agentLibrary.revisionChanged`) and never replaces a @@ -4764,29 +4772,44 @@ and its `agents` when not empty. `instructions`, as [Instruction files](#instruction-files) describes. The library is saved whatever happens to an agent's file. -`read` answers the library, `skills`, `states` and `agents`: +`read` answers `directory`, the library directory as configured, so the +host can show where the library is; the library, as `save` takes it back, +with each variable of a server given as `{name, valueSet}` in place of its +value; and `skills`, `states`, `stateDetails`, `found` and `agents`: - `skills`: the library's skills, `{name, description?, agents}`, sorted by name. `agents` maps each agent key to `on` (the agent's skills directory has a link of that name into the library), `conflict` (an entry of that name that is not) or `off`. - `states.mcpServers` maps each library server's name, and - `states.hooks` each library hook's `id`, to the same kind of map. A server - is `on` when the agent has a server of that name that is the same server - (transport, `command`, `args` and `url`) with no environment variables or - headers, `conflict` when its server of that name differs, `unsupported` - when the plugin names no file for servers, otherwise `off`. A hook is `on` + `states.hooks` each library hook's `id`, to the same kind of map. A + server's state is as [MCP servers](#mcp-servers) describes. A hook is `on` when the agent has a hook with the same `event`, `matcher` and `command` (an empty matcher is no matcher), `unsupported` when the plugin names no file for hooks or the agent runs no hooks for the event, otherwise `off`. An agent whose plugin is not granted, whose `read` failed or that declares no `files` is in neither map; one whose skills directory Lithe could not read, or that declares no `skills`, is in no skill's `agents`. +- `stateDetails` is `{mcpServers, hooks}`, keyed like `states`, with an + entry only where there is something to say: `{reason?, + unsupportedFields?}`. `reason` is why the item cannot be put into the + agent, as the refusal of that `put` would say it: for a hook + `agentLibrary.noTarget` or `agentLibrary.unsupportedEvent`, for a server + those of [MCP servers](#mcp-servers), also for a `conflict` the library's + server cannot replace. `unsupportedFields` lists the fields the server uses + that the agent does not keep, as `configuration.mcpServers.fields` names + them, in that table's order. +- `found`: what agents hold outside the library, one group per item (see + [Found items](#found-items)). - `agents`: one entry per agent that declares `configuration`, in catalog order: `{agent, pluginID, agentID, displayName, icon?, mayConfigure, - editable, backup?, instructions?, skills?, mcpServers?, hooks?, - hookEvents?, providedSkills?, targets?, readError?}`. An agent whose - plugin is not granted gives only the fields up to `editable`. + editable, mcpServerSupport?, backup?, instructions?, skills?, + mcpServers?, hooks?, hookEvents?, providedSkills?, targets?, readError?}`. + An agent whose plugin is not granted gives only the fields up to + `editable`. + - `mcpServerSupport`: `{transports, fields}`, the agent's + `configuration.mcpServers` with the defaults applied, for an agent that + declares `read`. - `backup`: `{savedAtMs, modifiedSince}` while Core keeps a backup of the agent's files, whichever command changed them, as [Backups and restore](#backups-and-restore) describes; the same that @@ -4803,23 +4826,27 @@ and its `agents` when not empty. "agentLibrary.unreadable"}`. Entries without a readable `SKILL.md`, hidden entries and plain files are left out. - `mcpServers` and `hooks` are what `read` reported, each with - `inLibrary`, whether the library holds the same item; `hookEvents` and - `providedSkills` likewise; `targets` is `{mcpServers, hooks}`, whether - the plugin names a file for each. + `inLibrary`, whether the library holds the same item (for a server, + whether the library's server of its name writes exactly it into this + agent); a server's variables are `{name, valueSet}`, whether the plugin + reported a value, never the value, and names reported alone are + variables without one. `hookEvents` and `providedSkills` are as `read` + reported them; `targets` is `{mcpServers, hooks}`, whether the plugin + names a file for each. - `readError` is the code of a failed `read` (`agentLibrary.backendUnavailable`, `agentLibrary.readFailed` or `agentLibrary.invalidSnapshot`); the rest of the entry still answers. The filters of `read` are optional. Without any, the answer is exactly as -above and has no `matches`. With any, `library`, `skills`, `states` and -`agents` are still whole, because `save` replaces the whole library, and +above and has no `matches`. With any, `library`, `skills`, `states`, +`stateDetails`, `found` and `agents` are still whole, because `save` replaces the whole library, and `matches` is `{mcpServers, hooks, skills}`: the keys (server name, hook `id`, skill name) of the library items the filters keep, in the order `sort` gives, or in library order without `sort`. | Filter | Keeps | | --- | --- | -| `query` | Items whose text contains it, ignoring case: a server's name; a hook's `id`, `event`, `matcher` and `command`; a skill's name and description. At most 256 characters without NUL. | +| `query` | Items whose text contains it, ignoring case: a server's name and note; a hook's `id`, `event`, `matcher` and `command`; a skill's name and description. At most 256 characters without NUL. | | `agent` with `presence` | Items whose state for the agent key `agent` is `on` (`presence: "present"`) or anything else (`"missing"`: `off`, `conflict` or `unsupported`). An agent with no state for the item, such as one whose `read` failed, keeps nothing. The two come together. | | `sort` | `name` orders by name ignoring case; `agentCount` orders by how many agents have the item `on`, most first, then by name. | @@ -4836,6 +4863,7 @@ already had what it asks for: | --- | --- | | `{category: "mcpServers", op: "put", name}` | puts the library server `name` into the agent | | `{category: "mcpServers", op: "remove", name}` | removes the agent's own server `name` | +| `{category: "mcpServers", op: "import", name, revision}` | copies the agent's server `name`, values included, into the library at `revision` (see [MCP servers](#mcp-servers)); the agent's files stay as they are | | `{category: "hooks", op: "put", id}` | puts the library hook `id` into the agent | | `{category: "hooks", op: "remove", hook: {event, matcher?, command, timeoutSeconds?}}` | removes the agent's own hook that is this hook | | `{category: "skills", op: "link", name}` | links the library skill `name` into the agent's skills directory | @@ -4853,7 +4881,9 @@ A server or hook changes through the plugin, on a copy: without `edit` is `agentLibrary.notEditable`). Removing an item the user's own configuration does not hold, including one the CLI installed itself, is `agentLibrary.notInAgent`; putting a hook for an event the - agent does not run is `agentLibrary.unsupportedEvent`. + agent does not run is `agentLibrary.unsupportedEvent`; putting a server + the agent cannot take is refused as [MCP servers](#mcp-servers) + describes. 2. Core follows links in the file's path to the file itself (a link to nothing is `agentLibrary.brokenLink`), copies the file, or nothing when it does not exist, into an owner-only file in `staging/`, and calls `edit` @@ -4902,6 +4932,181 @@ agent whose plugin is granted, then the skill, and answers how many links it removed. A link in an agent whose plugin is not granted is left, and leads nowhere. +#### MCP servers + +A library server's fields beyond `name`, `transport`, `command`, `args` and +`url`: + +| Field | Meaning | +| --- | --- | +| `environment` | At most 64 `{name, value?}`, the environment variables of a `stdio` server. A name is 1–128 bytes of ASCII letters, digits, `_` and `-`, unique in the list; a value is at most 32 KiB without NUL. | +| `headers` | At most 64 `{name, value?}`, the HTTP headers of an `http` or `sse` server: names as above, unique ignoring ASCII case; a value also has no line break. | +| `note` | At most 1024 characters without NUL: the user's own note on the server. | +| `enabled` | `false` switches the server off; absent is on. | +| `pausedAgents` | At most 256 distinct agent keys, only while the server is off: the agents the host took the server out of when it switched it off, to put it back into when it switches it on. Core keeps them and does nothing else with them. | +| `disabledTools` | At most 256 distinct names of the server's tools, each a name as for a server, that agents leave out. | +| `startupTimeoutSeconds` | 1–86400: how long an agent waits for the server to start. | +| `callTimeoutSeconds` | 1–86400: how long one call of the server's tools may take. | +| `icon` | `{type, data}`: a picture for the server, `data` its bytes in standard Base64, 1 byte to 32 KiB decoded, and `type` `image/png`, `image/jpeg`, `image/gif` or `image/webp`, which the bytes must start as. Core fetches no icon. | + +`note`, `icon` and `pausedAgents` are the library's own and never reach an +agent. + +The values of environment variables and headers are secrets, written and +never read back: + +- `library.json` keeps them, and Core writes it owner-only. +- `read` gives each variable as `{name, valueSet}`, in the library and in + each agent's servers, never its value. +- In a `save`, a variable with `value` takes that value; one without (such + as the `{name, valueSet}` `read` gave) keeps the value the library has + for the variable of that name, ignoring ASCII case for a header, in the + server of the same name. A server the user renames gives the name it had + as `renamedFrom`, which keeps its values and is not kept itself. A + variable left out loses its value with it. +- A `put` hands the values to the plugin's `edit`; the plugin's `read` + reports them back, so Core can tell whether the agent holds the library's + server and can import the agent's. +- No answer but `parseServers`, no refusal and no log carries a value; a + payload that does not decode is refused (`agents.invalidPayload`) without + the decoder's text, which could quote one. + +What a `put` writes depends on what the agent's plugin declares in +`configuration.mcpServers` (`mcpServerSupport` in `read`): + +- A server whose transport the agent does not connect with is never written + (`agentLibrary.transportUnsupported`). +- A server with environment variables or headers is written only into an + agent that keeps them, since without them it would not start or not + authenticate (`agentLibrary.fieldUnsupported`), and only when each has a + value (`agentLibrary.valueMissing`). +- A server switched off is written with `enabled: false` into an agent that + keeps `enabled`, and into no other (`agentLibrary.serverOff`): the host + takes it out of such an agent with `remove` and notes the agent in + `pausedAgents`. +- `enabled` goes to every agent that keeps it, so a `put` also switches a + server back on there. `disabledTools` and the timeouts go to an agent that + keeps them and are left out otherwise. + +A server's state for an agent compares what a `put` would write with the +agent's servers of that name: the same transport, `command`, `args`, `url`, +variables and values (header names ignoring ASCII case), and the same of +each further field the agent keeps (`disabledTools` in any order); a field +the agent does not keep is not compared. + +| State | When | +| --- | --- | +| `on` | The agent has a server of that name that is what a `put` writes. | +| `conflict` | The agent has a server of that name that differs. | +| `unsupported` | The agent has none, and its plugin names no file for servers (`agentLibrary.noTarget`) or a `put` is refused as above. | +| `off` | The agent has none and a `put` would write it. | + +`import` takes the agent's server `name` into the library: of the agent's +servers of that name, the first whose every value the plugin reported and +that is the user's own, else the first whose every value it reported, else +the first of the user's own, else the first. It takes the server's +transport, command, arguments, URL, variables with their values, switch, +tools left out and timeouts. It is refused when the agent has no server of +that name (`agentLibrary.notInAgent`), the library is no longer at +`revision` (`agentLibrary.revisionChanged`), already has a server of that +name (`agentLibrary.serverExists`) or holds 256 (`agentLibrary.libraryFull`), +or the server breaks a rule of the library (`agentLibrary.invalidLibrary`, +such as a timeout of 0). A variable whose value the plugin did not report is +imported without one; the user gives it before a `put`. A missing `name` or +`revision` is `agentLibrary.invalidChange`. + +#### Found items + +`found` in `read` is what agents hold outside the library, so the host shows +each item once, whichever agents hold it: `{mcpServers, hooks, skills}`, each +a list of groups in the order of their first copy, agents in catalog order +and each agent's items in the order its entry lists them. + +| Category | A copy is found when | Grouped by | Two copies are the same when | +| --- | --- | --- | --- | +| `mcpServers` | the library has no server of its name that a `put` writes exactly as the copy is into its agent (`inLibrary: false`) | name | their transport, `command`, `args`, `url`, variables with their values (header names ignoring ASCII case), switch, `disabledTools` in any order and timeouts are | +| `hooks` | no library hook has its `event`, `matcher` and `command` (`inLibrary: false`) | `event`, `matcher` (an empty one is none), `command` and `timeoutSeconds` | always: a group is one hook | +| `skills` | it is an entry of the agent's skills directory that is not a link into the library (`own` or `link`), or a skill the CLI installed itself (`providedSkills`) | name | their `SKILL.md` bytes are; a skill the CLI installed is compared by its description, and is never the same as a directory | + +- A server group is `{name, copies, variants, inLibrary, importable, + importFrom?, valuesMissing?, reason?}`, each copy `{agent, index, variant, + differsFromLibrary?}`. +- A hook group is `{event, matcher?, command, timeoutSeconds?, copies, + importable, reason?}`, each copy `{agent, index}`. +- A skill group is `{name, copies, variants, inLibrary, importable, + importFrom?, reason?}`, each copy `{agent, source, index, variant, + differsFromLibrary?}`. The directory entries come before the skills CLIs + installed. +- `index` is the copy's place in its agent's `mcpServers` or `hooks`, or, + by `source`, in its `skills.items` (`skills`) or `providedSkills` + (`providedSkills`). `variant` numbers the distinct copies of a group from + 0 in the order they come, and `variants` counts them. Two copies that + differ only in a value are two variants; no group carries a value. +- `inLibrary` says the library has an item of the group's name. Then every + copy has `differsFromLibrary`: always `true` for a server, since a copy + the same as the library's is not found, and for a skill whether its + `SKILL.md` differs from the library skill's. +- `importable` says whether the library can take the group in, and `reason` + why not: + + | Category | How | `reason` | + | --- | --- | --- | + | `mcpServers` | `apply` `import` from the agent `importFrom`, whose copy is the first by the order `import` takes copies in | `agentLibrary.serverExists`, `agentLibrary.libraryFull`, or `agentLibrary.invalidLibrary` when that copy breaks a rule of the library | + | `hooks` | the host adds the hook to the library in a `save` | `agentLibrary.libraryFull` | + | `skills` | `importSkill {agent, name}` from `importFrom`, the first agent whose own directory holds it | `agentLibrary.skillExists`, or `agentLibrary.notOwnSkill` when no copy is an agent's own directory | + + `valuesMissing: true` says the server copy an import takes lacks a + variable's value. + +#### Pasted servers + +`parseServers` reads the MCP servers a text the user pasted describes and +saves nothing. `text` is at most 256 KiB (`agentLibrary.textTooLarge`). It +answers `{servers, problems}`: `servers` in the shape `save` takes, values +included, without `name` when the text gives none, and `problems`, what it +could not read. + +The text is JSON, which may hold `//` and `/* */` comments and trailing +commas. A text that is not JSON is read once more between `{` and `}`, so a +pasted `"name": {…}` member reads too. Servers are found in the first of +these the text holds: + +1. an object whose `mcpServers`, `servers`, `context_servers` or `mcp` + member is an object of servers by name, or whose `mcp.servers` is; +2. one server: an object with `command`, `url`, `serverUrl`, `httpUrl` or + `uri`, named by its `name` member when it has one; +3. an array some item of which is a server, each item named by its `name`; +4. an object some member of which is a server, each member a server by + name. + +| Field | Read from | +| --- | --- | +| `command`, `args` | `command` as a string, as an array of the command and its first arguments, or as `{path, args?, env?}`; then `args` | +| `url` | `url`, `serverUrl`, `httpUrl` or `uri` | +| `transport` | `type` or `transport`: `stdio` or `local`; `http`, `streamable-http`, `streamableHttp` or `streamable_http`; `sse`. Otherwise a command is `stdio`, a URL whose path ends in `/sse` is `sse` unless it came from `httpUrl`, and any other URL `http`. | +| `environment` | `env` or `environment`: an object of names and values | +| `headers` | `headers` or `http_headers` | +| `enabled` | `enabled`, or the opposite of `disabled` | +| `disabledTools` | `disabledTools`, `excludeTools` or `disabled_tools` | +| `startupTimeoutSeconds` | `startupTimeoutSeconds` or `startup_timeout_sec` | +| `callTimeoutSeconds` | `callTimeoutSeconds` or `tool_timeout_sec` | +| `note` | `note` or `description` | + +A number or boolean where text belongs reads as its text; other members are +ignored. Each server is checked as `save` checks it. A problem is +`{reason, path?, field?, line?, column?}`, `path` being the JSON pointer of +the entry: + +| `reason` | Meaning | +| --- | --- | +| `syntax`, `end` | The text is not JSON (`end`: it ends too early). `line` and `column`, from 1 and counting characters, say where in the text as pasted. Nothing else is read. | +| `noServers` | The text holds none of the shapes above. | +| `noCommandOrUrl` | The entry is not an object with a command or a URL. | +| `invalidName` | The entry's name breaks the rule for names. | +| `duplicateName` | An earlier entry has the name. | +| `invalidField` | The entry's `field`, named as the library names it (such as `args[2]`, `url` or `environment`), cannot be read or breaks a rule. | +| `tooMany` | The text holds more than 256 servers; only the first 256 are read. | + #### Instruction files Lithe writes only its own block in an agent's instruction file; every other @@ -5033,12 +5238,21 @@ for the file, with the same extension; `exists` says whether anything is at - `format: "litheAgentConfiguration"` and `version: 0`; - `mcpServers`: at most 256 `{name, transport, command?, args?, url?, - environmentNames?, headerNames?, origin, provider?}`, the servers the - files configure. `environmentNames` and `headerNames` are at most 64 names - each of ASCII letters, digits, `_` and `-`, never values. `origin` is - `user` for the user's own configuration, which `edit` changes, or `agent` - for what the CLI installed itself, such as through a CLI plugin, which - `provider` (1–128 characters) names and Lithe only shows; + environment?, headers?, environmentNames?, headerNames?, enabled?, + disabledTools?, startupTimeoutSeconds?, callTimeoutSeconds?, origin, + provider?}`, the servers the files configure. `environment` and `headers` + are at most 64 `{name, value?}` each, with the value the files hold; a + plugin that does not report values gives the names alone in + `environmentNames` and `headerNames` instead, never both lists for one + kind. Names are ASCII letters, digits, `_` and `-`. A plugin that + declares `environment` or `headers` in `configuration.mcpServers.fields` + reports their values, otherwise a server the library put never reads as + put. `enabled` is `false` for a server the CLI keeps switched off; + `disabledTools` (at most 256) and the timeouts are as the files hold + them. `origin` is `user` for the user's own configuration, which `edit` + changes, or `agent` for what the CLI installed itself, such as through a + CLI plugin, which `provider` (1–128 characters) names and Lithe only + shows; - `hooks`: at most 256 `{event, matcher?, command, timeoutSeconds?, origin, provider?}`; - `hookEvents`: at most 64 distinct events the CLI runs hooks for; empty @@ -5054,11 +5268,16 @@ Any other answer is `agentLibrary.invalidSnapshot`; a failed call is `edit` receives `{agentID, file: {id, staging, exists}, change}`, with `change` one of `{category: "mcpServers", op: "put", server: {name, -transport, command?, args?, url?}}`, `{category: "mcpServers", op: -"remove", name}`, `{category: "hooks", op: "put", hook: {event, matcher?, -command, timeoutSeconds?}}` and `{category: "hooks", op: "remove", hook}`. -`put` makes the user's configuration hold exactly that server, replacing a -server of the same name, or that hook; `remove` takes the item out. The +transport, command?, args?, url?, environment?, headers?, enabled?, +disabledTools?, startupTimeoutSeconds?, callTimeoutSeconds?}}`, +`{category: "mcpServers", op: "remove", name}`, `{category: "hooks", op: +"put", hook: {event, matcher?, command, timeoutSeconds?}}` and `{category: +"hooks", op: "remove", hook}`. A server carries only the fields its plugin +declares in `configuration.mcpServers.fields`, `environment` and `headers` +as `{name, value}` with every value, and `enabled` whenever the plugin +declares it. `put` makes the user's configuration hold exactly that server, +replacing a server of the same name, or that hook; `remove` takes the item +out. The backend never logs a value or puts one in an error. The backend changes only the file at `staging`, empty when `exists` is false, in the CLI's own format, keeping everything else the file holds, and answers `{format: "litheAgentConfigurationEdit", version: 0, changed}` within 10 @@ -5539,8 +5758,9 @@ in `agentLibrary.read` offers no restore there. - A request before `agentLibrary.configure` is `agentLibrary.notConfigured`. A `save` whose library breaks a rule above, or an `import` that would make the library break one, is `agentLibrary.invalidLibrary`, its message - naming the field. A backend that is not running is - `agentLibrary.backendUnavailable`. + naming the field, never a value. A `save` or `import` that would make + `library.json` larger than Core reads is `agentLibrary.libraryTooLarge`. + A backend that is not running is `agentLibrary.backendUnavailable`. - Changes never interleave: Core checks and replaces one file at a time, never while waiting for a backend. - Core logs plugin and agent IDs, categories, operations, counts, durations @@ -5560,7 +5780,8 @@ in `agentLibrary.read` offers no restore there. later changes were discarded and whether the agent stopped following the library) or `agent.providers.restore_failed` (refusal code). None of them carries a model, provider, URL, variable - name, label, key or backup content. + name, label, key or backup content, nor the value of a server's + environment variable or header. ### Privacy and logging diff --git a/shared/plugins/contract/v1/fixtures/agents/agents.plugin.json b/shared/plugins/contract/v1/fixtures/agents/agents.plugin.json index 7e98b547..58162f57 100644 --- a/shared/plugins/contract/v1/fixtures/agents/agents.plugin.json +++ b/shared/plugins/contract/v1/fixtures/agents/agents.plugin.json @@ -86,6 +86,18 @@ ], "read": "example.configuration.read", "edit": "example.configuration.edit", + "mcpServers": { + "transports": [ + "stdio", + "http" + ], + "fields": [ + "environment", + "headers", + "enabled", + "disabledTools" + ] + }, "providers": { "read": "example.providers.read", "edit": "example.providers.edit", diff --git a/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json b/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json index a163a05f..e48aa943 100644 --- a/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json +++ b/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json @@ -1014,6 +1014,11 @@ {"name": "a provider operation is a contract operation", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/configuration/providers/operations", "value": ["setModel", "setSecret"]}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.providers.operations[1]"}, {"name": "a provider operation is listed once", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/configuration/providers/operations", "value": ["setModel", "setModel"]}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.providers.operations[1]"}, {"name": "a providers field is known", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/configuration/providers/secrets", "value": "example.providers.secrets"}], "expectedCode": "plugin.manifest.invalid"}, + {"name": "MCP server support needs a read function", "base": "agents.plugin.json", "edits": [{"op": "remove", "path": "/agents/0/configuration/edit"}, {"op": "remove", "path": "/agents/0/configuration/read"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.mcpServers"}, + {"name": "an MCP transport is stdio, http or sse", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/configuration/mcpServers/transports", "value": ["stdio", "websocket"]}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.mcpServers.transports[1]"}, + {"name": "a CLI takes at least one MCP transport", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/configuration/mcpServers/transports", "value": []}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.mcpServers.transports"}, + {"name": "an MCP server field is a contract field", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/configuration/mcpServers/fields", "value": ["environment", "cwd"]}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.mcpServers.fields[1]"}, + {"name": "an MCP server field is listed once", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/configuration/mcpServers/fields", "value": ["enabled", "enabled"]}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.mcpServers.fields[1]"}, {"name": "a configuration edit function needs read", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/configuration/files", "value": []}, {"op": "remove", "path": "/agents/0/configuration/read"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.edit"}, {"name": "a configuration function is a function ID", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/configuration/edit", "value": "Example Edit"}], "expectedCode": "plugin.manifest.invalid", "expectedField": "agents[0].configuration.edit"}, {"name": "an agent field is known", "base": "agents.plugin.json", "edits": [{"op": "set", "path": "/agents/0/environment", "value": {"EXAMPLE": "1"}}], "expectedCode": "plugin.manifest.invalid"} diff --git a/shared/plugins/contract/v1/plugin-manifest.schema.json b/shared/plugins/contract/v1/plugin-manifest.schema.json index 327bed37..c4264071 100644 --- a/shared/plugins/contract/v1/plugin-manifest.schema.json +++ b/shared/plugins/contract/v1/plugin-manifest.schema.json @@ -512,7 +512,8 @@ "dependentRequired": { "read": ["files"], "edit": ["read"], - "providers": ["files"] + "providers": ["files"], + "mcpServers": ["read"] }, "if": {"required": ["files"], "properties": {"files": {"minItems": 1}}}, "then": {"anyOf": [{"required": ["read"]}, {"required": ["providers"]}]}, @@ -585,6 +586,26 @@ "enum": ["cli", "lithe"] } } + }, + "mcpServers": { + "description": "Added within agents 0. What the CLI's MCP servers can hold, as read reports them and edit writes them; needs read. Absent, the CLI takes every transport and none of the fields. Core never writes a server whose transport, environment variables or headers the CLI cannot keep, writes a switched-off server only into a CLI that keeps enabled, and leaves out disabledTools and timeouts the CLI does not keep.", + "type": "object", + "additionalProperties": false, + "properties": { + "transports": { + "description": "The transports the CLI connects with; absent is all of them.", + "type": "array", + "minItems": 1, + "uniqueItems": true, + "items": {"enum": ["stdio", "http", "sse"]} + }, + "fields": { + "description": "The server fields beyond name, transport, command, args and url that the CLI keeps. environment and headers: read reports each variable's value and edit writes it. enabled: the CLI keeps a server switched off. disabledTools: tools the CLI leaves out. startupTimeout and callTimeout: startupTimeoutSeconds and callTimeoutSeconds.", + "type": "array", + "uniqueItems": true, + "items": {"enum": ["environment", "headers", "enabled", "disabledTools", "startupTimeout", "callTimeout"]} + } + } } } }, diff --git a/shared/plugins/reference/api-catalog.md b/shared/plugins/reference/api-catalog.md index fd00d60f..78a8be8f 100644 --- a/shared/plugins/reference/api-catalog.md +++ b/shared/plugins/reference/api-catalog.md @@ -61,7 +61,7 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I | API-38 | 受管网络 | 部分完成 | `network/request`:可取消、有界 HTTP(S) | 下载文件、身份验证会话 | [工作流](../guides/plugin-workflows.md) | | API-40 | 工作区 authority | 部分完成 | [工作区上下文](../contract/v1/README.md#workspace-contexts-and-capability-discovery)带 `local` 或 `remote`,远程的另带远端主机的 `platform`(`os`、`arch`);`workspace/getHostPaths` 单独给出根目录在远端主机上的路径;文件和编辑器方法对远程上下文明确返回 `plugin.host.authorityUnsupported`;远程专用的失败码 `remoteDisconnected`、`platformUnavailable` | 远程执行(进程、语言服务器、调试器在远端主机上运行)、贡献的运行位置 `placement` | [插件后端](domains/backend.md)、[远程工作区](../guides/plugin-backend-remote-workspaces.md) | | API-41 | 激活事件与启动预算 | 部分完成 | [`onWorkspaceOpen`](../contract/v1/README.md#permissions-and-activation)、`onCommand`、后台两路并发启动、`initialize` 超时、有界通知队列 | 按工作区内容匹配激活、全局冷启动预算 | [插件后端](domains/backend.md) | -| API-45 | Agent | 部分完成 | [`agents`](../contract/v1/README.md#agents) 声明用户自己安装的 Agent CLI:[原生会话](../contract/v1/README.md#native-sessions)(Core 启动和回收 CLI,后端用 `agents/write`、`agents/report` 翻译 CLI 自己的协议)、终端形式、更新命令;用户逐个 Agent 同意后,Core 读取声明目录里的[会话记录](../contract/v1/README.md#session-records),后端解析,Core 缓存、搜索和统计。宿主可用 `agentSessions.stats` 一次读取用量总计、分组和时间序列;`agents/usage` 汇总用量与额度,不含对话正文、标题、会话 ID 和目录;声明了 [`configuration`](../contract/v1/README.md#agent-configuration) 的 Agent 由宿主的资源库统一管理指令、技能、MCP 服务器和 Hooks,Core 只在用户操作时写进 CLI 自己的配置;`agentLibrary.read` 可选按文字、某个 Agent 是否已有、名称或已启用 Agent 数筛选排序(`agents` 0 内的补充);再声明 [`configuration.providers`](../contract/v1/README.md#models-and-providers) 的 Agent 由宿主显示当前模型、模型供应商、配置档和登录账号标签,并按插件声明的操作经暂存副本修改(`agents` 0 内的补充),密钥只写不读(读取只报 `keySet`),请求头和查询参数只报名字,端点不得带用户信息、查询或片段,插件不读凭据文件和钥匙串;配置里只能放一个自定义端点的 CLI 由 Lithe 保存供应商列表(`listKeptBy: "lithe"`,密钥由插件存进自己的凭据),资源库和供应商的修改替换文件前都先备份(同一个文件只存一份原样,`agentLibrary.read` 与 `agentProviders.read` 带同一个 `backup`),`agentProviders.restore` 由用户恢复任何已授权 Agent 的原样(`agents` 0 内的补充);[指令文件](../contract/v1/README.md#instruction-files)里 Core 只写自己标记的一块、块外用户文字不动,资源库有多套指令、各有开关和 Agent 列表,`agentLibrary.save` 保存后给每个跟随的 Agent 同步并逐个回答结果(不覆盖用户改过的块),`agentLibrary.apply` 的 `import` 把块外用户文字并入资源库,恢复放回指令文件时该 Agent 不再跟随(`agents` 0 内的补充);已记录的会话可按插件声明的 `terminal.resumeArguments` 生成恢复命令(`agentSessions.resume`,转义后可复制,在终端继续需 `agents.run`)、导出为有大小上限、文字由宿主按界面语言传入的 Markdown(`agentSessions.export`)、按插件 `scan` 报告的线程列出子代理及其调用和用量(`agentSessions.subagents`),列表分组标出根目录、临时目录和隐藏文件夹(`category`),搜索命中可带片段和命中区间(`snippets`),这些操作对会话文件只读(`agents` 0 内的补充);插件可在 `providers` 快照里[列出模型](../contract/v1/README.md#listed-models)及其推理强度、速度档和上下文窗口,Core 检查选择在清单里、组合是插件允许的,用户在 Lithe 选择器里显示或隐藏模型的开关由 Core 记住(`agentProviders.showModels`),插件声明 `setModelMenu` 时 CLI 自己的模型菜单跟着变,开关和选择可整组读出、写回(`agentProviders.readModelSettings`、`agentProviders.applyModelSettings`)(`agents` 0 内的补充) | ACP 客户端(`acp` 只校验、列入审查)、MCP 会话搜索、远程工作区、模型方案的保存与切换;Lithe 桌面端尚未声明 `agents` | [Agent](domains/agents.md) | +| API-45 | Agent | 部分完成 | [`agents`](../contract/v1/README.md#agents) 声明用户自己安装的 Agent CLI:[原生会话](../contract/v1/README.md#native-sessions)(Core 启动和回收 CLI,后端用 `agents/write`、`agents/report` 翻译 CLI 自己的协议)、终端形式、更新命令;用户逐个 Agent 同意后,Core 读取声明目录里的[会话记录](../contract/v1/README.md#session-records),后端解析,Core 缓存、搜索和统计。宿主可用 `agentSessions.stats` 一次读取用量总计、分组和时间序列;`agents/usage` 汇总用量与额度,不含对话正文、标题、会话 ID 和目录;声明了 [`configuration`](../contract/v1/README.md#agent-configuration) 的 Agent 由宿主的资源库统一管理指令、技能、MCP 服务器和 Hooks,Core 只在用户操作时写进 CLI 自己的配置;`agentLibrary.read` 可选按文字、某个 Agent 是否已有、名称或已启用 Agent 数筛选排序(`agents` 0 内的补充);再声明 [`configuration.providers`](../contract/v1/README.md#models-and-providers) 的 Agent 由宿主显示当前模型、模型供应商、配置档和登录账号标签,并按插件声明的操作经暂存副本修改(`agents` 0 内的补充),密钥只写不读(读取只报 `keySet`),请求头和查询参数只报名字,端点不得带用户信息、查询或片段,插件不读凭据文件和钥匙串;配置里只能放一个自定义端点的 CLI 由 Lithe 保存供应商列表(`listKeptBy: "lithe"`,密钥由插件存进自己的凭据),资源库和供应商的修改替换文件前都先备份(同一个文件只存一份原样,`agentLibrary.read` 与 `agentProviders.read` 带同一个 `backup`),`agentProviders.restore` 由用户恢复任何已授权 Agent 的原样(`agents` 0 内的补充);[指令文件](../contract/v1/README.md#instruction-files)里 Core 只写自己标记的一块、块外用户文字不动,资源库有多套指令、各有开关和 Agent 列表,`agentLibrary.save` 保存后给每个跟随的 Agent 同步并逐个回答结果(不覆盖用户改过的块),`agentLibrary.apply` 的 `import` 把块外用户文字并入资源库,恢复放回指令文件时该 Agent 不再跟随(`agents` 0 内的补充);已记录的会话可按插件声明的 `terminal.resumeArguments` 生成恢复命令(`agentSessions.resume`,转义后可复制,在终端继续需 `agents.run`)、导出为有大小上限、文字由宿主按界面语言传入的 Markdown(`agentSessions.export`)、按插件 `scan` 报告的线程列出子代理及其调用和用量(`agentSessions.subagents`),列表分组标出根目录、临时目录和隐藏文件夹(`category`),搜索命中可带片段和命中区间(`snippets`),这些操作对会话文件只读(`agents` 0 内的补充);插件可在 `providers` 快照里[列出模型](../contract/v1/README.md#listed-models)及其推理强度、速度档和上下文窗口,Core 检查选择在清单里、组合是插件允许的,用户在 Lithe 选择器里显示或隐藏模型的开关由 Core 记住(`agentProviders.showModels`),插件声明 `setModelMenu` 时 CLI 自己的模型菜单跟着变,开关和选择可整组读出、写回(`agentProviders.readModelSettings`、`agentProviders.applyModelSettings`)(`agents` 0 内的补充);插件用 `configuration.mcpServers` 声明 CLI 支持的 MCP 连接方式和能保存的字段,资源库的 [MCP 服务器](../contract/v1/README.md#mcp-servers)多了环境变量和请求头(值存在仅所有者可读写的 `library.json`,只写不读,不进回答、拒绝和日志)、备注、开关、禁用的工具、超时和图标,Core 只写 Agent 能保存的字段,放不进去时在 `stateDetails` 给出原因;`agentLibrary.apply` 的服务器 `import` 连同值从 Agent 导入,`agentLibrary.parseServers` 解析粘贴的 JSON,`agentLibrary.read` 带资源库目录和只在 Agent 里的条目分组 `found`(`agents` 0 内的补充) | ACP 客户端(`acp` 只校验、列入审查)、MCP 会话搜索、远程工作区、模型方案的保存与切换;Lithe 桌面端尚未声明 `agents` | [Agent](domains/agents.md) | ### 计划中的 API @@ -284,7 +284,7 @@ Status meanings: | API-38 | Managed network | Partial | `network/request`: bounded HTTP(S) with cancellation | File downloads and authentication sessions | [Workflows](../guides/plugin-workflows.md) | | API-40 | Workspace authority | Partial | [Workspace contexts](../contract/v1/README.md#workspace-contexts-and-capability-discovery) carry `local` or `remote`, and a remote one also the remote host's `platform` (`os`, `arch`); `workspace/getHostPaths` gives the roots' paths on the remote host on its own; file and editor methods refuse a remote context with `plugin.host.authorityUnsupported`; the remote failure codes `remoteDisconnected` and `platformUnavailable` | Remote execution (processes, language servers, and debuggers running on the remote host), the `placement` of contributions | [Plugin backend](domains/backend.md), [Remote workspaces](../guides/plugin-backend-remote-workspaces.md) | | API-41 | Activation events and startup budget | Partial | [`onWorkspaceOpen`](../contract/v1/README.md#permissions-and-activation), `onCommand`, two concurrent background starts, `initialize` timeout, bounded notification queues | Activation by workspace content, a global cold-start budget | [Plugin backend](domains/backend.md) | -| API-45 | Agents | Partial | [`agents`](../contract/v1/README.md#agents) declares agent CLIs the user installed: [native sessions](../contract/v1/README.md#native-sessions) (Core starts and reaps the CLI; the backend translates the CLI's own protocol with `agents/write` and `agents/report`), terminal forms, and update commands. After the user consents for an agent, Core reads the [session records](../contract/v1/README.md#session-records) in the declared directories, the backend parses them, and Core caches, searches, and sums them. The host can read totals, groups and a time series in one `agentSessions.stats` overview; `agents/usage` sums usage and quotas without conversation text, titles, session IDs, or directories. For an agent that declares [`configuration`](../contract/v1/README.md#agent-configuration), the host's library manages instructions, skills, MCP servers, and hooks, and Core writes them into the CLI's own configuration only on a user action; `agentLibrary.read` optionally filters and sorts library items by text, by whether one agent has them, by name, or by how many agents have them on (an addition within `agents` 0); for an agent that also declares [`configuration.providers`](../contract/v1/README.md#models-and-providers), the host shows the current model, model providers, profiles, and signed-in account label, and changes the operations the plugin declares through a staged copy (an addition within `agents` 0); keys are write-only (a read reports only `keySet`), headers and query parameters are reported by name only, endpoints carry no user info, query, or fragment, and plugins never read credential files or the keychain; for a CLI whose configuration holds one custom endpoint, Lithe keeps the list of providers (`listKeptBy: "lithe"`, the plugin keeping keys in its own credentials), Core backs a file up before a library or providers change replaces it (one original per file; `agentLibrary.read` and `agentProviders.read` carry the same `backup`), and `agentProviders.restore` puts any granted agent's files back on the user's request (an addition within `agents` 0); in the [instruction file](../contract/v1/README.md#instruction-files) Core writes only its own marked block and never the user's text outside it, the library holds several instruction sets each with its own switch and agent list, `agentLibrary.save` brings every following agent up to date and answers each agent's result (never writing over a block the user edited), the `import` of `agentLibrary.apply` moves the user's text outside the block into the library, and a restore that puts the instruction file back stops the agent following (an addition within `agents` 0); a recorded session can be continued with a quoted, copyable command built from the plugin's `terminal.resumeArguments` (`agentSessions.resume`; continuing in a terminal needs `agents.run`), exported as bounded Markdown whose words the host passes in the interface language (`agentSessions.export`), and broken down by subagent with each one's calls and usage from the threads the plugin's `scan` reports (`agentSessions.subagents`); list groups mark roots, temporary directories and hidden folders (`category`), and search hits can carry a snippet with the matched words (`snippets`); none of these writes a session file (an addition within `agents` 0); the plugin may [list models](../contract/v1/README.md#listed-models) in the `providers` snapshot with their reasoning efforts, speeds, and context windows, Core checks that a pick is listed and a combination the plugin allows, Core keeps the switches with which the user shows or hides models in Lithe's pickers (`agentProviders.showModels`), the CLI's own model menu follows them when the plugin declares `setModelMenu`, and the switches and picks are read and written back as one group (`agentProviders.readModelSettings`, `agentProviders.applyModelSettings`) (an addition within `agents` 0) | An ACP client (`acp` is only validated and reviewed), MCP session search, remote workspaces, saving and switching model plans; the Lithe desktop client does not declare `agents` yet | [Agents](domains/agents.md) | +| API-45 | Agents | Partial | [`agents`](../contract/v1/README.md#agents) declares agent CLIs the user installed: [native sessions](../contract/v1/README.md#native-sessions) (Core starts and reaps the CLI; the backend translates the CLI's own protocol with `agents/write` and `agents/report`), terminal forms, and update commands. After the user consents for an agent, Core reads the [session records](../contract/v1/README.md#session-records) in the declared directories, the backend parses them, and Core caches, searches, and sums them. The host can read totals, groups and a time series in one `agentSessions.stats` overview; `agents/usage` sums usage and quotas without conversation text, titles, session IDs, or directories. For an agent that declares [`configuration`](../contract/v1/README.md#agent-configuration), the host's library manages instructions, skills, MCP servers, and hooks, and Core writes them into the CLI's own configuration only on a user action; `agentLibrary.read` optionally filters and sorts library items by text, by whether one agent has them, by name, or by how many agents have them on (an addition within `agents` 0); for an agent that also declares [`configuration.providers`](../contract/v1/README.md#models-and-providers), the host shows the current model, model providers, profiles, and signed-in account label, and changes the operations the plugin declares through a staged copy (an addition within `agents` 0); keys are write-only (a read reports only `keySet`), headers and query parameters are reported by name only, endpoints carry no user info, query, or fragment, and plugins never read credential files or the keychain; for a CLI whose configuration holds one custom endpoint, Lithe keeps the list of providers (`listKeptBy: "lithe"`, the plugin keeping keys in its own credentials), Core backs a file up before a library or providers change replaces it (one original per file; `agentLibrary.read` and `agentProviders.read` carry the same `backup`), and `agentProviders.restore` puts any granted agent's files back on the user's request (an addition within `agents` 0); in the [instruction file](../contract/v1/README.md#instruction-files) Core writes only its own marked block and never the user's text outside it, the library holds several instruction sets each with its own switch and agent list, `agentLibrary.save` brings every following agent up to date and answers each agent's result (never writing over a block the user edited), the `import` of `agentLibrary.apply` moves the user's text outside the block into the library, and a restore that puts the instruction file back stops the agent following (an addition within `agents` 0); a recorded session can be continued with a quoted, copyable command built from the plugin's `terminal.resumeArguments` (`agentSessions.resume`; continuing in a terminal needs `agents.run`), exported as bounded Markdown whose words the host passes in the interface language (`agentSessions.export`), and broken down by subagent with each one's calls and usage from the threads the plugin's `scan` reports (`agentSessions.subagents`); list groups mark roots, temporary directories and hidden folders (`category`), and search hits can carry a snippet with the matched words (`snippets`); none of these writes a session file (an addition within `agents` 0); the plugin may [list models](../contract/v1/README.md#listed-models) in the `providers` snapshot with their reasoning efforts, speeds, and context windows, Core checks that a pick is listed and a combination the plugin allows, Core keeps the switches with which the user shows or hides models in Lithe's pickers (`agentProviders.showModels`), the CLI's own model menu follows them when the plugin declares `setModelMenu`, and the switches and picks are read and written back as one group (`agentProviders.readModelSettings`, `agentProviders.applyModelSettings`) (an addition within `agents` 0); a plugin declares the MCP transports its CLI connects with and the server fields it keeps in `configuration.mcpServers`, the library's [MCP servers](../contract/v1/README.md#mcp-servers) gain environment variables and headers (values kept in the owner-only `library.json`, write-only, never in an answer, refusal or log), a note, a switch, tools left out, timeouts and an icon, Core writes only the fields the agent keeps and gives the reason in `stateDetails` when a server cannot be put, a server `import` of `agentLibrary.apply` takes an agent's server with its values, `agentLibrary.parseServers` reads pasted JSON, and `agentLibrary.read` gives the library directory and `found`, the groups of items only in agents (an addition within `agents` 0) | An ACP client (`acp` is only validated and reviewed), MCP session search, remote workspaces, saving and switching model plans; the Lithe desktop client does not declare `agents` yet | [Agents](domains/agents.md) | ### Planned APIs diff --git a/shared/plugins/reference/capabilities-and-versions.md b/shared/plugins/reference/capabilities-and-versions.md index 00e29abf..9062154d 100644 --- a/shared/plugins/reference/capabilities-and-versions.md +++ b/shared/plugins/reference/capabilities-and-versions.md @@ -67,7 +67,7 @@ Core 列以本仓库 `main` 上的 Core 源码为准([`capabilities.rs`](https | `outputLinkMatchers` `0` | [`outputLinkMatchers[]`](../contract/v1/README.md#output-link-matchers):插件声明的匹配规则让 Run 和测试控制台的输出出现链接;Core 负责匹配,`resolve` 函数在点击时才调用 | ✅ | ✅ | [语言](domains/languages.md) | | `projectGenerators` `0` | [`projectGenerators[]`](../contract/v1/README.md#project-generators):新建项目窗口里的条目,含 [`tool` 字段](../contract/v1/README.md#tool-fields) | ✅ | ✅ | [项目生成器](domains/project-generators.md) | | `backend` `0` | [`backend`](../contract/v1/README.md#plugin-backend):插件自己的长驻进程,带或不带页面启动,按权限提供宿主服务,说 `litheFunctions` | ✅ | ✅¹ | [插件后端与插件函数](domains/backend.md) | -| `agents` `0` | [`agents[]`](../contract/v1/README.md#agents):用户自己安装的 Agent CLI 的原生会话(后端翻译 CLI 自己的协议,Core 启动进程)、终端形式、更新命令和会话记录;权限 `agents.run`、`agents.native`、`agents.sessions.read`、`agents.usage.read`,激活事件 `onAgent:`;`acp` 只校验、不运行。Agent 资源库的 `configuration` 声明和权限 `agents.configuration` 是 0 内的补充:不认识它们的 Core 以 `plugin.manifest.invalid` 拒绝声明了它们的清单,也不回答 `agentLibrary.*` 命令;提示附件(`agents.prompt` 的 `attachments`)和 `native.imageTypes` 也是 0 内的补充:不认识它们的 Core 同样拒绝声明了 `imageTypes` 的清单,也拒绝带 `attachments` 的 `agents.prompt`;`configuration.providers`(模型与模型供应商)和 `agentLibrary.read` 的筛选排序参数也是 0 内的补充:不认识它们的 Core 以 `plugin.manifest.invalid` 拒绝声明了 `providers` 的清单,以 `agents.invalidPayload` 拒绝带筛选参数的 `agentLibrary.read`,也不回答 `agentProviders.*` 命令;`configuration.providers.listKeptBy`、修改里的 `key`/`clearKey`/`model`、快照的 `keySet`/`model` 和 `agentProviders.restore` 同属这项补充;资源库修改前的备份、`agentLibrary.read` 的 `backup` 和对不声明 `providers` 的 Agent 的 `agentProviders.restore` 是其后的补充:旧 Core 只备份 `agentProviders.apply` 的修改,不回答这个 `backup`,并以 `agentProviders.notDeclared` 拒绝这种恢复;指令文件只写 Lithe 的块、指令集的 `on` 与 `agents`、`save` 回答的 `instructions`、`agentLibrary.apply` 的 `import` 和恢复回答的 `unfollowed` 是其后的补充;`terminal.resumeArguments`、`scan` 的 `threads`、`agentSessions.resume`/`export`/`subagents`、列表的 `resumable` 与分组 `category`、搜索的 `snippets` 也是 0 内的补充:不认识它们的 Core 以 `plugin.manifest.invalid` 拒绝声明了 `resumeArguments` 的清单,不向 `scan` 要 `threads`,也不回答这三个命令;插件在 `providers` 快照里列出的模型(`models`、`efforts`、`speeds`、`effort`、`speed`、`modelMenu`、`targets.modelMenu`)、操作 `setEffort`、`setSpeed`、`setModelMenu` 和 `setModel` 的 `effort`、`speed`,以及命令 `agentProviders.showModels`、`agentProviders.readModelSettings`、`agentProviders.applyModelSettings` 是最后的补充 | ✅ | 待宿主接入 | [Agent](domains/agents.md) | +| `agents` `0` | [`agents[]`](../contract/v1/README.md#agents):用户自己安装的 Agent CLI 的原生会话(后端翻译 CLI 自己的协议,Core 启动进程)、终端形式、更新命令和会话记录;权限 `agents.run`、`agents.native`、`agents.sessions.read`、`agents.usage.read`,激活事件 `onAgent:`;`acp` 只校验、不运行。Agent 资源库的 `configuration` 声明和权限 `agents.configuration` 是 0 内的补充:不认识它们的 Core 以 `plugin.manifest.invalid` 拒绝声明了它们的清单,也不回答 `agentLibrary.*` 命令;提示附件(`agents.prompt` 的 `attachments`)和 `native.imageTypes` 也是 0 内的补充:不认识它们的 Core 同样拒绝声明了 `imageTypes` 的清单,也拒绝带 `attachments` 的 `agents.prompt`;`configuration.providers`(模型与模型供应商)和 `agentLibrary.read` 的筛选排序参数也是 0 内的补充:不认识它们的 Core 以 `plugin.manifest.invalid` 拒绝声明了 `providers` 的清单,以 `agents.invalidPayload` 拒绝带筛选参数的 `agentLibrary.read`,也不回答 `agentProviders.*` 命令;`configuration.providers.listKeptBy`、修改里的 `key`/`clearKey`/`model`、快照的 `keySet`/`model` 和 `agentProviders.restore` 同属这项补充;资源库修改前的备份、`agentLibrary.read` 的 `backup` 和对不声明 `providers` 的 Agent 的 `agentProviders.restore` 是其后的补充:旧 Core 只备份 `agentProviders.apply` 的修改,不回答这个 `backup`,并以 `agentProviders.notDeclared` 拒绝这种恢复;指令文件只写 Lithe 的块、指令集的 `on` 与 `agents`、`save` 回答的 `instructions`、`agentLibrary.apply` 的 `import` 和恢复回答的 `unfollowed` 是其后的补充;`terminal.resumeArguments`、`scan` 的 `threads`、`agentSessions.resume`/`export`/`subagents`、列表的 `resumable` 与分组 `category`、搜索的 `snippets` 也是 0 内的补充:不认识它们的 Core 以 `plugin.manifest.invalid` 拒绝声明了 `resumeArguments` 的清单,不向 `scan` 要 `threads`,也不回答这三个命令;插件在 `providers` 快照里列出的模型(`models`、`efforts`、`speeds`、`effort`、`speed`、`modelMenu`、`targets.modelMenu`)、操作 `setEffort`、`setSpeed`、`setModelMenu` 和 `setModel` 的 `effort`、`speed`,以及命令 `agentProviders.showModels`、`agentProviders.readModelSettings`、`agentProviders.applyModelSettings` 是其后的补充;`configuration.mcpServers`、资源库 MCP 服务器的环境变量与请求头(值只写不读)、备注、开关、`pausedAgents`、禁用的工具、超时和图标,`configuration.read` 报告的值、开关、禁用的工具和超时,`edit` 的服务器按声明带这些字段,`agentLibrary.apply` 的服务器 `import`、`agentLibrary.parseServers`,以及 `agentLibrary.read` 的 `directory`、`stateDetails`、`found` 和 `mcpServerSupport` 是最后的补充 | ✅ | 待宿主接入 | [Agent](domains/agents.md) | | `toolDefinitions` `0` | `toolDefinitions[]`:[工具身份、布局、发现和四层候选](../contract/v1/toolchains/README.md) | ✅ | ✅¹ | [工具链](domains/toolchains.md) | | `toolDefinitions` `1` | 在 `0` 之上加:工具定义的 `category`(设置页「工具链」里的分组)和 `audience`(`plugin` 表示插件自用的运行时,单独放在最后一组),只影响显示位置 | ✅ | 未声明 | [Settings list](../contract/v1/toolchains/README.md#settings-list) | | `toolchainProviders` `0` | `toolchainProviders[]`:[提供者声明和按权限校验应答](../contract/v1/toolchains/README.md);说 `litheToolchains` | ✅ | ✅ | [工具链](domains/toolchains.md) | @@ -188,7 +188,7 @@ Each row is one capability. `requires` lists **exactly** the capabilities a mani | `outputLinkMatchers` `0` | [`outputLinkMatchers[]`](../contract/v1/README.md#output-link-matchers): plugin-declared patterns that turn Run and Test console output into links; Core does the matching, and the `resolve` function is called only on click | ✅ | ✅ | [Languages](domains/languages.md) | | `projectGenerators` `0` | [`projectGenerators[]`](../contract/v1/README.md#project-generators): entries of the New Project window, including [`tool` fields](../contract/v1/README.md#tool-fields) | ✅ | ✅ | [Project generators](domains/project-generators.md) | | `backend` `0` | [`backend`](../contract/v1/README.md#plugin-backend): the plugin's own long-lived process, started with or without a page, serving the host services its permissions grant and speaking `litheFunctions` | ✅ | ✅¹ | [Plugin backend and plugin functions](domains/backend.md) | -| `agents` `0` | [`agents[]`](../contract/v1/README.md#agents): native sessions of agent CLIs the user installed (the backend translates the CLI's own protocol and Core starts the process), terminal forms, update commands, and session records; permissions `agents.run`, `agents.native`, `agents.sessions.read`, `agents.usage.read`, activation event `onAgent:`; `acp` is validated but not run. The agent library's `configuration` declaration and the `agents.configuration` permission were added within 0: a Core that does not know them refuses a manifest that declares them with `plugin.manifest.invalid` and answers no `agentLibrary.*` command. Prompt attachments, the `attachments` of `agents.prompt`, and `native.imageTypes` were also added within 0: a Core that does not know them refuses a manifest that declares `imageTypes` the same way, and refuses an `agents.prompt` with `attachments`. `configuration.providers` (models and model providers) and the filter and sort parameters of `agentLibrary.read` were also added within 0: a Core that does not know them refuses a manifest that declares `providers` with `plugin.manifest.invalid`, refuses an `agentLibrary.read` with filters with `agents.invalidPayload`, and answers no `agentProviders.*` command; `configuration.providers.listKeptBy`, the `key`, `clearKey` and `model` of a change, the snapshot's `keySet` and `model`, and `agentProviders.restore` belong to the same addition; the backups before library changes, `backup` in `agentLibrary.read`, and `agentProviders.restore` for an agent without `providers` were added after it: an older Core backs up only what `agentProviders.apply` changes, gives no such `backup`, and refuses such a restore with `agentProviders.notDeclared`; writing only Lithe's block of the instruction file, the sets' `on` and `agents`, the `instructions` a `save` answers, the `import` of `agentLibrary.apply` and the `unfollowed` of a restore were added after that; `terminal.resumeArguments`, `threads` from `scan`, `agentSessions.resume`, `export` and `subagents`, `resumable` and the group `category` of the list, and `snippets` of the search are additions within 0 as well: an older Core rejects a manifest that declares `resumeArguments` with `plugin.manifest.invalid`, never asks `scan` for `threads`, and answers none of the three commands; the models a plugin lists in the `providers` snapshot (`models`, `efforts`, `speeds`, `effort`, `speed`, `modelMenu`, `targets.modelMenu`), the operations `setEffort`, `setSpeed` and `setModelMenu` with the `effort` and `speed` of `setModel`, and the commands `agentProviders.showModels`, `agentProviders.readModelSettings` and `agentProviders.applyModelSettings` were added last | ✅ | Pending host integration | [Agents](domains/agents.md) | +| `agents` `0` | [`agents[]`](../contract/v1/README.md#agents): native sessions of agent CLIs the user installed (the backend translates the CLI's own protocol and Core starts the process), terminal forms, update commands, and session records; permissions `agents.run`, `agents.native`, `agents.sessions.read`, `agents.usage.read`, activation event `onAgent:`; `acp` is validated but not run. The agent library's `configuration` declaration and the `agents.configuration` permission were added within 0: a Core that does not know them refuses a manifest that declares them with `plugin.manifest.invalid` and answers no `agentLibrary.*` command. Prompt attachments, the `attachments` of `agents.prompt`, and `native.imageTypes` were also added within 0: a Core that does not know them refuses a manifest that declares `imageTypes` the same way, and refuses an `agents.prompt` with `attachments`. `configuration.providers` (models and model providers) and the filter and sort parameters of `agentLibrary.read` were also added within 0: a Core that does not know them refuses a manifest that declares `providers` with `plugin.manifest.invalid`, refuses an `agentLibrary.read` with filters with `agents.invalidPayload`, and answers no `agentProviders.*` command; `configuration.providers.listKeptBy`, the `key`, `clearKey` and `model` of a change, the snapshot's `keySet` and `model`, and `agentProviders.restore` belong to the same addition; the backups before library changes, `backup` in `agentLibrary.read`, and `agentProviders.restore` for an agent without `providers` were added after it: an older Core backs up only what `agentProviders.apply` changes, gives no such `backup`, and refuses such a restore with `agentProviders.notDeclared`; writing only Lithe's block of the instruction file, the sets' `on` and `agents`, the `instructions` a `save` answers, the `import` of `agentLibrary.apply` and the `unfollowed` of a restore were added after that; `terminal.resumeArguments`, `threads` from `scan`, `agentSessions.resume`, `export` and `subagents`, `resumable` and the group `category` of the list, and `snippets` of the search are additions within 0 as well: an older Core rejects a manifest that declares `resumeArguments` with `plugin.manifest.invalid`, never asks `scan` for `threads`, and answers none of the three commands; the models a plugin lists in the `providers` snapshot (`models`, `efforts`, `speeds`, `effort`, `speed`, `modelMenu`, `targets.modelMenu`), the operations `setEffort`, `setSpeed` and `setModelMenu` with the `effort` and `speed` of `setModel`, and the commands `agentProviders.showModels`, `agentProviders.readModelSettings` and `agentProviders.applyModelSettings` were added after that; `configuration.mcpServers`, the environment variables and headers (write-only values), note, switch, `pausedAgents`, tools left out, timeouts and icon of a library MCP server, the values, switch, tools left out and timeouts `configuration.read` reports, the declared fields of a server `edit` receives, the server `import` of `agentLibrary.apply`, `agentLibrary.parseServers`, and the `directory`, `stateDetails`, `found` and `mcpServerSupport` of `agentLibrary.read` were added last | ✅ | Pending host integration | [Agents](domains/agents.md) | | `toolDefinitions` `0` | `toolDefinitions[]`: [tool identities, layouts, discovery, and four-layer candidates](../contract/v1/toolchains/README.md) | ✅ | ✅¹ | [Toolchains](domains/toolchains.md) | | `toolDefinitions` `1` | Adds to `0`: a definition's `category` (its group in the settings page's Toolchains list) and `audience` (`plugin` for a runtime a plugin runs for itself, shown in its own last group); display placement only | ✅ | Not declared | [Settings list](../contract/v1/toolchains/README.md#settings-list) | | `toolchainProviders` `0` | `toolchainProviders[]`: [provider declarations and permission-bound answer validation](../contract/v1/toolchains/README.md); they speak `litheToolchains` | ✅ | ✅ | [Toolchains](domains/toolchains.md) | diff --git a/shared/plugins/reference/domains/agents.md b/shared/plugins/reference/domains/agents.md index 55dfd42d..27a0e0d4 100644 --- a/shared/plugins/reference/domains/agents.md +++ b/shared/plugins/reference/domains/agents.md @@ -58,13 +58,28 @@ Core 区分三种输入:默认 `send` 在空闲且队列为空时开始新轮 宿主的 Agent 资源库把指令、技能、MCP 服务器和 Hooks 存一份,用户按 Agent 开关后,Core 写进每个 CLI 自己的配置。插件只声明 `configuration`: - `instructions`、`skills`:CLI 读取的用户指令文件和用户技能目录。Core 自己读写它们:指令文件里 Core 只写自己的一块(见下面的“指令文件”),块外的文字都是用户的、逐字节保留;技能以符号链接放进技能目录,资源库外的技能只显示、不改。 -- `files` 和 `read`、`edit`:保存 MCP 服务器和 Hooks 的 CLI 配置文件。只有后端认识它们的格式:`read` 报告文件里有哪些服务器和 Hooks(环境变量和请求头只给名称),`edit` 只改 Core 给的暂存副本,并保留文件里其他内容;Core 校验后用原子替换写回,文件在此期间被改动就拒绝。 +- `files` 和 `read`、`edit`:保存 MCP 服务器和 Hooks 的 CLI 配置文件。只有后端认识它们的格式:`read` 报告文件里有哪些服务器和 Hooks,`edit` 只改 Core 给的暂存副本,并保留文件里其他内容;Core 校验后用原子替换写回,文件在此期间被改动就拒绝。 +- `mcpServers`:CLI 的 MCP 服务器能保存什么。`transports` 是 CLI 支持的连接方式(`stdio`、`http`、`sse`,不写就是全部);`fields` 是 CLI 能保存的额外字段:`environment`(环境变量)、`headers`(请求头)、`enabled`(开关)、`disabledTools`(禁用的工具)、`startupTimeout`、`callTimeout`(启动和单次调用超时),不写就是一个都不保存。Core 只往 Agent 里写它声明的字段,见下面的“MCP 服务器”。 - CLI 自己装的内容(比如 CLI 插件带来的 MCP 服务器、Hooks 和技能)标为 `origin: "agent"`,宿主只显示、不改。 - 宿主按插件声明的 `displayName` 和 `icon` 显示每个 Agent,不按名字特殊处理。 所有改动都只能由用户的操作发起;Core 只读写声明的路径;插件没有获得 `agents.configuration` 授权时,它的 Agent 以 `mayConfigure: false` 列出,Core 什么都不读、不改。Core 替换指令文件或配置文件之前都先备份,见下面的“修改前备份与恢复”。命令见 Rust Core API 的 `agentLibrary.*`。 -`agentLibrary.read` 可以带可选参数 `query`(名称、描述等文字,忽略大小写)、`agent` 加 `presence`(`present` 或 `missing`,两者一起给)和 `sort`(`name` 或 `agentCount`)。不带参数时结果和以前完全一样;带了参数,资源库本身仍完整返回(`save` 要整份替换),另加 `matches`,按顺序列出留下的 MCP 服务器名、Hook `id` 和技能名。 +`agentLibrary.read` 可以带可选参数 `query`(名称、备注、描述等文字,忽略大小写)、`agent` 加 `presence`(`present` 或 `missing`,两者一起给)和 `sort`(`name` 或 `agentCount`)。不带参数时结果和以前完全一样;带了参数,资源库本身仍完整返回(`save` 要整份替换),另加 `matches`,按顺序列出留下的 MCP 服务器名、Hook `id` 和技能名。`read` 还回答资源库目录 `directory`、每一项按 Agent 的状态原因 `stateDetails`,以及 Agent 里有、资源库里没有的条目分组 `found`(见下面的“只在 Agent 里的条目”)。 + +### MCP 服务器 + +资源库的服务器除了名称、连接方式、命令、参数和 URL,还可以有环境变量 `environment` 或请求头 `headers`(`{name, value?}`)、备注 `note`、开关 `enabled`、`pausedAgents`(关掉时被拿掉的 Agent,打开时再放回)、禁用的工具 `disabledTools`、启动和单次调用超时(秒),以及图标 `icon`(`{type, data}`,PNG、JPEG、GIF 或 WebP,Base64 解码后不超过 32 KiB,Core 不联网取图标)。备注、图标和 `pausedAgents` 只留在资源库里。 + +- **值只写不读**:环境变量和请求头的值存在 `library.json`(只有所有者可读写)。`read` 只给 `{name, valueSet}`;`save` 里不带 `value` 的变量沿用资源库里同名服务器同名变量的值,改名的服务器用 `renamedFrom` 给出原名。`put` 时把值交给插件的 `edit`,插件的 `read` 也报告值,这样 Core 才能判断 Agent 里是不是资源库的那一份,也能把值一起导入。除了 `parseServers` 的回答,任何回答、拒绝和日志都不带值。 +- **按声明写入**:Agent 不支持的连接方式不写(`agentLibrary.transportUnsupported`);带环境变量或请求头的服务器只写进能保存它们的 Agent(`agentLibrary.fieldUnsupported`),且每个都要有值(`agentLibrary.valueMissing`);关掉的服务器只以 `enabled: false` 写进能保存开关的 Agent,别的 Agent 不写(`agentLibrary.serverOff`),由宿主 `remove` 并记进 `pausedAgents`;禁用的工具和超时只写给能保存的 Agent,否则略过,并在 `stateDetails` 的 `unsupportedFields` 里列出。 +- **状态**:`on` 是 Agent 里同名服务器就是 `put` 会写的那一份(只比较 Agent 能保存的字段);`conflict` 是同名但不同;`unsupported` 是 Agent 没有、也放不进去(`reason` 给出原因);其余是 `off`。 +- **从 Agent 导入**:`apply` 的 `{category: "mcpServers", op: "import", name, revision}` 把 Agent 的服务器连同值一起放进资源库,不改 Agent 的文件;资源库已有同名是 `agentLibrary.serverExists`,满了是 `agentLibrary.libraryFull`。 +- **粘贴解析**:`agentLibrary.parseServers {text}` 把用户粘贴的 JSON(可带注释和末尾逗号,也可以只是一个 `"名称": {…}` 成员)解析成 `save` 用的服务器,不保存。支持 `mcpServers`、`servers`、`context_servers`、`mcp` 下的服务器表、单个服务器对象、服务器数组和名称到服务器的对象;语法错误给出行和列(按字符计),条目问题给出 JSON 指针和原因。 + +### 只在 Agent 里的条目 + +`read` 的 `found` 把 Agent 里有、资源库里没有的条目按项归组,宿主不用自己再比:MCP 服务器按名称,Hooks 按事件、匹配器、命令和超时,技能按名称(先是技能目录里的,再是 CLI 自己装的)。每组列出各 Agent 的副本和它是第几种写法(`variant`),资源库有同名项时标出副本和资源库那份是否不同(`differsFromLibrary`),并说明能否导入、从哪个 Agent 导入(`importFrom`)或为什么不能(`reason`)。两个副本只差在值上也算两种写法,但组里不带值。 ### 指令文件 @@ -121,6 +136,9 @@ Core 替换 Agent 的任何一个文件之前,都先把它备份到资源库 | [Native sessions](../../contract/v1/README.md#native-sessions) | 启动流程、通知、宿主方法、会话事件 | | [Session records](../../contract/v1/README.md#session-records) | 会话来源、`scan` 与 `read` 函数、汇总和拒绝码 | | [Agent configuration](../../contract/v1/README.md#agent-configuration) | `configuration` 声明、资源库的存储、命令和筛选、`read` 与 `edit` 函数、限制和拒绝码 | +| [MCP servers](../../contract/v1/README.md#mcp-servers) | 服务器的额外字段、值的只写规则、按声明写入、状态和从 Agent 导入 | +| [Found items](../../contract/v1/README.md#found-items) | 只在 Agent 里的条目怎么分组、比较和导入 | +| [Pasted servers](../../contract/v1/README.md#pasted-servers) | `agentLibrary.parseServers` 支持的写法和问题原因 | | [Instruction files](../../contract/v1/README.md#instruction-files) | 指令文件里 Lithe 的块、状态、保存后同步、并入资源库和已有数据的迁移 | | [Models and providers](../../contract/v1/README.md#models-and-providers) | `configuration.providers`、`agentProviders.*` 命令、快照与修改、隐私规则和拒绝码 | | [Backups and restore](../../contract/v1/README.md#backups-and-restore) | 资源库和供应商修改前的备份、`backup` 状态、`agentProviders.restore` 与拒绝码 | @@ -214,13 +232,28 @@ and the [shared Core/desktop fixture](../../../../rust/fixtures/agents/turn-inte The host's agent library keeps one copy of instructions, skills, MCP servers and hooks; once the user turns them on per agent, Core writes them into each CLI's own configuration. The plugin only declares `configuration`: - `instructions` and `skills`: the user instruction file and the user skills directory the CLI reads. Core reads and writes them itself: in the instruction file it writes only its own block (see "Instruction files" below), and every line outside it is the user's and kept byte for byte; it puts skills into the skills directory as symbolic links. Skills outside the library are shown and never changed. -- `files` with `read` and `edit`: the CLI configuration files that hold MCP servers and hooks. Only the backend knows their format. `read` reports the servers and hooks a file holds (names only for environment variables and headers), and `edit` changes only the staged copy Core gives it and keeps everything else in the file. Core checks the copy and replaces the file atomically, refusing when the file changed meanwhile. +- `files` with `read` and `edit`: the CLI configuration files that hold MCP servers and hooks. Only the backend knows their format. `read` reports the servers and hooks a file holds, and `edit` changes only the staged copy Core gives it and keeps everything else in the file. Core checks the copy and replaces the file atomically, refusing when the file changed meanwhile. +- `mcpServers`: what the CLI's MCP servers can hold. `transports` lists the transports the CLI connects with (`stdio`, `http`, `sse`; absent is all), and `fields` the further fields it keeps: `environment` (environment variables), `headers`, `enabled` (the switch), `disabledTools`, `startupTimeout` and `callTimeout`; absent is none. Core writes into the agent only the fields it declares; see "MCP servers" below. - What the CLI installed itself, such as the MCP servers, hooks and skills a CLI plugin brings, has `origin: "agent"`; the host shows it and never changes it. - The host shows each agent by the `displayName` and `icon` its plugin declares and never special-cases agents by name. Every change comes only from a user action. Core reads and writes only the declared paths. An agent whose plugin is not granted `agents.configuration` is listed with `mayConfigure: false`, and Core reads and changes nothing of it. Core backs up an instruction or configuration file before replacing it; see "Backups before a change, and restore" below. The commands are the `agentLibrary.*` commands of the Rust Core API. -`agentLibrary.read` takes optional `query` (text in a name, description and so on, ignoring case), `agent` with `presence` (`present` or `missing`, given together) and `sort` (`name` or `agentCount`). Without them the answer is exactly as before; with them the library still comes whole, since `save` replaces all of it, and `matches` lists the kept MCP server names, hook `id`s and skill names in order. +`agentLibrary.read` takes optional `query` (text in a name, note, description and so on, ignoring case), `agent` with `presence` (`present` or `missing`, given together) and `sort` (`name` or `agentCount`). Without them the answer is exactly as before; with them the library still comes whole, since `save` replaces all of it, and `matches` lists the kept MCP server names, hook `id`s and skill names in order. `read` also answers the library directory `directory`, why each item is in its state for each agent (`stateDetails`), and the groups of what agents hold outside the library (`found`; see "Items only in agents" below). + +### MCP servers + +Beyond its name, transport, command, arguments and URL, a library server may have environment variables `environment` or headers `headers` (`{name, value?}`), a note `note`, a switch `enabled`, `pausedAgents` (the agents it was taken out of when switched off, to put it back into when switched on), the tools agents leave out `disabledTools`, startup and per-call timeouts in seconds, and an icon `icon` (`{type, data}`: PNG, JPEG, GIF or WebP, at most 32 KiB decoded from Base64; Core fetches no icon). The note, the icon and `pausedAgents` stay in the library. + +- **Values are write-only**: the values of variables and headers are kept in `library.json`, owner-only. `read` gives only `{name, valueSet}`; in a `save`, a variable without `value` keeps the value the library has for the same variable of the server of the same name, and a renamed server gives its old name as `renamedFrom`. A `put` hands the values to the plugin's `edit`, and the plugin's `read` reports them too, so Core can tell whether the agent holds the library's server and can import it with its values. No answer but that of `parseServers`, no refusal and no log carries a value. +- **Written as declared**: a server whose transport the agent does not take is not written (`agentLibrary.transportUnsupported`); one with variables or headers goes only to an agent that keeps them (`agentLibrary.fieldUnsupported`), and only when each has a value (`agentLibrary.valueMissing`); a switched-off server goes as `enabled: false` only to an agent that keeps the switch and to no other (`agentLibrary.serverOff`), which the host takes it out of with `remove` and notes in `pausedAgents`; tools left out and timeouts go only to an agent that keeps them, are left out otherwise, and are listed in `unsupportedFields` of `stateDetails`. +- **States**: `on` when the agent's server of that name is what a `put` writes (comparing only the fields the agent keeps); `conflict` when it differs; `unsupported` when the agent has none and cannot take it (`reason` says why); otherwise `off`. +- **Importing from an agent**: `apply` with `{category: "mcpServers", op: "import", name, revision}` takes the agent's server with its values into the library without changing the agent's files; a server of that name already in the library is `agentLibrary.serverExists`, a full library `agentLibrary.libraryFull`. +- **Pasted text**: `agentLibrary.parseServers {text}` reads the JSON the user pasted (comments and trailing commas allowed, or just one `"name": {…}` member) into servers in the shape `save` takes, and saves nothing. It reads the server maps under `mcpServers`, `servers`, `context_servers` and `mcp`, one server object, an array of servers, and an object of servers by name; a syntax error gives its line and column (in characters), and a problem with an entry its JSON pointer and reason. + +### Items only in agents + +`found` in `read` groups what agents hold outside the library, so the host compares nothing itself: MCP servers by name, hooks by event, matcher, command and timeout, skills by name (the skills directories first, then what the CLIs installed). Each group lists each agent's copy and which distinct copy it is (`variant`), marks, when the library has an item of the name, whether the copy differs from it (`differsFromLibrary`), and says whether the library can import it and from which agent (`importFrom`) or why not (`reason`). Two copies that differ only in a value are two variants, and no group carries a value. ### Instruction files @@ -277,6 +310,9 @@ Before Core replaces any of an agent's files, it backs the file up under `backup | [Native sessions](../../contract/v1/README.md#native-sessions) | Launch flow, notifications, host methods, session events | | [Session records](../../contract/v1/README.md#session-records) | Session sources, the `scan` and `read` functions, totals, and refusal codes | | [Agent configuration](../../contract/v1/README.md#agent-configuration) | The `configuration` declaration, the library's storage, commands and filters, the `read` and `edit` functions, limits, and refusal codes | +| [MCP servers](../../contract/v1/README.md#mcp-servers) | A server's further fields, write-only values, writing by declaration, states, and importing from an agent | +| [Found items](../../contract/v1/README.md#found-items) | How items only in agents are grouped, compared and imported | +| [Pasted servers](../../contract/v1/README.md#pasted-servers) | The shapes `agentLibrary.parseServers` reads and its problem reasons | | [Instruction files](../../contract/v1/README.md#instruction-files) | Lithe's block in the instruction file, its states, the sync after a save, import, and how existing data is migrated | | [Models and providers](../../contract/v1/README.md#models-and-providers) | `configuration.providers`, the `agentProviders.*` commands, snapshots and changes, privacy rules, and refusal codes | | [Backups and restore](../../contract/v1/README.md#backups-and-restore) | Backups before library and providers changes, the `backup` status, `agentProviders.restore` and its refusal codes | diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 1139c36a..ddad4660 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -18,7 +18,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改动 | | --- | --- | --- | --- | --- | -| [#263](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/263)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 插件可在 `configuration.providers` 的 `read` 快照里列出 Agent 能用的模型 `models`(每项 `{id, name?, provider?, efforts?, defaultEffort?, speeds?, defaultSpeed?, contextWindow?, description?}`,最多 512 个),以及 CLI 提供的推理强度 `efforts`、速度档 `speeds`(各最多 16 个,每项 `{id, name?}`)、正在用的 `effort`、`speed`(`{id, source?}`)、CLI 自己的模型菜单 `modelMenu` 和写它的文件 `targets.modelMenu`;插件不列就没有,宿主和 Core 不内置任何模型名单。`configuration.providers.operations` 新增 `setEffort`、`setSpeed`、`setModelMenu`,`setModel` 可带 `effort`、`speed`(插件也声明了 `setEffort`、`setSpeed` 时);有清单时 Core 在调用插件前检查选择在清单里、组合是模型支持的,换模型时保留的强度和速度也要新模型支持(来源层是 `default` 的不查),新增错误码 `agentProviders.unknownModel`、`agentProviders.unknownEffort`、`agentProviders.unknownSpeed`、`agentProviders.unsupportedCombination`。`setModelMenu` 只由 Core 发给插件,宿主经 `agentProviders.apply` 发它以 `agentProviders.invalidChange` 拒绝。`agentProviders.read` 总是回答 `models`,每项带 `shown`。新增宿主命令 `agentProviders.showModels {agent, show?, hide?}`:用户隐藏的模型按隐藏顺序记在资源库目录的 `models.json`(仅所有者可读写),默认全部显示,插件新加的模型也显示,插件去掉的模型保留记录,每个 Agent 最多 1024 条,超出先丢最早的、已不在清单里的;插件声明 `setModelMenu` 时 Core 经暂存副本让插件把显示的模型写进 CLI 的菜单,写失败把开关放回,不声明时开关只影响 Lithe 的选择器。新增 `agentProviders.readModelSettings {agent}` 和 `agentProviders.applyModelSettings {agent, settings}`,把开关和模型、强度、速度作为一组读出和写回(写回先全部检查,一个被拒就都不改),供以后的模型方案使用。日志 `agent.providers.change_applied`、`agent.providers.change_failed` 的 `change` 新增取值 `showModels`、`applyModelSettings`。样例见 `contract/v1/fixtures/agents/model-catalog.json`。插件函数 `edit` 新增上述操作,`read` 回答新增上述字段;没有新增插件可调用的宿主方法、通知或能力版本,四语 SDK 不改代码,只更新说明。 | +| [#264](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/264)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 资源库的 MCP 服务器补齐字段:清单新增 `agents[].configuration.mcpServers {transports?, fields?}`,插件声明 CLI 支持的连接方式(`stdio`、`http`、`sse`,不写为全部)和能保存的字段(`environment`、`headers`、`enabled`、`disabledTools`、`startupTimeout`、`callTimeout`,不写为都不保存),需要 `read`,安装审查和目录条目列出它。资源库服务器新增 `environment`、`headers`(`{name, value?}`)、`note`、`enabled`、`pausedAgents`、`disabledTools`、`startupTimeoutSeconds`、`callTimeoutSeconds`、`icon`(PNG/JPEG/GIF/WebP,解码后不超过 32 KiB,不联网取);值存在 `library.json`,Core 总以仅所有者可读写写入,`agentLibrary.read` 只回答 `{name, valueSet}`,`save` 不带值的变量沿用原值、改名用 `renamedFrom`,回答、拒绝和日志都不带值。插件函数参数:`configuration.read` 的服务器新增 `environment`、`headers`(带值)、`enabled`、`disabledTools`、`startupTimeoutSeconds`、`callTimeoutSeconds`,原来只报名字的 `environmentNames`、`headerNames` 仍可用、两者不能同时给;`configuration.edit` 的 `put` 服务器只带插件声明的字段,声明了 `environment`/`headers` 时带值,声明了 `enabled` 时总带开关。宿主命令:新增 `agentLibrary.parseServers {text}`(解析粘贴的 JSON,回答 `{servers, problems}`,不保存);`agentLibrary.apply` 新增 `{category: "mcpServers", op: "import", name, revision}`(连同值从 Agent 导入,不改 Agent,回答 `{changed, revision}`);`agentLibrary.read` 新增 `directory`、`stateDetails`(`reason`、`unsupportedFields`)、`found`(只在 Agent 里的服务器、Hooks、技能分组,标出不同写法、与资源库是否不同、能否导入及原因)、Agent 条目的 `mcpServerSupport`,服务器状态改为比较 `put` 实际写入的内容,`query` 也匹配服务器备注。新增错误码 `agentLibrary.transportUnsupported`、`agentLibrary.fieldUnsupported`、`agentLibrary.valueMissing`、`agentLibrary.serverOff`(放不进 Agent 的原因)、`agentLibrary.serverExists`、`agentLibrary.libraryFull`(导入)、`agentLibrary.textTooLarge`(粘贴超过 256 KiB)、`agentLibrary.libraryTooLarge`(保存后的 `library.json` 会超过 Core 能读回的 8 MiB)。没有新增插件可调用的宿主方法、通知、日志事件或能力版本;四语 SDK 的 API 不变,SDK 文档改为说明读取时报告值。 | ## 按协议查首次出现 @@ -241,6 +241,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改动 | | --- | --- | --- | --- | --- | +| [#263](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/263) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 插件可在 `configuration.providers` 的 `read` 快照里列出 Agent 能用的模型 `models`(每项 `{id, name?, provider?, efforts?, defaultEffort?, speeds?, defaultSpeed?, contextWindow?, description?}`,最多 512 个),以及 CLI 提供的推理强度 `efforts`、速度档 `speeds`(各最多 16 个,每项 `{id, name?}`)、正在用的 `effort`、`speed`(`{id, source?}`)、CLI 自己的模型菜单 `modelMenu` 和写它的文件 `targets.modelMenu`;插件不列就没有,宿主和 Core 不内置任何模型名单。`configuration.providers.operations` 新增 `setEffort`、`setSpeed`、`setModelMenu`,`setModel` 可带 `effort`、`speed`(插件也声明了 `setEffort`、`setSpeed` 时);有清单时 Core 在调用插件前检查选择在清单里、组合是模型支持的,换模型时保留的强度和速度也要新模型支持(来源层是 `default` 的不查),新增错误码 `agentProviders.unknownModel`、`agentProviders.unknownEffort`、`agentProviders.unknownSpeed`、`agentProviders.unsupportedCombination`。`setModelMenu` 只由 Core 发给插件,宿主经 `agentProviders.apply` 发它以 `agentProviders.invalidChange` 拒绝。`agentProviders.read` 总是回答 `models`,每项带 `shown`。新增宿主命令 `agentProviders.showModels {agent, show?, hide?}`:用户隐藏的模型按隐藏顺序记在资源库目录的 `models.json`(仅所有者可读写),默认全部显示,插件新加的模型也显示,插件去掉的模型保留记录,每个 Agent 最多 1024 条,超出先丢最早的、已不在清单里的;插件声明 `setModelMenu` 时 Core 经暂存副本让插件把显示的模型写进 CLI 的菜单,写失败把开关放回,不声明时开关只影响 Lithe 的选择器。新增 `agentProviders.readModelSettings {agent}` 和 `agentProviders.applyModelSettings {agent, settings}`,把开关和模型、强度、速度作为一组读出和写回(写回先全部检查,一个被拒就都不改),供以后的模型方案使用。日志 `agent.providers.change_applied`、`agent.providers.change_failed` 的 `change` 新增取值 `showModels`、`applyModelSettings`。样例见 `contract/v1/fixtures/agents/model-catalog.json`。插件函数 `edit` 新增上述操作,`read` 回答新增上述字段;没有新增插件可调用的宿主方法、通知或能力版本,四语 SDK 不改代码,只更新说明。 | | [#262](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/262) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 已记录会话的五项补充,对 Agent 的会话文件都只读。**恢复命令**:清单 `agents[].terminal` 新增可选 `resumeArguments`(1–64 个参数,至少含一次 `${sessionID}`,不得有其他 `${`),安装审查的终端程序随之列出模板;宿主命令 `agentSessions.resume {agent, sessionID, toolPath, shell?}` 回答 `{pluginID, agentID, sessionID, executable, arguments, shell, cwd?, commandLine?}`,`commandLine` 按 `posix` 或 `powershell`(默认随宿主平台)转义;Core 只接受由字母、数字、`.`、`_`、`:`、`-` 组成、不以 `-` 开头、最长 256 字节的会话 ID;需要 `agents.run`,宿主用已有终端形式运行,不新增执行通道。`agentSessions.list` 的会话新增 `resumable`。**导出**:宿主命令 `agentSessions.export {agent, sessionID, labels, maxBytes?, keep?, utcOffsetSeconds?}` 回答 `{changed, markdown, messages, truncated}`,含用户消息、回复、每次工具调用一行和时间,不含思考和工具输出;`maxBytes` 4 KiB–4 MiB(默认 1 MiB),`keep` 为 `start` 或 `end`,最多读源文件 64 MiB。导出里的文字全部来自必填的 `labels`(`untitled`、`agent`、`session`、`directory`、`started`、`lastActive`、`timeZone`、`user`、`assistant`、`tool`、`failed`、`earlierOmitted`、`laterOmitted`,各 1–256 字节、不含控制字符),宿主按界面语言传入,Core 不带默认文字;缺少、多出或不合法的标签以 `agentSessions.invalidExport` 拒绝。**子代理**:`scan` 请求新增可选 `threads: true`,只有这时后端才可回答 `threads`(`{sessionID, threadID, parentThreadID?, kind?, startedAtMs?, updatedAtMs?, titleRange?}`);宿主命令 `agentSessions.subagents {agent, sessionID}` 合并线程描述和带 `threadID` 的调用,回答每个子代理的调用行与用量汇总,插件不报告时为空列表。**其他文件夹**:`agentSessions.list` 的 `groups` 新增 `category`(`root`、`temporary`、`hidden`),按路径形式套用 macOS、Linux、Windows 规则,共享用例 `rust/fixtures/agents/folder-categories-v1.json`。**搜索片段**:`agentSessions.search` 新增可选 `snippets: true`,命中带 `snippet`(第一个命中词前 36 个字符到其后 120 个字符,截断处加 `…`)和 `snippetMatches`(片段内的 UTF-8 字节区间,多词、不分大小写、重叠或相接的合并),匹配规则与搜索索引相同;单个命中超过 256 KiB 或一次搜索累计超过 4 MiB 时不给片段、不报错。`agentSessions.read`、`agentSessions.page` 对拆不开的 `agent` 键也回答 `agentSessions.unknownAgent` 和 `entry_not_found`(此前 `read` 回答 `invalid_request`,`page` 回答 `agentSessions.invalidPage`),与新命令一致,一个错误码只对应一个数字码。新增错误码 `agentSessions.unknownSession`、`agentSessions.runNotGranted`、`agentSessions.toolNotFound`、`agentSessions.noResume`、`agentSessions.unsafeResume`、`agentSessions.invalidExport`。旧 Core 以 `plugin.manifest.invalid` 拒绝声明 `resumeArguments` 的清单,不发送 `threads`、严格拒绝回答里的 `threads`,把三个新命令当未知命令、把 `snippets` 当未知字段拒绝。`scan`、`read` 仍是普通 JSON 函数,四语 SDK 无类型或版本变化;新增日志事件 `agent.session.cleanup_failed`(启动失败或会话结束后停不掉的 Agent CLI,带 Core 错误码,不带参数或输出)和 `agent.records.rate_limits_save_failed`(额度快照写入或换名失败,只带步骤和文件系统错误类别,不带路径);`agents/didExit` 通知发不出去时记 `agent.interaction.failed`。没有新增插件可调用的宿主方法、通知或能力版本。样例见 `fixtures/agents/agents.plugin.json` 与 `fixtures/manifest/invalid-manifests.json`。 | | [#261](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/261) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 资源库的指令改为只写指令文件里 Lithe 标记的一块(`` 到 ``):块外用户文字逐字节保留,新块追加在用户文字之后,资源库文字里的标记行写成失效形式,多余的块和落单的标记行被清掉,指令为空时去掉整块,重复写入不变大;`state.json` 改记块内文字的哈希,旧 Core 整份写过且哈希一致的文件下次写成只有块,其他没有块的文件当作用户文字直接追加,不需确认。指令集新增可选 `on`、`agents`(空为所有 Agent),按 `sets` 顺序拼接后加 Agent 的 `extra`;去掉 `active`:读取带 `active` 的旧 `library.json` 时换成“该套开、其余关”,拼接结果逐字节不变,`save` 带 `active` 以 `agentLibrary.invalidLibrary` 拒绝。宿主命令 `agentLibrary.read` 的 `instructions.state` 改为 `absent`、`noBlock`、`current`、`stale`、`edited`、`tooLarge`、`unreadable`,新增 `ownLines`(块外用户文字行数);`agentLibrary.save` 回答新增 `instructions`:保存后 Core 给每个跟随的 Agent 写块,逐个回答 `written`、`unchanged`、`skipped`(带 `reason`)或 `failed`(带 `reason`),不覆盖用户改过的块;`agentLibrary.apply` 新增 `{category: "instructions", op: "import", id, name?, revision, replace?}`,把块外用户文字并入新建或已有的一套,先备份,文件只剩块,回答 `{changed, revision, instructions}`;`agentLibrary.otherInstructions` 收窄为“块里有不是 Lithe 写的内容”。`agentProviders.restore` 放回指令文件时关掉该 Agent 的跟随,回答新增 `unfollowed`,日志 `agent.providers.restore_applied` 新增字段 `unfollowed`。新增错误码 `agentLibrary.setExists`(并入时新建的一套 `id` 已存在)。新增日志事件 `agent.library.cleanup_failed`:资源库删不掉不再需要的文件(写入失败留下的临时文件、暂存副本、导入一半的技能、备份基线或历史),或失败后放不回备份记录时记录,只带对象种类和文件系统错误类别,不带路径。样例见 `rust/fixtures/agents/library-instructions-v1.json`。没有新增插件可调用的宿主方法、通知、插件函数参数或能力版本,插件后端协议和四语 SDK 不变。 | | [#260](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/260) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 资源库的修改替换 Agent 的文件前也先备份,和 `agentProviders.apply` 共用同一份备份。`agentLibrary.apply` 为 MCP 服务器、Hooks 改声明文件,以及整份写入指令文件(包括 `replace: true` 覆盖不是 Lithe 写的内容)之前先备份,备份不成功就不写文件,复用已有错误码 `agentProviders.backupFailed`;技能的符号链接不覆盖内容,不备份。同一个文件无论资源库还是供应商先改,都只存一份“自上次恢复以来 Lithe 第一次修改前的原样”(按第一个解析到该路径的声明文件归并,指令文件不是声明文件时单独一项)。宿主命令 `agentLibrary.read` 的每个 Agent 新增可选 `backup {savedAtMs, modifiedSince}`,和 `agentProviders.read` 的 `backup` 相同;后者现在也覆盖指令文件和资源库的修改。`agentProviders.restore` 不再要求 Agent 声明 `providers`(原来以 `agentProviders.notDeclared` 拒绝),恢复该 Agent 所有备份过的文件;放回指令文件前先忘掉 Core 最后写入的指令哈希,恢复后 `instructions.state` 按文件实际内容显示、不会是 `written`,再写入要重新确认 `replace: true`。旧 Core 只备份 `agentProviders.apply` 的修改,`agentLibrary.read` 不带 `backup`,对不声明 `providers` 的 Agent 的恢复回答 `agentProviders.notDeclared`。没有新增错误码、日志事件、宿主方法、通知、插件函数参数或能力版本,插件后端协议不变。 | diff --git a/shared/plugins/sdk/go/README.md b/shared/plugins/sdk/go/README.md index cd210919..2a91c301 100644 --- a/shared/plugins/sdk/go/README.md +++ b/shared/plugins/sdk/go/README.md @@ -682,11 +682,14 @@ and gives each call 10 seconds. - `read` receives `{agentID, files: [{id, path, exists}]}` and answers the `litheAgentConfiguration` snapshot: the MCP servers, hooks, hook events and self-installed skills the files hold, and which declared file takes the - changes of each category. Report environment variable and header names, - never their values. + changes of each category. For the server fields the agent declares in + [`configuration.mcpServers`](../../contract/v1/README.md#mcp-servers) + report what the files hold, the values of environment variables and + headers included; never log a value or put one in an error. - `edit` receives `{agentID, file: {id, staging, exists}, change}`, changes only the file at `staging` in the CLI's own format, keeps everything else - the file holds, and answers + the file holds (a server `put` carries only the declared fields, values + included), and answers `{format: "litheAgentConfigurationEdit", version: 0, changed}`. Core checks the staged copy and moves it into place; the backend never writes the real file. diff --git a/shared/plugins/sdk/java/README.md b/shared/plugins/sdk/java/README.md index 6d3b2a71..e23adb79 100644 --- a/shared/plugins/sdk/java/README.md +++ b/shared/plugins/sdk/java/README.md @@ -649,11 +649,14 @@ and gives each call 10 seconds. - `read` receives `{agentID, files: [{id, path, exists}]}` and answers the `litheAgentConfiguration` snapshot: the MCP servers, hooks, hook events and self-installed skills the files hold, and which declared file takes the - changes of each category. Report environment variable and header names, - never their values. + changes of each category. For the server fields the agent declares in + [`configuration.mcpServers`](../../contract/v1/README.md#mcp-servers) + report what the files hold, the values of environment variables and + headers included; never log a value or put one in an error. - `edit` receives `{agentID, file: {id, staging, exists}, change}`, changes only the file at `staging` in the CLI's own format, keeps everything else - the file holds, and answers + the file holds (a server `put` carries only the declared fields, values + included), and answers `{format: "litheAgentConfigurationEdit", version: 0, changed}`. Core checks the staged copy and moves it into place; the backend never writes the real file. diff --git a/shared/plugins/sdk/node/README.md b/shared/plugins/sdk/node/README.md index 28da19fd..c04e85d1 100644 --- a/shared/plugins/sdk/node/README.md +++ b/shared/plugins/sdk/node/README.md @@ -662,11 +662,14 @@ and gives each call 10 seconds. - `read` receives `{agentID, files: [{id, path, exists}]}` and answers the `litheAgentConfiguration` snapshot: the MCP servers, hooks, hook events and self-installed skills the files hold, and which declared file takes the - changes of each category. Report environment variable and header names, - never their values. + changes of each category. For the server fields the agent declares in + [`configuration.mcpServers`](../../contract/v1/README.md#mcp-servers) + report what the files hold, the values of environment variables and + headers included; never log a value or put one in an error. - `edit` receives `{agentID, file: {id, staging, exists}, change}`, changes only the file at `staging` in the CLI's own format, keeps everything else - the file holds, and answers + the file holds (a server `put` carries only the declared fields, values + included), and answers `{format: "litheAgentConfigurationEdit", version: 0, changed}`. Core checks the staged copy and moves it into place; the backend never writes the real file. diff --git a/shared/plugins/sdk/rust/README.md b/shared/plugins/sdk/rust/README.md index b9ac12ce..5ae3265a 100644 --- a/shared/plugins/sdk/rust/README.md +++ b/shared/plugins/sdk/rust/README.md @@ -859,11 +859,14 @@ and gives each call 10 seconds. - `read` receives `{agentID, files: [{id, path, exists}]}` and answers the `litheAgentConfiguration` snapshot: the MCP servers, hooks, hook events and self-installed skills the files hold, and which declared file takes the - changes of each category. Report environment variable and header names, - never their values. + changes of each category. For the server fields the agent declares in + [`configuration.mcpServers`](../../contract/v1/README.md#mcp-servers) + report what the files hold, the values of environment variables and + headers included; never log a value or put one in an error. - `edit` receives `{agentID, file: {id, staging, exists}, change}`, changes only the file at `staging` in the CLI's own format, keeps everything else - the file holds, and answers + the file holds (a server `put` carries only the declared fields, values + included), and answers `{format: "litheAgentConfigurationEdit", version: 0, changed}`. Core checks the staged copy and moves it into place; the backend never writes the real file.