Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(registry): validate tool names on config load

Steven Enamakela919eed69ce3
diff --git a/crates/openhuman-core/src/mcp/registry/config_doc.rs b/crates/openhuman-core/src/mcp/registry/config_doc.rs
deleted file mode 100644
index 12767871ba..0000000000
--- a/crates/openhuman-core/src/mcp/registry/config_doc.rs
+++ /dev/null
@@ -1,352 +0,0 @@
-//! The user's MCP servers as one `mcp.json` document.
-//!
-//! Installing a server is not a catalog action any more. The registry tab is
-//! browse-only; a user who found a server there reads its own install page and
-//! declares it here, in the same `{ "mcpServers": { … } }` shape every desktop
-//! MCP client already uses. This module is the contract for that document and
-//! the reconciliation of the install store against it.
-//!
-//! # One store, two notations
-//!
-//! The rows the **Servers** tab renders and the document the **mcp.json** tab
-//! edits are the same `tinymcp` store. [`render`] projects the store into the
-//! document; [`parse`] reads a document back into declarations; and
-//! [`config_ops::mcp_clients_config_set`](super::config_ops) applies the difference. Neither
-//! is an import format that can drift from what is configured.
-//!
-//! # Credentials are write-only
-//!
-//! A stdio server's `env` and an HTTP server's `headers` are secrets. They are
-//! accepted on write and stored in the credential table; a read never echoes a
-//! value, only the names (`envKeys`) and whether anything is stored
-//! (`authConfigured`). An entry saved *without* an `env`/`headers` block
-//! therefore keeps its stored credentials — a round trip cannot silently
-//! de-authenticate a server. A key set to the empty string removes that one
-//! stored value.
-
-use std::collections::BTreeMap;
-
-use serde_json::{json, Map, Value};
-
-use tinymcp_bus::{InstalledServer, Transport};
-
-/// The document's root key.
-pub const ROOT_KEY: &str = "mcpServers";
-
-/// Fields a read echoes for the reader and a write ignores.
-const ECHOED_FIELDS: &[&str] = &["envKeys", "authConfigured"];
-
-/// Fields a write accepts without acting on, because other clients emit them.
-const TOLERATED_FIELDS: &[&str] = &["type", "transport"];
-
-/// Credential names beginning this way are the store's own bookkeeping (the
-/// OAuth refresh bundle) and are neither rendered nor overwritten from here.
-const INTERNAL_KEY_PREFIX: &str = "__";
-
-/// One server as the document declares it, after validation.
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct Declared {
- /// The document key; doubles as the store's `qualified_name`.
- pub name: String,
- /// How the server is dialled.
- pub transport: Transport,
- /// The launcher, for stdio; empty for HTTP.
- pub command: String,
- /// Arguments to the launcher, for stdio.
- pub args: Vec<String>,
- /// Credentials named in this write: stdio `env` or HTTP `headers`.
- ///
- /// `None` when the block was absent, which leaves stored values alone.
- pub credentials: Option<BTreeMap<String, String>>,
- /// Free text shown beside the row.
- pub description: Option<String>,
- /// Whether the server is brought up and exposed.
- pub enabled: bool,
-}
-
-/// Projects the install store into the document.
-///
-/// Servers are keyed by `qualified_name` and sorted, so the same store renders
-/// the same text and a re-save is not an edit. `authConfigured` is derived from
-/// the stored credential names the caller passes in, never from values.
-#[must_use]
-pub fn render(servers: &[InstalledServer], stored_keys: &BTreeMap<String, Vec<String>>) -> Value {
- let mut entries: Vec<&InstalledServer> = servers.iter().collect();
- entries.sort_by(|a, b| a.qualified_name.cmp(&b.qualified_name));
-
- let mut out = Map::new();
- for server in entries {
- let mut entry = Map::new();
- match &server.transport {
- Transport::HttpRemote { url } => {
- entry.insert("url".into(), json!(url));
- }
- _ => {
- entry.insert("command".into(), json!(server.command));
- if !server.args.is_empty() {
- entry.insert("args".into(), json!(server.args));
- }
- }
- }
- if let Some(description) = server.description.as_deref().filter(|d| !d.is_empty()) {
- entry.insert("description".into(), json!(description));
- }
- if !server.enabled {
- entry.insert("enabled".into(), json!(false));
- }
-
- let keys: Vec<&String> = stored_keys
- .get(&server.server_id)
- .map(|keys| {
- keys.iter()
- .filter(|key| !key.starts_with(INTERNAL_KEY_PREFIX))
- .collect()
- })
- .unwrap_or_default();
- if !keys.is_empty() {
- entry.insert("envKeys".into(), json!(keys));
- }
- entry.insert("authConfigured".into(), json!(!keys.is_empty()));
-
- out.insert(server.qualified_name.clone(), Value::Object(entry));
- }
-
- json!({ ROOT_KEY: out })
-}
-
-/// Reads a document into declarations, refusing anything it cannot honour.
-///
-/// The message names the entry and the field, because the text is still on
-/// the user's screen and "invalid document" would send them hunting.
-///
-/// # Errors
-///
-/// Returns a sentence for the first problem found: a missing or non-object
-/// `mcpServers`, an entry that is not an object, an entry with neither or both
-/// of `url` and `command`, a field of the wrong type, or a field this host does
-/// not understand (a `cwd`, say, which the install store cannot carry).
-pub fn parse(doc: &Value) -> Result<Vec<Declared>, String> {
- let Some(root) = doc.as_object() else {
- return Err(format!("mcp.json holds an object with an `{ROOT_KEY}` key"));
- };
- let Some(servers) = root.get(ROOT_KEY) else {
- return Err(format!("no `{ROOT_KEY}` key — every server lives under it"));
- };
- let Some(servers) = servers.as_object() else {
- return Err(format!("`{ROOT_KEY}` maps a server name to its settings"));
- };
-
- let mut declared = Vec::with_capacity(servers.len());
- for (name, entry) in servers {
- let name = name.trim();
- if name.is_empty() {
- return Err("a server needs a name — one entry's key is empty".to_string());
- }
- let Some(entry) = entry.as_object() else {
- return Err(format!(
- "`{name}` holds an object, e.g. {{ \"command\": \"npx\", \"args\": [\"-y\", \"…\"] }} or {{ \"url\": \"https://…\" }}"
- ));
- };
- declared.push(parse_entry(name, entry)?);
- }
- Ok(declared)
-}
-
-/// Reads one entry.
-fn parse_entry(name: &str, entry: &Map<String, Value>) -> Result<Declared, String> {
- for key in entry.keys() {
- let known = matches!(
- key.as_str(),
- "url" | "command" | "args" | "env" | "headers" | "description" | "enabled"
- ) || ECHOED_FIELDS.contains(&key.as_str())
- || TOLERATED_FIELDS.contains(&key.as_str());
- if !known {
- return Err(format!(
- "`{name}` has a `{key}` field this host doesn't understand; it accepts url, headers, command, args, env, description and enabled"
- ));
- }
- }
-
- let url = optional_string(name, entry, "url")?;
- let command = optional_string(name, entry, "command")?;
-
- let (transport, command) = match (url, command) {
- (Some(_), Some(_)) => {
- return Err(format!(
- "`{name}` names both a `url` and a `command`; a server is dialled one way"
- ));
- }
- (Some(url), None) => (Transport::HttpRemote { url }, String::new()),
- (None, Some(command)) => (Transport::Stdio, command),
- (None, None) => {
- return Err(format!(
- "`{name}` needs a `url` (hosted) or a `command` (run locally)"
- ));
- }
- };
-
- let args = match entry.get("args") {
- None | Some(Value::Null) => Vec::new(),
- Some(Value::Array(items)) => items
- .iter()
- .map(|item| {
- item.as_str()
- .map(str::to_string)
- .ok_or_else(|| format!("`{name}`.args holds strings only"))
- })
- .collect::<Result<Vec<_>, _>>()?,
- Some(_) => return Err(format!("`{name}`.args is a list of strings")),
- };
- if matches!(transport, Transport::HttpRemote { .. }) && !args.is_empty() {
- return Err(format!(
- "`{name}` is a hosted server; `args` only apply to a `command`"
- ));
- }
-
- // `env` is the stdio spelling and `headers` the HTTP one; both land in the
- // same credential table, because that is what the transport reads.
- let credential_field = match transport {
- Transport::Stdio => "env",
- _ => "headers",
- };
- let wrong_field = match transport {
- Transport::Stdio => "headers",
- _ => "env",
- };
- if entry.contains_key(wrong_field) {
- return Err(format!(
- "`{name}` takes `{credential_field}`, not `{wrong_field}`, for a `{}` server",
- match transport {
- Transport::Stdio => "command",
- _ => "url",
- }
- ));
- }
- let credentials = match entry.get(credential_field) {
- None | Some(Value::Null) => None,
- Some(Value::Object(values)) => {
- let mut out = BTreeMap::new();
- for (key, value) in values {
- let key = key.trim();
- if key.is_empty() {
- return Err(format!("`{name}`.{credential_field} has an empty key"));
- }
- if key.starts_with(INTERNAL_KEY_PREFIX) {
- return Err(format!(
- "`{name}`.{credential_field}.{key} — names beginning `{INTERNAL_KEY_PREFIX}` are reserved"
- ));
- }
- let Some(value) = value.as_str() else {
- return Err(format!("`{name}`.{credential_field}.{key} holds a string"));
- };
- out.insert(key.to_string(), value.to_string());
- }
- Some(out)
- }
- Some(_) => {
- return Err(format!(
- "`{name}`.{credential_field} maps a name to a string value"
- ))
- }
- };
-
- let description = optional_string(name, entry, "description")?;
- let enabled = match entry.get("enabled") {
- None | Some(Value::Null) => true,
- Some(Value::Bool(flag)) => *flag,
- Some(_) => return Err(format!("`{name}`.enabled is true or false")),
- };
-
- Ok(Declared {
- name: name.to_string(),
- transport,
- command,
- args,
- credentials,
- description,
- enabled,
- })
-}
-
-/// A string field that may be absent, refusing a blank or non-string one.
-fn optional_string(
- name: &str,
- entry: &Map<String, Value>,
- key: &str,
-) -> Result<Option<String>, String> {
- match entry.get(key) {
- None | Some(Value::Null) => Ok(None),
- Some(Value::String(value)) => {
- let trimmed = value.trim();
- if trimmed.is_empty() {
- return Err(format!("`{name}`.{key} is empty"));
- }
- Ok(Some(trimmed.to_string()))
- }
- Some(_) => Err(format!("`{name}`.{key} holds a string")),
- }
-}
-
-/// Whether a declaration describes the same dial as an install row.
-///
-/// Credentials are not compared: they are write-only, so a declaration cannot
-/// know what is stored, and a re-save must not read as a change.
-#[must_use]
-pub fn same_dial(declared: &Declared, server: &InstalledServer) -> bool {
- declared.transport == server.transport
- && declared.command == server.command
- && declared.args == server.args
- && declared.description.as_deref().unwrap_or_default()
- == server.description.as_deref().unwrap_or_default()
- && declared.enabled == server.enabled
-}
-
-/// Builds the install row a declaration becomes.
-///
-/// `server_id` is the caller's: a fresh id for a new server, the existing one
-/// for a server being rewritten in place, so the row the frontend and the
-/// connection map address stays the same row.
-#[must_use]
-pub fn to_installed(declared: &Declared, server_id: String, installed_at: i64) -> InstalledServer {
- let command_kind = tinymcp::transport::stdio::spawn_env::required_runtime(&declared.command);
- InstalledServer {
- server_id,
- qualified_name: declared.name.clone(),
- display_name: declared.name.clone(),
- description: declared.description.clone(),
- icon_url: None,
- command_kind,
- command: declared.command.clone(),
- args: declared.args.clone(),
- env_keys: Vec::new(),
- config: None,
- installed_at,
- last_connected_at: None,
- transport: declared.transport.clone(),
- enabled: declared.enabled,
- }
-}
-
-/// Merges a write's credentials over what is stored.
-///
-/// A non-empty value replaces; an empty string removes; a name the write did
-/// not mention is kept. Internal bookkeeping is never touched.
-#[must_use]
-pub fn merge_credentials(
- stored: &BTreeMap<String, String>,
- written: &BTreeMap<String, String>,
-) -> BTreeMap<String, String> {
- let mut merged = stored.clone();
- for (key, value) in written {
- if value.is_empty() {
- merged.remove(key);
- } else {
- merged.insert(key.clone(), value.clone());
- }
- }
- merged
-}
-
-#[cfg(test)]
-#[path = "config_doc_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/mcp/registry/config_doc_tests.rs b/crates/openhuman-core/src/mcp/registry/config_doc_tests.rs
deleted file mode 100644
index f8547aa1df..0000000000
--- a/crates/openhuman-core/src/mcp/registry/config_doc_tests.rs
+++ /dev/null
@@ -1,249 +0,0 @@
-//! The `mcp.json` contract: what a read shows, what a write accepts, and what
-//! counts as a change.
-
-use std::collections::BTreeMap;
-
-use serde_json::json;
-use tinymcp_bus::{CommandKind, InstalledServer, Transport};
-
-use super::*;
-
-fn stdio_row(name: &str) -> InstalledServer {
- InstalledServer {
- server_id: format!("id-{name}"),
- qualified_name: name.to_string(),
- display_name: name.to_string(),
- description: None,
- icon_url: None,
- command_kind: CommandKind::Node,
- command: "npx".to_string(),
- args: vec!["-y".to_string(), "@x/y".to_string()],
- env_keys: vec![],
- config: None,
- installed_at: 1,
- last_connected_at: None,
- transport: Transport::Stdio,
- enabled: true,
- }
-}
-
-fn http_row(name: &str) -> InstalledServer {
- InstalledServer {
- transport: Transport::HttpRemote {
- url: "https://x.test/mcp".to_string(),
- },
- command: String::new(),
- args: vec![],
- ..stdio_row(name)
- }
-}
-
-// ── render ───────────────────────────────────────────────────────────────────
-
-#[test]
-fn a_read_shows_the_dial_and_never_a_credential_value() {
- let mut keys = BTreeMap::new();
- keys.insert(
- "id-a".to_string(),
- vec!["API_KEY".to_string(), "__oauth".to_string()],
- );
- let doc = render(&[stdio_row("a"), http_row("b")], &keys);
-
- assert_eq!(
- doc,
- json!({
- "mcpServers": {
- "a": {
- "command": "npx",
- "args": ["-y", "@x/y"],
- "envKeys": ["API_KEY"],
- "authConfigured": true,
- },
- "b": {
- "url": "https://x.test/mcp",
- "authConfigured": false,
- }
- }
- })
- );
-}
-
-#[test]
-fn a_read_is_sorted_and_says_when_a_server_is_off() {
- let mut off = stdio_row("zeta");
- off.enabled = false;
- off.description = Some("the last one".to_string());
- let doc = render(&[off, stdio_row("alpha")], &BTreeMap::new());
- let names: Vec<&String> = doc["mcpServers"].as_object().unwrap().keys().collect();
- assert_eq!(names, ["alpha", "zeta"]);
- assert_eq!(doc["mcpServers"]["zeta"]["enabled"], json!(false));
- assert_eq!(
- doc["mcpServers"]["zeta"]["description"],
- json!("the last one")
- );
- assert!(doc["mcpServers"]["alpha"].get("enabled").is_none());
-}
-
-// ── parse ────────────────────────────────────────────────────────────────────
-
-#[test]
-fn a_write_reads_both_spellings() {
- let declared = parse(&json!({
- "mcpServers": {
- "local": { "command": "uvx", "args": ["thing"], "env": { "TOKEN": "t" } },
- "hosted": { "type": "http", "url": "https://h.test/mcp", "headers": { "Authorization": "Bearer x" }, "enabled": false },
- }
- }))
- .unwrap();
-
- let local = declared.iter().find(|d| d.name == "local").unwrap();
- assert_eq!(local.transport, Transport::Stdio);
- assert_eq!(local.command, "uvx");
- assert_eq!(local.args, ["thing"]);
- assert_eq!(
- local.credentials.as_ref().unwrap().get("TOKEN").unwrap(),
- "t"
- );
- assert!(local.enabled);
-
- let hosted = declared.iter().find(|d| d.name == "hosted").unwrap();
- assert_eq!(
- hosted.transport,
- Transport::HttpRemote {
- url: "https://h.test/mcp".to_string()
- }
- );
- assert!(!hosted.enabled);
- assert_eq!(
- hosted
- .credentials
- .as_ref()
- .unwrap()
- .get("Authorization")
- .unwrap(),
- "Bearer x"
- );
-}
-
-#[test]
-fn a_write_without_a_credential_block_leaves_it_unsaid() {
- let declared = parse(&json!({ "mcpServers": { "a": { "command": "npx" } } })).unwrap();
- assert_eq!(declared[0].credentials, None);
-}
-
-#[test]
-fn the_echoed_fields_are_ignored_on_write() {
- let declared = parse(&json!({
- "mcpServers": { "a": { "url": "https://a.test", "envKeys": ["X"], "authConfigured": true } }
- }))
- .unwrap();
- assert_eq!(declared.len(), 1);
- assert_eq!(declared[0].credentials, None);
-}
-
-#[test]
-fn refusals_name_the_entry_and_the_field() {
- let cases: Vec<(serde_json::Value, &str)> = vec![
- (json!([]), "holds an object"),
- (json!({}), "no `mcpServers` key"),
- (json!({ "mcpServers": 1 }), "maps a server name"),
- (
- json!({ "mcpServers": { "": {} } }),
- "one entry's key is empty",
- ),
- (json!({ "mcpServers": { "a": "x" } }), "`a` holds an object"),
- (json!({ "mcpServers": { "a": {} } }), "`a` needs a `url`"),
- (
- json!({ "mcpServers": { "a": { "url": "u", "command": "c" } } }),
- "both a `url` and a `command`",
- ),
- (
- json!({ "mcpServers": { "a": { "command": "c", "cwd": "/x" } } }),
- "`cwd` field this host doesn't understand",
- ),
- (
- json!({ "mcpServers": { "a": { "url": "u", "args": ["x"] } } }),
- "`args` only apply to a `command`",
- ),
- (
- json!({ "mcpServers": { "a": { "url": "u", "env": {} } } }),
- "takes `headers`, not `env`",
- ),
- (
- json!({ "mcpServers": { "a": { "command": "c", "env": { "__x": "1" } } } }),
- "reserved",
- ),
- (
- json!({ "mcpServers": { "a": { "command": "c", "env": { "K": 1 } } } }),
- "`a`.env.K holds a string",
- ),
- (
- json!({ "mcpServers": { "a": { "command": "c", "enabled": "yes" } } }),
- "`a`.enabled is true or false",
- ),
- (
- json!({ "mcpServers": { "a": { "command": " " } } }),
- "`a`.command is empty",
- ),
- ];
- for (doc, expected) in cases {
- let error = parse(&doc).expect_err("refused");
- assert!(
- error.contains(expected),
- "{doc}: expected {expected:?} in {error:?}"
- );
- }
-}
-
-// ── reconciliation helpers ───────────────────────────────────────────────────
-
-#[test]
-fn a_re_save_of_what_is_installed_is_not_a_change() {
- let row = stdio_row("a");
- let declared = parse(&render(std::slice::from_ref(&row), &BTreeMap::new())).unwrap();
- assert!(same_dial(&declared[0], &row));
-}
-
-#[test]
-fn a_changed_argument_or_flag_is_a_change() {
- let row = stdio_row("a");
- let mut declared = parse(&render(std::slice::from_ref(&row), &BTreeMap::new())).unwrap();
- declared[0].args.push("--verbose".to_string());
- assert!(!same_dial(&declared[0], &row));
-
- let mut declared = parse(&render(std::slice::from_ref(&row), &BTreeMap::new())).unwrap();
- declared[0].enabled = false;
- assert!(!same_dial(&declared[0], &row));
-}
-
-#[test]
-fn a_declaration_becomes_a_row_keyed_by_its_name() {
- let declared =
- parse(&json!({ "mcpServers": { "fs": { "command": "npx", "args": ["-y", "x"] } } }))
- .unwrap();
- let row = to_installed(&declared[0], "id-1".to_string(), 42);
- assert_eq!(row.server_id, "id-1");
- assert_eq!(row.qualified_name, "fs");
- assert_eq!(row.display_name, "fs");
- assert_eq!(row.command_kind, CommandKind::Node);
- assert_eq!(row.installed_at, 42);
- assert!(row.env_keys.is_empty());
-}
-
-#[test]
-fn merging_credentials_replaces_removes_and_keeps() {
- let mut stored = BTreeMap::new();
- stored.insert("A".to_string(), "old".to_string());
- stored.insert("B".to_string(), "keep".to_string());
- stored.insert("C".to_string(), "gone".to_string());
- let mut written = BTreeMap::new();
- written.insert("A".to_string(), "new".to_string());
- written.insert("C".to_string(), String::new());
- written.insert("D".to_string(), "added".to_string());
-
- let merged = merge_credentials(&stored, &written);
- assert_eq!(merged.get("A").unwrap(), "new");
- assert_eq!(merged.get("B").unwrap(), "keep");
- assert!(!merged.contains_key("C"));
- assert_eq!(merged.get("D").unwrap(), "added");
-}
diff --git a/crates/openhuman-core/src/mcp/registry/config_ops.rs b/crates/openhuman-core/src/mcp/registry/config_ops.rs
index 8714226bec..4a530ce1ac 100644
--- a/crates/openhuman-core/src/mcp/registry/config_ops.rs
+++ b/crates/openhuman-core/src/mcp/registry/config_ops.rs
@@ -1,10 +1,12 @@
//! The `mcp.json` RPC handlers: reading the install store as one document and
//! replacing it from one.
//!
-//! The contract — what a read shows, what a write may say — is
-//! [`super::config_doc`]; this file is the reconciliation against the store
-//! and the events it publishes. Split from `ops.rs` so each stays a
-//! readable size.
+//! The contract — what a read shows, what a write may say — and the
+//! reconciliation against the store are `tinymcp`'s
+//! (`tinymcp::registry::config_doc`, `McpRegistry::apply_config_doc`). What is
+//! left here is this application's: the `RpcOutcome` envelope, the domain
+//! events a change publishes, and connecting the changed servers in the
+//! background so the editor that saved the document does not wait on them.
use serde_json::{json, Value};
@@ -13,25 +15,22 @@ use crate::core::bus::BUS;
use crate::core::events::DomainEvent;
use crate::rpc::RpcOutcome;
-use super::config_doc;
use super::helpers::resolve;
// ── mcp.json ─────────────────────────────────────────────────────────────────
/// Renders the install store as the `mcp.json` document.
///
-/// Credential *names* ride along as `envKeys`; values never do. See
-/// [`super::config_doc`] for the contract.
+/// Credential *names* ride along as `envKeys`; values never do.
pub async fn mcp_clients_config_get(config: &Config) -> Result<RpcOutcome<Value>, String> {
let service = resolve(config)?;
- let installed = service
+ let doc = service
.dynamic()
- .installed_list()
+ .render_config_doc()
.map_err(|error| error.to_string())?;
-
- let stored_keys = stored_credential_names(service.dynamic().store(), &installed);
- let count = installed.len();
- let doc = config_doc::render(&installed, &stored_keys);
+ let count = doc[tinymcp::registry::config_doc::ROOT_KEY]
+ .as_object()
+ .map_or(0, serde_json::Map::len);
Ok(RpcOutcome::new(
doc,
@@ -41,161 +40,38 @@ pub async fn mcp_clients_config_get(config: &Config) -> Result<RpcOutcome<Value>
/// Replaces the install store with what `doc` declares.
///
-/// A replace, not a merge: a server absent from the document is uninstalled,
-/// one not yet installed is added, and one whose dial changed is rewritten in
-/// place under the same `server_id`. Credentials are the exception — a
-/// declaration that says nothing about them leaves the stored ones alone,
-/// because a read never shows them and a round trip must not wipe them.
-///
-/// Every added or rewritten server that is enabled is connected in the
-/// background; the status poll reports how that went. The reply carries the
-/// re-rendered document and what changed, so the editor can show both.
+/// A replace, not a merge — see `McpRegistry::apply_config_doc`. Every added
+/// or updated server that is enabled is connected in the background; the
+/// status poll reports how that went. The reply carries the re-rendered
+/// document and what changed, so the editor can show both.
pub async fn mcp_clients_config_set(
config: &Config,
doc: Value,
) -> Result<RpcOutcome<Value>, String> {
- let declared = config_doc::parse(&doc)?;
-
- // Keys are trimmed on the way in, so two spellings of one name can collide
- // after the fact even though a JSON object cannot repeat a key.
- {
- let mut seen = std::collections::HashSet::new();
- for entry in &declared {
- if !seen.insert(entry.name.as_str()) {
- return Err(format!("`{}` is declared twice", entry.name));
- }
- }
- }
-
let service = resolve(config)?;
let registry = service.dynamic();
- let store = registry.store();
- let installed = registry
- .installed_list()
+ let report = registry
+ .apply_config_doc(&doc)
+ .await
.map_err(|error| error.to_string())?;
- let mut added = Vec::new();
- let mut updated = Vec::new();
- let mut removed = Vec::new();
- let mut to_connect: Vec<String> = Vec::new();
-
- // Removals first, so a server renamed in the document (drop one key, add
- // another) does not briefly hold two live connections to one process.
- for server in &installed {
- if declared
- .iter()
- .any(|entry| entry.name == server.qualified_name)
- {
- continue;
- }
- tracing::debug!(
- server_id = %server.server_id,
- name = %server.qualified_name,
- "[mcp] config_set removing a server absent from the document"
- );
- registry
- .uninstall(&server.server_id)
- .await
- .map_err(|error| error.to_string())?;
+ for server in &report.removed {
BUS.publish(DomainEvent::McpServerDisconnected {
server_id: server.server_id.clone(),
reason: Some("removed from mcp.json".to_string()),
});
- removed.push(server.qualified_name.clone());
}
-
- for entry in &declared {
- let existing = installed
- .iter()
- .find(|server| server.qualified_name == entry.name);
-
- match existing {
- None => {
- let server_id = uuid::Uuid::new_v4().to_string();
- let row = config_doc::to_installed(entry, server_id.clone(), now_ms());
- store
- .insert_server(&row)
- .map_err(|error| error.to_string())?;
- if let Some(written) = &entry.credentials {
- let merged = config_doc::merge_credentials(&Default::default(), written);
- write_credentials(store, &server_id, &merged)?;
- }
- tracing::debug!(
- server_id = %server_id,
- name = %entry.name,
- transport = entry.transport.dispatch_kind(),
- "[mcp] config_set added a server"
- );
- BUS.publish(DomainEvent::McpServerInstalled {
- server_id: server_id.clone(),
- qualified_name: entry.name.clone(),
- });
- added.push(entry.name.clone());
- if entry.enabled {
- to_connect.push(server_id);
- }
- }
- Some(existing) => {
- let server_id = existing.server_id.clone();
- let dial_changed = !config_doc::same_dial(entry, existing);
- let mut stored = store
- .load_env_values(&server_id)
- .map_err(|error| error.to_string())?;
-
- if dial_changed {
- // The store has no "update the dial" statement, so the row
- // is rewritten under the same id. Deleting it cascades the
- // credentials, which is why they were read first.
- registry.connections().disconnect(&server_id).await;
- store
- .delete_server(&server_id)
- .map_err(|error| error.to_string())?;
- let row =
- config_doc::to_installed(entry, server_id.clone(), existing.installed_at);
- store
- .insert_server(&row)
- .map_err(|error| error.to_string())?;
- write_credentials(store, &server_id, &stored)?;
- tracing::debug!(
- server_id = %server_id,
- name = %entry.name,
- "[mcp] config_set rewrote a server whose dial changed"
- );
- }
-
- let credentials_changed = match &entry.credentials {
- Some(written) if !written.is_empty() => {
- let merged = config_doc::merge_credentials(&stored, written);
- let changed = merged != stored;
- if changed {
- write_credentials(store, &server_id, &merged)?;
- stored = merged;
- }
- changed
- }
- _ => false,
- };
- drop(stored);
-
- if dial_changed || credentials_changed {
- updated.push(entry.name.clone());
- if entry.enabled {
- if credentials_changed && !dial_changed {
- // A new credential only takes effect on a fresh
- // session.
- registry.connections().disconnect(&server_id).await;
- }
- to_connect.push(server_id);
- }
- }
- }
- }
+ for server in &report.installed {
+ BUS.publish(DomainEvent::McpServerInstalled {
+ server_id: server.server_id.clone(),
+ qualified_name: server.name.clone(),
+ });
}
// Connecting can take the transport's whole timeout per server; the editor
// must not wait on it. The status poll shows each attempt's outcome, and a
// failure is recorded against the server either way.
- for server_id in to_connect {
+ for server_id in report.connect_queued.clone() {
let service = std::sync::Arc::clone(&service);
tokio::spawn(async move {
match service.dynamic().connect(&server_id).await {
@@ -221,68 +97,31 @@ pub async fn mcp_clients_config_set(
});
}
- let installed = registry
- .installed_list()
+ let mut rendered = registry
+ .render_config_doc()
.map_err(|error| error.to_string())?;
- let stored_keys = stored_credential_names(store, &installed);
- let mut rendered = config_doc::render(&installed, &stored_keys);
+ let names = |servers: &[tinymcp::AppliedServer]| -> Vec<String> {
+ servers.iter().map(|server| server.name.clone()).collect()
+ };
let note = format!(
"config_set added={} updated={} removed={}",
- added.len(),
- updated.len(),
- removed.len()
+ report.installed.len(),
+ report.updated.len(),
+ report.removed.len()
+ );
+ tracing::debug!(
+ added = report.installed.len(),
+ updated = report.updated.len(),
+ removed = report.removed.len(),
+ connecting = report.connect_queued.len(),
+ "[mcp] config_set applied mcp.json"
);
if let Some(object) = rendered.as_object_mut() {
- object.insert("added".into(), json!(added));
- object.insert("updated".into(), json!(updated));
- object.insert("removed".into(), json!(removed));
+ object.insert("added".into(), json!(names(&report.installed)));
+ object.insert("updated".into(), json!(names(&report.updated)));
+ object.insert("removed".into(), json!(names(&report.removed)));
}
Ok(RpcOutcome::new(rendered, vec![note]))
}
-
-/// The credential *names* stored for each server, keyed by `server_id`.
-///
-/// Values are loaded and dropped here; only the names leave this function.
-fn stored_credential_names(
- store: &tinymcp::Store,
- installed: &[tinymcp_bus::InstalledServer],
-) -> std::collections::BTreeMap<String, Vec<String>> {
- installed
- .iter()
- .map(|server| {
- let names = store
- .load_env_values(&server.server_id)
- .map(|values| values.into_keys().collect())
- .unwrap_or_default();
- (server.server_id.clone(), names)
- })
- .collect()
-}
-
-/// Stores a server's credentials and keeps the row's name list in step.
-fn write_credentials(
- store: &tinymcp::Store,
- server_id: &str,
- values: &std::collections::BTreeMap<String, String>,
-) -> Result<(), String> {
- store
- .set_env_values(server_id, values)
- .map_err(|error| error.to_string())?;
- let names: Vec<String> = values.keys().cloned().collect();
- store
- .update_env_keys(server_id, &names)
- .map_err(|error| error.to_string())
-}
-
-/// Now, in Unix epoch milliseconds, as the install rows record it.
-fn now_ms() -> i64 {
- i64::try_from(
- std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .map(|elapsed| elapsed.as_millis())
- .unwrap_or_default(),
- )
- .unwrap_or(i64::MAX)
-}
diff --git a/crates/openhuman-core/src/mcp/registry/mod.rs b/crates/openhuman-core/src/mcp/registry/mod.rs
index 1b3291f76f..c5dbdee267 100644
--- a/crates/openhuman-core/src/mcp/registry/mod.rs
+++ b/crates/openhuman-core/src/mcp/registry/mod.rs
@@ -13,10 +13,9 @@
//! the extraction: an end-to-end test seeding the upstream response cache.
//! - [`ops`] — the `mcp_clients` RPC handlers, delegating to the service
//! [`super::host`] holds and publishing this application's own events.
-//! - [`config_doc`] — the `mcp.json` document: how the store renders as one
-//! and what a written one may say.
-//! - [`config_ops`] — the `config_get` / `config_set` handlers that reconcile
-//! the store against that document.
+//! - [`config_ops`] — the `config_get` / `config_set` handlers over the
+//! `mcp.json` document; the document contract and the reconciliation are
+//! `tinymcp::registry::config_doc`.
//! - `schemas` — the controller schemas and dispatch.
//! - [`supervisor_events`] — what the reconnect supervisor observed each
//! tick, as this domain's events; the Event Log and the notification bridge
@@ -41,8 +40,6 @@ pub mod action_tool;
#[cfg(feature = "mcp")]
pub mod bus;
#[cfg(feature = "mcp")]
-pub mod config_doc;
-#[cfg(feature = "mcp")]
pub mod config_ops;
#[cfg(feature = "mcp")]
pub(crate) mod helpers;
diff --git a/vendor/tinymcp b/vendor/tinymcp
index 44dca37035..7d603ab886 160000
--- a/vendor/tinymcp
+++ b/vendor/tinymcp
@@ -1 +1 @@
-Subproject commit 44dca370359ee6331b38a01bcd76b4a3f68b65de
+Subproject commit 7d603ab886d3b41d769263c51a4e76f600a750e6