The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(mcp): use extracted registry RPC handlers
Steven Enamakelb39d18c0566d
diff --git a/src/openhuman/mcp/registry/ops.rs b/src/openhuman/mcp/registry/ops.rsindex 6615b5fc82..62435ae5f1 100644--- a/src/openhuman/mcp/registry/ops.rs+++ b/src/openhuman/mcp/registry/ops.rs@@ -1,184 +1,122 @@//! RPC handler implementations for the MCP clients domain.//!-//! Each function maps 1-to-1 with a `schemas.rs` handler and is testable-//! in isolation; live-process tests live in `tests/json_rpc_e2e.rs`.+//! Every function here maps one-to-one with a `schemas.rs` handler and keeps+//! the signature and the JSON shape it had before the client moved out to+//! `tinymcp` — the frontend calls these methods and nothing about its contract+//! changed. What changed is underneath: each one now delegates to the service+//! [`super::super::host`] holds.+//!+//! # What stayed here on purpose+//!+//! **Events.** `tinymcp` reports what happened in its return values and+//! publishes nothing. `DomainEvent` is this application's vocabulary, so the+//! publishing happens at this layer, where that vocabulary is known.+//!+//! **The scan over remote tool definitions.** Prompt-injection detection is+//! host policy: the detector, its rules, and what a hit means belong to this+//! application's threat model.+//!+//! **The configuration assistant's agent turn.** `tinymcp` gathers the catalog+//! detail and the credential names a model would need and stops. Running the+//! turn needs the agent, the tool surface, and the approval gate, all of which+//! are here.use std::collections::HashMap;use std::time::Instant;use serde_json::{json, Value};-use uuid::Uuid;-use crate::core::event_bus::{publish_global, DomainEvent};+use crate::core::bus::BUS;+use crate::core::events::DomainEvent;use crate::openhuman::config::Config;+use crate::openhuman::mcp::host;use crate::rpc::RpcOutcome;-use super::connections;-use super::registry;-use super::store;-use super::types::{CommandKind, ConnStatus, InstalledServer, ServerProvenance};+use super::helpers::{encode, inject_required_env_keys, require, resolve};+use super::types::ChatTurn;-// ── registry_search ───────────────────────────────────────────────────────────+// ── registry_search ──────────────────────────────────────────────────────────+/// `transport` is accepted and ignored: the catalog no longer filters by it,+/// because the picker chooses a connection at install time from what the server+/// actually offers. The parameter stays so the frontend's call does not have to+/// change in the same release.pub async fn mcp_clients_registry_search(config: &Config,query: Option<String>,- transport: Option<String>,+ _transport: Option<String>,page: Option<u32>,page_size: Option<u32>,) -> Result<RpcOutcome<Value>, String> {let page = page.unwrap_or(1);let page_size = page_size.unwrap_or(20);- tracing::debug!(- "[mcp-client] registry_search query={:?} transport={:?} page={} page_size={}",- query,- transport,- page,- page_size- );+ let mut found = resolve(config)?+ .dynamic()+ .registry_search(query.as_deref(), page, page_size)+ .await+ .map_err(|error| error.to_string())?;- let (servers, total_pages) = registry::registry_search(- config,- query.as_deref(),- transport.as_deref(),- page,- page_size,- )- .await- .map_err(|e| e.to_string())?;+ // Badging and the strict filter are presentation choices, applied here so a+ // caller assembling its own view does not have to undo them.+ tinymcp::registry::curation::tag_official(&mut found.servers);+ tinymcp::registry::curation::float_official_first(&mut found.servers);+ let count = found.servers.len();Ok(RpcOutcome::new(- json!({ "servers": servers, "page": page, "total_pages": total_pages }),- vec![format!(- "registry_search returned {} servers",- servers.len()- )],+ json!({+ "servers": found.servers,+ "page": found.page,+ "total_pages": found.total_pages,+ }),+ vec![format!("registry_search returned {count} servers")],))}-// ── registry_get ──────────────────────────────────────────────────────────────+// ── registry_get ─────────────────────────────────────────────────────────────pub async fn mcp_clients_registry_get(config: &Config,qualified_name: String,) -> Result<RpcOutcome<Value>, String> {- if qualified_name.trim().is_empty() {- return Err("qualified_name must not be empty".to_string());- }-- tracing::debug!(- "[mcp-client] registry_get qualified_name={}",- qualified_name- );+ let qualified_name = require(&qualified_name, "qualified_name")?;- let detail = registry::registry_get(config, qualified_name.trim())+ let (detail, required_env_keys) = resolve(config)?+ .dynamic()+ .registry_get(&qualified_name).await- .map_err(|e| e.to_string())?;-- // Augment the response with required_env_keys derived from the connection- // the install will actually use (shared with the setup-agent path), so the- // frontend install dialog prompts only for what the picked transport needs.- let required_env_keys = super::setup_ops::collect_required_env_keys(&detail);- let mut server_value =- serde_json::to_value(&detail).map_err(|e| format!("serialization error: {e}"))?;- if let Some(obj) = server_value.as_object_mut() {- obj.insert(- "required_env_keys".to_string(),- serde_json::to_value(&required_env_keys).unwrap_or_else(|_| Value::Array(Vec::new())),- );- }+ .map_err(|error| error.to_string())?;++ // The install dialog needs both, and fetching them separately would be two+ // catalog round trips for one screen.+ let mut server = encode(&detail)?;+ inject_required_env_keys(&mut server, &required_env_keys);Ok(RpcOutcome::new(- json!({ "server": server_value }),+ json!({ "server": server }),vec![format!(- "registry_get ok: {} env_keys={}",- qualified_name.trim(),+ "registry_get ok: {qualified_name} env_keys={}",required_env_keys.len())],))}-// ── installed_list ────────────────────────────────────────────────────────────+// ── installed_list ───────────────────────────────────────────────────────────pub async fn mcp_clients_installed_list(config: &Config) -> Result<RpcOutcome<Value>, String> {- tracing::debug!("[mcp-client] installed_list");- let installed = store::list_servers(config).map_err(|e| e.to_string())?;+ let installed = resolve(config)?+ .dynamic()+ .installed_list()+ .map_err(|error| error.to_string())?;++ let count = installed.len();Ok(RpcOutcome::new(json!({ "installed": installed }),- vec![format!(- "installed_list returned {} servers",- installed.len()- )],+ vec![format!("installed_list returned {count} servers")],))}-// ── install ───────────────────────────────────────────────────────────────────--/// Refresh supplied env/config onto an already-installed row and return the-/// idempotent install outcome (`already_installed: true`). Shared by the-/// fast-path (the service was already present when install was called) and the-/// race-loss path (a concurrent install won the insert). Env is MERGED over the-/// stored values — same semantics as `update_env` — so a partial dialog-/// submission doesn't erase keys it didn't resend. A failed env read is-/// propagated rather than treated as an empty base (which could silently drop-/// stored keys on the subsequent write).-fn refresh_existing_install(- config: &Config,- mut existing: InstalledServer,- env: &HashMap<String, String>,- config_value: &Option<Value>,- canonical_name: &str,-) -> Result<RpcOutcome<Value>, String> {- // Both callers funnel through here, so the provenance rule lives here rather- // than at either call site. A hand-added server is not a catalog listing that- // happens to share a name — there is no listing behind it. Merging- // caller-supplied env onto connection details the user typed (and that this- // path cannot re-derive) would let `install`, which takes `qualified_name` as- // a free-form string and is reachable as an agent tool, inject env into a- // user's local command. Custom rows are edited via `update_custom` only.- if existing.provenance == ServerProvenance::Custom {- return Err(format!(- "`{canonical_name}` is a custom server you added by hand; edit it from Custom servers instead of installing over it"- ));- }-- let mut refreshed = false;- if !env.is_empty() {- let mut merged = store::load_env_values(config, &existing.server_id)- .map_err(|e| format!("Failed to load existing env values: {e}"))?;- merged.extend(env.clone());- store::set_env_values(config, &existing.server_id, &merged).map_err(|e| e.to_string())?;- let mut keys: Vec<String> = merged.keys().cloned().collect();- keys.sort();- if existing.env_keys != keys {- store::update_server_env_keys(config, &existing.server_id, &keys)- .map_err(|e| e.to_string())?;- existing.env_keys = keys;- }- refreshed = true;- }- if let Some(cfg) = config_value.clone() {- store::update_server_config(config, &existing.server_id, Some(&cfg))- .map_err(|e| e.to_string())?;- existing.config = Some(cfg);- refreshed = true;- }- tracing::debug!(- "[mcp-client] install no-op{} for {} (server_id={})",- if refreshed {- " (refreshed env/config)"- } else {- ""- },- canonical_name,- existing.server_id- );- Ok(RpcOutcome::new(- json!({ "server": existing, "already_installed": true }),- vec![format!("already installed qualified_name={canonical_name}")],- ))-}+// ── install ──────────────────────────────────────────────────────────────────pub async fn mcp_clients_install(config: &Config,@@ -186,309 +124,144 @@ pub async fn mcp_clients_install(env: HashMap<String, String>,config_value: Option<Value>,) -> Result<RpcOutcome<Value>, String> {- if qualified_name.trim().is_empty() {- return Err("qualified_name must not be empty".to_string());- }-- tracing::debug!(- "[mcp-client] install qualified_name={} env_keys={:?}",- qualified_name,- env.keys().collect::<Vec<_>>()- );+ let qualified_name = require(&qualified_name, "qualified_name")?;- // A source-routed install (`<source>::<qualified_name>`, e.g.- // `smithery::@org/server`) carries a registry prefix purely so- // `registry_get` can route to the right adapter. The catalog stores and- // dedups on the bare qualified_name, so the prefix must be stripped before- // the idempotency check and when persisting — otherwise a server installed- // once via the catalog (bare name) and again via a source-routed name would- // write a second row for the same service.- let routing_name = qualified_name.trim();- let canonical_name = routing_name- .split_once("::")- .map(|(_, rest)| rest)- .unwrap_or(routing_name);-- // Idempotent install: one server per (bare) qualified_name. If this service- // is already installed, refresh any supplied env/config onto the existing- // row instead of writing a second one (the table PK is server_id, so nothing- // else prevents duplicates). The refresh matters because the install dialog- // awaits connect() right after install — a user re-running it to replace an- // expired token must not silently reconnect with the stale secret.- if let Some(existing) =- store::find_server_by_qualified_name(config, canonical_name).map_err(|e| e.to_string())?- {- // The Custom-provenance guard lives inside `refresh_existing_install`, the- // single function this and the race-loss path below both funnel into.- return refresh_existing_install(config, existing, &env, &config_value, canonical_name);- }-- // Fetch registry detail to resolve command/args/env_keys. Use the full- // routing name (with any `<source>::` prefix) so registry_get reaches the- // correct adapter even when that registry is search-gated.- let detail = registry::registry_get(config, routing_name)+ let outcome = resolve(config)?+ .dynamic()+ .install(&qualified_name, env.into_iter().collect(), config_value).await- .map_err(|e| format!("Failed to fetch registry detail: {e}"))?;-- // Pick the best dialable connection — published stdio > any stdio >- // published http_remote > any http_remote — using the same picker the- // setup-agent path uses. Previously this path was stdio-only, so most- // Smithery listings (HTTP-remote) could not be installed from the manual- // install dialog at all; now both transports work identically- // (issue #3039 gap A2).- let picked = super::setup_ops::pick_connection(&detail.connections).ok_or_else(|| {- format!(- "server `{}` exposes neither stdio nor http_remote connections; nothing to install",- canonical_name- )- })?;- let (transport, command_kind, command, args) =- super::setup_ops::build_install_transport(canonical_name, picked)?;-- // Derive required env keys from provided map + schema- let env_keys: Vec<String> = env.keys().cloned().collect();-- let server_id = Uuid::new_v4().to_string();- let now_ms = std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .map(|d| d.as_millis() as i64)- .unwrap_or(0);-- let server = InstalledServer {- server_id: server_id.clone(),- qualified_name: canonical_name.to_string(),- display_name: detail.display_name.clone(),- description: detail.description.clone(),- icon_url: detail.icon_url.clone(),- command_kind,- command,- args,- env_keys,- config: config_value,- installed_at: now_ms,- last_connected_at: None,- transport,- enabled: true,- provenance: ServerProvenance::Registry,- };+ .map_err(|error| error.to_string())?;- // Insert only if no row for this canonical name exists yet, atomically — the- // `find_server_by_qualified_name` above and this insert are separated by the- // awaited `registry_get`, so two concurrent installs of the same service- // could otherwise both miss and write duplicate rows (the table PK is- // `server_id`, which doesn't prevent that). If we lost that race, refresh- // onto the row the winner created instead of leaving a duplicate.- if !store::insert_server_if_absent(config, &server).map_err(|e| e.to_string())? {- let existing = store::find_server_by_qualified_name(config, canonical_name)- .map_err(|e| e.to_string())?- .ok_or_else(|| "install raced but the existing row could not be found".to_string())?;- return refresh_existing_install(config, existing, &env, &server.config, canonical_name);+ if !outcome.already_installed {+ BUS.publish(DomainEvent::McpServerInstalled {+ server_id: outcome.server.server_id.clone(),+ qualified_name: outcome.server.qualified_name.clone(),+ });}- store::set_env_values(config, &server_id, &env).map_err(|e| e.to_string())?;-- tracing::debug!(- "[mcp-client] install ok server_id={} qualified_name={}",- server_id,- server.qualified_name- );- publish_global(DomainEvent::McpServerInstalled {- server_id: server_id.clone(),- qualified_name: server.qualified_name.clone(),- });+ let note = if outcome.already_installed {+ format!("already installed qualified_name={qualified_name}")+ } else {+ format!("installed server_id={}", outcome.server.server_id)+ };Ok(RpcOutcome::new(- json!({ "server": server }),- vec![format!("installed server_id={server_id}")],+ json!({+ "server": outcome.server,+ "already_installed": outcome.already_installed,+ }),+ vec![note],))}-/// Resolve the launch command from the qualified name and optional registry connection metadata.-pub(super) fn resolve_command(- qualified_name: &str,- stdio_conn: Option<&super::types::SmitheryConnection>,-) -> (CommandKind, String, Vec<String>) {- // Check if the connection has example_config with a command hint- if let Some(conn) = stdio_conn {- if let Some(example) = &conn.example_config {- if let Some(cmd) = example.get("command").and_then(Value::as_str) {- let args = example- .get("args")- .and_then(Value::as_array)- .map(|arr| {- arr.iter()- .filter_map(Value::as_str)- .map(String::from)- .collect()- })- .unwrap_or_default();- let kind = if cmd.contains("uvx") || cmd.contains("python") {- CommandKind::Python- } else {- CommandKind::Node- };- return (kind, cmd.to_string(), args);- }- }- }-- // Default: npx for all packages — both npm-scoped (@org/pkg) and- // plain smithery-style (owner/name) are launched the same way.- (- CommandKind::Node,- "npx".to_string(),- vec!["-y".to_string(), qualified_name.to_string()],- )-}--// ── uninstall ─────────────────────────────────────────────────────────────────+// ── uninstall ────────────────────────────────────────────────────────────────pub async fn mcp_clients_uninstall(config: &Config,server_id: String,) -> Result<RpcOutcome<Value>, String> {- if server_id.trim().is_empty() {- return Err("server_id must not be empty".to_string());- }-- tracing::debug!("[mcp-client] uninstall server_id={}", server_id);+ let server_id = require(&server_id, "server_id")?;- // Disconnect if currently connected- connections::disconnect(server_id.trim()).await;-- let removed = store::delete_server(config, server_id.trim()).map_err(|e| e.to_string())?;- tracing::debug!(- "[mcp-client] uninstall server_id={} removed={}",- server_id,- removed- );+ let removed = resolve(config)?+ .dynamic()+ .uninstall(&server_id)+ .await+ .map_err(|error| error.to_string())?;Ok(RpcOutcome::new(- json!({ "server_id": server_id.trim(), "removed": removed }),- vec![format!("uninstalled server_id={}", server_id.trim())],+ json!({ "server_id": server_id, "removed": removed }),+ vec![format!("uninstalled server_id={server_id}")],))}-// ── auth detection + browser OAuth ──────────────────────────────────────────────+// ── auth detection and browser OAuth ─────────────────────────────────────────-/// Classify how a server authenticates (`none` / `token` / `oauth`) by probing-/// it — the connect modal renders the matching control. Registry metadata is-/// unreliable, so this is the source of truth.pub async fn mcp_clients_detect_auth(config: &Config,server_id: String,) -> Result<RpcOutcome<Value>, String> {- if server_id.trim().is_empty() {- return Err("server_id must not be empty".to_string());- }- let detection = super::oauth::detect(config, server_id.trim()).await?;- let kind = detection.kind.clone();- let value = serde_json::to_value(&detection).map_err(|e| e.to_string())?;+ let server_id = require(&server_id, "server_id")?;++ let detection = resolve(config)?+ .dynamic()+ .detect_auth(&server_id)+ .await+ .map_err(|error| error.to_string())?;++ let kind = detection.kind.as_str();+ let value = encode(&detection)?;+Ok(RpcOutcome::new(value,- vec![format!("detect_auth {} -> {}", server_id.trim(), kind)],+ vec![format!("detect_auth {server_id} -> {kind}")],))}-/// Begin browser OAuth: discover + dynamic client registration + PKCE, returning-/// the live `/authorize` URL for the frontend to open. The `/oauth/mcp/callback`-/// route completes the exchange + reconnect.pub async fn mcp_clients_oauth_begin(config: &Config,server_id: String,) -> Result<RpcOutcome<Value>, String> {- if server_id.trim().is_empty() {- return Err("server_id must not be empty".to_string());- }- let authorize_url = super::oauth::begin(config, server_id.trim()).await?;+ let server_id = require(&server_id, "server_id")?;++ let authorize_url = resolve(config)?+ .dynamic()+ .oauth_begin(&server_id, &host::oauth_redirect_uri())+ .await+ .map_err(|error| error.to_string())?;+Ok(RpcOutcome::new(json!({ "authorize_url": authorize_url }),- vec![format!("oauth_begin {}", server_id.trim())],+ vec![format!("oauth_begin {server_id}")],))}-// ── connect ────────────────────────────────────────────────────────────────────+// ── connect ──────────────────────────────────────────────────────────────────pub async fn mcp_clients_connect(config: &Config,server_id: String,) -> Result<RpcOutcome<Value>, String> {- if server_id.trim().is_empty() {- return Err("server_id must not be empty".to_string());- }-- tracing::debug!("[mcp-client] connect rpc server_id={}", server_id);-- let server = store::get_server(config, server_id.trim()).map_err(|e| e.to_string())?;+ let server_id = require(&server_id, "server_id")?;- if !server.enabled {- return Err(format!(- "server_id={} is disabled; enable it via mcp_clients_set_enabled before connecting",- server_id.trim()- ));- }-- let tools = connections::connect(config, &server)+ let outcome = resolve(config)?+ .dynamic()+ .connect(&server_id).await- .map_err(|e| e.to_string())?;- let tools = super::tools_safe_for_agent(server_id.trim(), tools);+ .map_err(|error| error.to_string())?;- let tool_count = tools.len() as u32;+ let tools = super::tools_safe_for_agent(&server_id, outcome.tools);+ let tool_count = u32::try_from(tools.len()).unwrap_or(u32::MAX);- publish_global(DomainEvent::McpServerConnected {- server_id: server_id.trim().to_string(),+ BUS.publish(DomainEvent::McpServerConnected {+ server_id: server_id.clone(),tool_count,});Ok(RpcOutcome::new(- json!({- "server_id": server_id.trim(),- "status": "connected",- "tools": tools- }),+ json!({ "server_id": server_id, "status": "connected", "tools": tools }),vec![format!(- "connected server_id={} tools={}",- server_id.trim(),- tool_count+ "connected server_id={server_id} tools={tool_count}")],))}-// ── set_enabled ────────────────────────────────────────────────────────────────+// ── set_enabled ──────────────────────────────────────────────────────────────-/// Flip the `enabled` flag on an installed server.-///-/// - `enabled=false`: persist the flip, then disconnect any live session so-/// the server's tools immediately disappear from the agent's surface. The-/// install row and env values are kept intact so re-enabling later does-/// not require re-entering credentials.-/// - `enabled=true`: persist the flip. The server is NOT auto-connected here-/// — the user calls `connect` explicitly. This keeps "enabled" purely a-/// persistent setting and "connected" purely a live-session state.pub async fn mcp_clients_set_enabled(config: &Config,server_id: String,enabled: bool,) -> Result<RpcOutcome<Value>, String> {- if server_id.trim().is_empty() {- return Err("server_id must not be empty".to_string());- }- let server_id = server_id.trim().to_string();+ let server_id = require(&server_id, "server_id")?;- tracing::debug!(- "[mcp-client] set_enabled server_id={} enabled={}",- server_id,- enabled- );-- // Existence check produces a clear error before we mutate.- let _existing = store::get_server(config, &server_id).map_err(|e| e.to_string())?;- store::update_enabled(config, &server_id, enabled).map_err(|e| e.to_string())?;+ resolve(config)?+ .dynamic()+ .set_enabled(&server_id, enabled)+ .await+ .map_err(|error| error.to_string())?;if !enabled {- connections::disconnect(&server_id).await;- connections::clear_last_error(&server_id).await;- publish_global(DomainEvent::McpServerDisconnected {+ BUS.publish(DomainEvent::McpServerDisconnected {server_id: server_id.clone(),reason: Some("disabled".to_string()),});@@ -502,349 +275,263 @@ pub async fn mcp_clients_set_enabled())}-// ── disconnect ────────────────────────────────────────────────────────────────+// ── disconnect ───────────────────────────────────────────────────────────────-pub async fn mcp_clients_disconnect(server_id: String) -> Result<RpcOutcome<Value>, String> {- if server_id.trim().is_empty() {- return Err("server_id must not be empty".to_string());- }-- tracing::debug!("[mcp-client] disconnect rpc server_id={}", server_id);+pub async fn mcp_clients_disconnect(+ config: &Config,+ server_id: String,+) -> Result<RpcOutcome<Value>, String> {+ let server_id = require(&server_id, "server_id")?;- connections::disconnect(server_id.trim()).await;+ resolve(config)?+ .dynamic()+ .disconnect(&server_id)+ .await+ .map_err(|error| error.to_string())?;- publish_global(DomainEvent::McpServerDisconnected {- server_id: server_id.trim().to_string(),+ BUS.publish(DomainEvent::McpServerDisconnected {+ server_id: server_id.clone(),reason: None,});Ok(RpcOutcome::new(- json!({ "server_id": server_id.trim(), "status": "disconnected" }),- vec![format!("disconnected server_id={}", server_id.trim())],+ json!({ "server_id": server_id, "status": "disconnected" }),+ vec![format!("disconnected server_id={server_id}")],))}// ── update_env ───────────────────────────────────────────────────────────────-/// Replace the stored env values for an already-installed server and reconnect-/// so the new credentials take effect immediately (issue #3039 gap A3 — API-key-/// rotation / reconfigure without uninstall+reinstall).-///-/// Flow: persist env → disconnect (drop the stale session) → reload the install-/// record → reconnect with the fresh env. The reconnect reuses the transport-/// dispatch in [`connections::connect`], so this works for both stdio and-/// HTTP-remote installs. Values are never logged — only the key names.-///-/// A failed reconnect does **not** roll back the persisted env (matching-/// `mcp_setup_install_and_connect`): the user fixed a value, we keep it, and the-/// error is surfaced so they can retry `mcp_clients_connect`.pub async fn mcp_clients_update_env(config: &Config,server_id: String,env: HashMap<String, String>,) -> Result<RpcOutcome<Value>, String> {- if server_id.trim().is_empty() {- return Err("server_id must not be empty".to_string());- }- let server_id = server_id.trim();+ use tinymcp_bus::UpdateEnvStatus;- tracing::debug!(- "[mcp-client] update_env server_id={} env_keys={:?}",- server_id,- env.keys().collect::<Vec<_>>()- );+ let server_id = require(&server_id, "server_id")?;- // Merge the supplied values over any already-stored env, THEN persist —- // `set_env_values` replaces the value table wholesale, so a partial update- // (e.g. the connect modal sending only the one field the user just typed,- // with no way to display the other stored secrets) would silently erase- // the rest. Merging preserves keys the caller didn't send; supplied values- // win on collision. Callers that send every key (the reconfigure form,- // which requires all fields) are unaffected — for them merged == supplied.- let mut merged = store::load_env_values(config, server_id).unwrap_or_default();- merged.extend(env);- // Persist first so the new values survive even if the reconnect fails.- store::set_env_values(config, server_id, &merged).map_err(|e| e.to_string())?;-- // Drop any live session so the reconnect picks up the new env.- connections::disconnect(server_id).await;- publish_global(DomainEvent::McpServerDisconnected {- server_id: server_id.to_string(),- reason: Some("env reconfigured".to_string()),- });+ let outcome = resolve(config)?+ .dynamic()+ .update_env(&server_id, env.into_iter().collect())+ .await+ .map_err(|error| error.to_string())?;- let mut server = store::get_server(config, server_id).map_err(|e| e.to_string())?;-- // Keep the install record's `env_keys` list in sync with the full merged- // value set we just wrote (not just the keys supplied this call), so the- // key-name list shown in the UI (and returned below) reflects every stored- // key — including the ones a partial update preserved.- let mut new_keys: Vec<String> = merged.keys().cloned().collect();- new_keys.sort();- if server.env_keys != new_keys {- server.env_keys = new_keys;- store::update_server_env_keys(config, server_id, &server.env_keys)- .map_err(|e| e.to_string())?;- }+ match outcome.status {+ UpdateEnvStatus::Connected => {+ let tools = super::tools_safe_for_agent(&server_id, outcome.tools);+ let tool_count = u32::try_from(tools.len()).unwrap_or(u32::MAX);++ BUS.publish(DomainEvent::McpServerConnected {+ server_id: server_id.clone(),+ tool_count,+ });- // A disabled server must not be auto-reconnected even when its env is- // reconfigured — `enabled` is the user-visible "should this be live" gate- // and the same disabled rule that blocks `mcp_clients_connect` applies- // here. The new values are already persisted so a later `set_enabled(true)`- // + `connect` round-trip will pick them up.- if !server.enabled {- return Ok(RpcOutcome::new(+ Ok(RpcOutcome::new(+ json!({+ "server_id": server_id,+ "status": "connected",+ "env_keys": outcome.env_keys,+ "tools": tools,+ }),+ vec![format!(+ "update_env reconnected server_id={server_id} tools={tool_count}"+ )],+ ))+ }+ UpdateEnvStatus::Disabled => Ok(RpcOutcome::new(json!({"server_id": server_id,"status": "disabled",- "env_keys": server.env_keys,+ "env_keys": outcome.env_keys,}),vec![format!("update_env persisted env for server_id={server_id} but did not reconnect: server is disabled")],- ));- }-- match connections::connect(config, &server).await {- Ok(tools) => {- let tools = super::tools_safe_for_agent(server_id, tools);- let tool_count = tools.len() as u32;- publish_global(DomainEvent::McpServerConnected {- server_id: server_id.to_string(),- tool_count,- });+ )),+ UpdateEnvStatus::Unauthorized => {+ // The reason code, never the raw 401 message: that leaks the OAuth+ // metadata URL, and the frontend renders localized copy from the+ // code alone.+ let hint = outcome.auth_hint.map(|hint| hint.as_code()).unwrap_or_default();Ok(RpcOutcome::new(json!({"server_id": server_id,- "status": "connected",- "env_keys": server.env_keys,- "tools": tools,+ "status": "unauthorized",+ "env_keys": outcome.env_keys,+ "auth_hint": hint,}),vec![format!(- "update_env reconnected server_id={server_id} tools={tool_count}"+ "update_env persisted env for server_id={server_id} but reconnect was unauthorized: {hint}")],))}- Err(err) => {- // A 401 is surfaced as `unauthorized` + a stable `auth_hint` code- // (oauth_required / token_rejected / credential_required) the UI maps- // to actionable copy — the raw message is WITHHELD because it leaks- // the OAuth metadata URL (#3719, #4289). Generic transport failures- // keep their diagnostic message under `disconnected`.- match connections::auth_hint_for(server_id).await {- Some(hint) => Ok(RpcOutcome::new(- json!({- "server_id": server_id,- "status": "unauthorized",- "env_keys": server.env_keys,- "auth_hint": hint,- }),- vec![format!(- "update_env persisted env for server_id={server_id} but reconnect was unauthorized: {hint}"- )],- )),- None => Ok(RpcOutcome::new(- json!({- "server_id": server_id,- "status": "disconnected",- "env_keys": server.env_keys,- "error": err.to_string(),- }),- vec![format!(- "update_env persisted env for server_id={server_id} but reconnect failed: {err}"- )],- )),- }+ _ => {+ let error = outcome.error.unwrap_or_default();+ Ok(RpcOutcome::new(+ json!({+ "server_id": server_id,+ "status": "disconnected",+ "env_keys": outcome.env_keys,+ "error": error,+ }),+ vec![format!(+ "update_env persisted env for server_id={server_id} but reconnect failed: {error}"+ )],+ ))}}}-// ── registry settings ──────────────────────────────────────────────────────--/// Build the non-secret registry-settings snapshot: booleans reporting whether-/// each credential is set (from config OR env) plus the user-configured-/// official-registry base URL. Secret *values* are never included.-fn registry_settings_snapshot(config: &Config) -> Value {- json!({- "smithery_api_key_set":- super::registries::smithery::smithery_api_key(config).is_some(),- "mcp_official_token_set":- super::registries::mcp_official::auth_token(config).is_some(),- "mcp_official_base":- config- .mcp_client- .registry_auth- .mcp_official_base- .clone()- .filter(|s| !s.trim().is_empty()),- })-}+// ── registry settings ────────────────────────────────────────────────────────-/// Report which registry credentials are configured. NEVER returns secret-/// values — only `*_set` booleans + the (non-secret) base URL override-/// (issue #3039 gap A6).pub async fn mcp_clients_registry_settings_get(config: &Config,) -> Result<RpcOutcome<Value>, String> {- tracing::debug!("[mcp-client] registry_settings_get");+ let settings = resolve(config)?.dynamic().registry_settings();+Ok(RpcOutcome::new(- registry_settings_snapshot(config),+ encode(&settings)?,vec!["registry_settings_get".to_string()],))}-/// Persist registry credentials to config (issue #3039 gap A6).+/// Persists the credentials and tells the running service about them.///-/// Per-field semantics: `None` leaves the stored value unchanged; `Some(s)`-/// sets it, where an empty/whitespace string clears the value (falling back to-/// the env var, if any). Secrets are write-only — the response is the same-/// non-secret snapshot as the getter, never the values just written.+/// Both halves are needed: the file is what survives a restart, and the service+/// is what the next search actually uses.pub async fn mcp_clients_registry_settings_set(config: &mut Config,smithery_api_key: Option<String>,mcp_official_base: Option<String>,mcp_official_token: Option<String>,) -> Result<RpcOutcome<Value>, String> {+ /// A blank update clears the field; an absent one leaves it.fn apply(field: &mut Option<String>, update: Option<String>) {if let Some(value) = update {let trimmed = value.trim();- *field = if trimmed.is_empty() {- None- } else {- Some(trimmed.to_string())- };+ *field = (!trimmed.is_empty()).then(|| trimmed.to_string());}}- tracing::debug!(- "[mcp-client] registry_settings_set smithery_key_present={} official_token_present={} official_base_present={}",- smithery_api_key.is_some(),- mcp_official_token.is_some(),- mcp_official_base.is_some()- );-let auth = &mut config.mcp_client.registry_auth;- apply(&mut auth.smithery_api_key, smithery_api_key);- apply(&mut auth.mcp_official_base, mcp_official_base);- apply(&mut auth.mcp_official_token, mcp_official_token);+ apply(&mut auth.smithery_api_key, smithery_api_key.clone());+ apply(&mut auth.mcp_official_base, mcp_official_base.clone());+ apply(&mut auth.mcp_official_token, mcp_official_token.clone());++ config.save().await.map_err(|error| error.to_string())?;- config.save().await.map_err(|e| e.to_string())?;+ let settings = resolve(config)?.dynamic().set_registry_settings(+ smithery_api_key,+ mcp_official_base,+ mcp_official_token,+ );Ok(RpcOutcome::new(- registry_settings_snapshot(config),+ encode(&settings)?,vec!["registry_settings_set saved".to_string()],))}-// ── status ─────────────────────────────────────────────────────────────────────+// ── status ───────────────────────────────────────────────────────────────────pub async fn mcp_clients_status(config: &Config) -> Result<RpcOutcome<Value>, String> {- tracing::debug!("[mcp-client] status");- let statuses: Vec<ConnStatus> = connections::all_status(config).await;+ let statuses = resolve(config)?+ .dynamic()+ .status()+ .await+ .map_err(|error| error.to_string())?;++ let count = statuses.len();Ok(RpcOutcome::new(json!({ "servers": statuses }),- vec![format!("status returned {} servers", statuses.len())],+ vec![format!("status returned {count} servers")],))}-// ── list_tools ──────────────────────────────────────────────────────────────+// ── list_tools ───────────────────────────────────────────────────────────────++pub async fn mcp_clients_list_tools(+ config: &Config,+ server_id: String,+) -> Result<RpcOutcome<Value>, String> {+ let server_id = require(&server_id, "server_id")?;-/// List the tools (name + description + input schema) advertised by one-/// already-connected server. This is the agent's discovery primitive: it-/// reads the live snapshot without re-handshaking (unlike `connect`). When-/// the server is not connected, returns an error hint to connect first.-pub async fn mcp_clients_list_tools(server_id: String) -> Result<RpcOutcome<Value>, String> {- if server_id.trim().is_empty() {- return Err("server_id must not be empty".to_string());+ /// What a caller has to do about it either way.+ fn connect_first(server_id: &str) -> String {+ format!("server_id={server_id} is not connected; connect it first via mcp_clients_connect")}- tracing::debug!("[mcp-client] list_tools server_id={}", server_id);+ let tools = resolve(config)?+ .dynamic()+ .list_tools(&server_id)+ .await+ .map_err(|error| {+ tracing::debug!("[mcp-client] list_tools ({server_id}) failed: {error}");+ connect_first(&server_id)+ })?;- match connections::tools_for(server_id.trim()).await {- Some(tools) => {- let tools = super::tools_safe_for_agent(server_id.trim(), tools);- let count = tools.len();- Ok(RpcOutcome::new(- json!({ "server_id": server_id.trim(), "tools": tools }),- vec![format!(- "list_tools server_id={} returned {} tools",- server_id.trim(),- count- )],- ))- }- None => Err(format!(- "server_id={} is not connected; connect it first via mcp_clients_connect",- server_id.trim()- )),- }+ let tools = super::tools_safe_for_agent(&server_id, tools);+ let count = tools.len();++ Ok(RpcOutcome::new(+ json!({ "server_id": server_id, "tools": tools }),+ vec![format!(+ "list_tools server_id={server_id} returned {count} tools"+ )],+ ))}-// ── tool_call ─────────────────────────────────────────────────────────────────+// ── tool_call ────────────────────────────────────────────────────────────────pub async fn mcp_clients_tool_call(+ config: &Config,server_id: String,tool_name: String,arguments: Value,) -> Result<RpcOutcome<Value>, String> {- if server_id.trim().is_empty() {- return Err("server_id must not be empty".to_string());- }- if tool_name.trim().is_empty() {- return Err("tool_name must not be empty".to_string());- }-- tracing::debug!(- "[mcp-client] tool_call server_id={} tool_name={}",- server_id,- tool_name- );+ let server_id = require(&server_id, "server_id")?;+ let tool_name = require(&tool_name, "tool_name")?;let start = Instant::now();- let result = connections::call_tool(server_id.trim(), tool_name.trim(), arguments).await;- let elapsed_ms = start.elapsed().as_millis() as u64;- let success = result.is_ok();-- publish_global(DomainEvent::McpClientToolExecuted {- server_id: server_id.trim().to_string(),- tool_name: tool_name.trim().to_string(),- success,+ let result = resolve(config)?+ .dynamic()+ .tool_call(&server_id, &tool_name, arguments)+ .await;+ let elapsed_ms = u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX);++ BUS.publish(DomainEvent::McpClientToolExecuted {+ server_id: server_id.clone(),+ tool_name: tool_name.clone(),+ success: result.is_ok(),elapsed_ms,});match result {- Ok(value) => Ok(RpcOutcome::new(- json!({ "result": value, "is_error": false }),+ Ok(outcome) => Ok(RpcOutcome::new(+ json!({ "result": outcome.result, "is_error": outcome.is_error }),vec![format!(- "tool_call ok server_id={} tool={} elapsed_ms={}",- server_id.trim(),- tool_name.trim(),- elapsed_ms+ "tool_call ok server_id={server_id} tool={tool_name} elapsed_ms={elapsed_ms}")],)),- Err(e) => Ok(RpcOutcome::new(- json!({ "result": e, "is_error": true }),+ Err(error) => Ok(RpcOutcome::new(+ json!({ "result": error.to_string(), "is_error": true }),vec![format!(- "tool_call error server_id={} tool={}: {}",- server_id.trim(),- tool_name.trim(),- e+ "tool_call error server_id={server_id} tool={tool_name}: {error}")],)),}}-// ── config_assist ─────────────────────────────────────────────────────────────+// ── config_assist ────────────────────────────────────────────────────────────pub async fn mcp_clients_config_assist(config: &Config,qualified_name: String,user_message: String,- history: Option<Vec<super::types::ChatTurn>>,+ history: Option<Vec<ChatTurn>>,) -> Result<RpcOutcome<Value>, String> {- if qualified_name.trim().is_empty() {- return Err("qualified_name must not be empty".to_string());- }+ let qualified_name = require(&qualified_name, "qualified_name")?;tracing::debug!("[mcp-client] config_assist qualified_name={} message_len={}",@@ -852,18 +539,18 @@ pub async fn mcp_clients_config_assist(user_message.len());- // Fetch registry detail to build the system prompt- let detail = registry::registry_get(config, qualified_name.trim())+ // The module gathers the catalog detail and the credential names; running+ // the turn below is this layer's, because it needs the agent, the tool+ // surface and the approval gate.+ let (detail, required_env_keys) = resolve(config)?+ .dynamic()+ .config_assist(&qualified_name).await- .map_err(|e| format!("Failed to fetch registry detail: {e}"))?;-- // Collect required env keys from the connection the install will use (shared- // with the setup-agent + install-dialog paths).- let required_env_keys: Vec<String> = super::setup_ops::collect_required_env_keys(&detail);+ .map_err(|error| format!("Failed to fetch registry detail: {error}"))?;let system_prompt = build_config_assist_system_prompt(&detail.display_name,- qualified_name.trim(),+ &qualified_name,&required_env_keys,);@@ -922,7 +609,7 @@ async fn invoke_config_assist_agent(// turn returns its text verbatim, so we want natural markdown, not a JSON// envelope. Server context comes through `user_message`._system_prompt: &str,- history: &[super::types::ChatTurn],+ history: &[ChatTurn],user_message: &str,) -> Result<Value, String> {// Run a real agent turn (not a bare completion) so the model can use@@ -993,83 +680,5 @@ async fn invoke_config_assist_agent(}#[cfg(test)]-mod tests {- use super::*;- use serde_json::json;-- #[test]- fn build_config_assist_system_prompt_lists_env_keys() {- let prompt = build_config_assist_system_prompt(- "Test Server",- "@test/server",- &["API_KEY".to_string(), "SECRET".to_string()],- );- assert!(prompt.contains("API_KEY"));- assert!(prompt.contains("SECRET"));- assert!(prompt.contains("Test Server"));- assert!(prompt.contains("@test/server"));- }-- #[test]- fn build_config_assist_system_prompt_no_keys() {- let prompt = build_config_assist_system_prompt("My Server", "@my/server", &[]);- assert!(prompt.contains("none detected"));- }-- #[test]- fn collect_required_env_keys_from_schema() {- use crate::openhuman::mcp::registry::types::{SmitheryConnection, SmitheryServerDetail};- let detail = SmitheryServerDetail {- qualified_name: "@test/s".to_string(),- display_name: "T".to_string(),- description: None,- icon_url: None,- connections: vec![SmitheryConnection {- r#type: "stdio".to_string(),- deployment_url: None,- config_schema: Some(json!({- "properties": {- "API_KEY": { "type": "string" },- "ENDPOINT": { "type": "string" }- }- })),- example_config: None,- published: true,- extra: Default::default(),- }],- source: "smithery".to_string(),- extra: Default::default(),- };- let keys = crate::openhuman::mcp::registry::setup_ops::collect_required_env_keys(&detail);- assert!(keys.contains(&"API_KEY".to_string()));- assert!(keys.contains(&"ENDPOINT".to_string()));- }-- #[test]- fn resolve_command_npm_package() {- let (kind, cmd, args) = resolve_command("@modelcontextprotocol/server-fs", None);- assert_eq!(kind, CommandKind::Node);- assert_eq!(cmd, "npx");- assert!(args.contains(&"@modelcontextprotocol/server-fs".to_string()));- }-- #[test]- fn resolve_command_with_example_config() {- use crate::openhuman::mcp::registry::types::SmitheryConnection;- let conn = SmitheryConnection {- r#type: "stdio".to_string(),- deployment_url: None,- config_schema: None,- example_config: Some(json!({- "command": "uvx",- "args": ["--from", "my-pkg", "mcp-server"]- })),- published: true,- extra: Default::default(),- };- let (kind, cmd, args) = resolve_command("my-pkg", Some(&conn));- assert_eq!(kind, CommandKind::Python);- assert_eq!(cmd, "uvx");- assert_eq!(args[0], "--from");- }-}+#[path = "ops_tests.rs"]+mod tests;diff --git a/src/openhuman/mcp/registry/schemas.rs b/src/openhuman/mcp/registry/schemas.rsindex 8521b8e8d1..9231380f89 100644--- a/src/openhuman/mcp/registry/schemas.rs+++ b/src/openhuman/mcp/registry/schemas.rs@@ -4,1443 +4,8 @@//! shape. Every `handle_*` function deserialises params and delegates to//! `ops.rs`.-use serde::de::DeserializeOwned;-use serde_json::{Map, Value};--use crate::core::all::{ControllerFuture, RegisteredController};-use crate::core::{ControllerSchema, FieldSchema, TypeSchema};-use crate::openhuman::config::rpc as config_rpc;-use crate::rpc::RpcOutcome;--// ── Schema registry ──────────────────────────────────────────────────────────--pub fn all_controller_schemas() -> Vec<ControllerSchema> {- vec![- schemas("registry_search"),- schemas("registry_get"),- schemas("installed_list"),- schemas("install"),- schemas("add_custom"),- schemas("update_custom"),- schemas("update_env"),- schemas("uninstall"),- schemas("detect_auth"),- schemas("oauth_begin"),- schemas("connect"),- schemas("disconnect"),- schemas("status"),- schemas("tool_call"),- schemas("config_assist"),- schemas("registry_settings_get"),- schemas("registry_settings_set"),- schemas("set_enabled"),- // Setup-agent surface (mcp_setup namespace, lives in setup_ops.rs).- setup_schemas("search"),- setup_schemas("get"),- setup_schemas("request_secret"),- setup_schemas("submit_secret"),- setup_schemas("test_connection"),- setup_schemas("install_and_connect"),- ]-}--pub fn all_registered_controllers() -> Vec<RegisteredController> {- vec![- RegisteredController {- schema: schemas("registry_search"),- handler: handle_registry_search,- },- RegisteredController {- schema: schemas("registry_get"),- handler: handle_registry_get,- },- RegisteredController {- schema: schemas("installed_list"),- handler: handle_installed_list,- },- RegisteredController {- schema: schemas("install"),- handler: handle_install,- },- RegisteredController {- schema: schemas("add_custom"),- handler: handle_add_custom,- },- RegisteredController {- schema: schemas("update_custom"),- handler: handle_update_custom,- },- RegisteredController {- schema: schemas("update_env"),- handler: handle_update_env,- },- RegisteredController {- schema: schemas("uninstall"),- handler: handle_uninstall,- },- RegisteredController {- schema: schemas("detect_auth"),- handler: handle_detect_auth,- },- RegisteredController {- schema: schemas("oauth_begin"),- handler: handle_oauth_begin,- },- RegisteredController {- schema: schemas("connect"),- handler: handle_connect,- },- RegisteredController {- schema: schemas("disconnect"),- handler: handle_disconnect,- },- RegisteredController {- schema: schemas("status"),- handler: handle_status,- },- RegisteredController {- schema: schemas("tool_call"),- handler: handle_tool_call,- },- RegisteredController {- schema: schemas("config_assist"),- handler: handle_config_assist,- },- RegisteredController {- schema: schemas("registry_settings_get"),- handler: handle_registry_settings_get,- },- RegisteredController {- schema: schemas("registry_settings_set"),- handler: handle_registry_settings_set,- },- RegisteredController {- schema: schemas("set_enabled"),- handler: handle_set_enabled,- },- RegisteredController {- schema: setup_schemas("search"),- handler: handle_setup_search,- },- RegisteredController {- schema: setup_schemas("get"),- handler: handle_setup_get,- },- RegisteredController {- schema: setup_schemas("request_secret"),- handler: handle_setup_request_secret,- },- RegisteredController {- schema: setup_schemas("submit_secret"),- handler: handle_setup_submit_secret,- },- RegisteredController {- schema: setup_schemas("test_connection"),- handler: handle_setup_test_connection,- },- RegisteredController {- schema: setup_schemas("install_and_connect"),- handler: handle_setup_install_and_connect,- },- ]-}--pub fn schemas(function: &str) -> ControllerSchema {- match function {- "registry_search" => ControllerSchema {- namespace: "mcp_clients",- function: "registry_search",- description: "Search the Smithery.ai MCP server registry.",- inputs: vec![- FieldSchema {- name: "query",- ty: TypeSchema::Option(Box::new(TypeSchema::String)),- comment: "Free-text search query.",- required: false,- },- FieldSchema {- name: "transport",- ty: TypeSchema::Option(Box::new(TypeSchema::String)),- comment: "Transport filter: \"stdio\", \"hosted\", or \"all\"/omitted.",- required: false,- },- FieldSchema {- name: "page",- ty: TypeSchema::Option(Box::new(TypeSchema::U64)),- comment: "1-based page number (default: 1).",- required: false,- },- FieldSchema {- name: "page_size",- ty: TypeSchema::Option(Box::new(TypeSchema::U64)),- comment: "Results per page (default: 20).",- required: false,- },- ],- outputs: vec![- FieldSchema {- name: "servers",- ty: TypeSchema::Array(Box::new(TypeSchema::Ref("SmitheryServerSummary"))),- comment: "Matching server summaries from the registry.",- required: true,- },- FieldSchema {- name: "page",- ty: TypeSchema::U64,- comment: "Current page number.",- required: true,- },- FieldSchema {- name: "total_pages",- ty: TypeSchema::U64,- comment: "Total number of pages available.",- required: true,- },- ],- },-- "registry_get" => ControllerSchema {- namespace: "mcp_clients",- function: "registry_get",- description: "Fetch full details for one MCP server from the Smithery registry.",- inputs: vec![FieldSchema {- name: "qualified_name",- ty: TypeSchema::String,- comment: "Registry qualified name, e.g. `@modelcontextprotocol/server-filesystem`.",- required: true,- }],- outputs: vec![FieldSchema {- name: "server",- ty: TypeSchema::Ref("SmitheryServerDetail"),- comment: "Full server detail including connection specs.",- required: true,- }],- },-- "installed_list" => ControllerSchema {- namespace: "mcp_clients",- function: "installed_list",- description: "List all locally installed MCP servers.",- inputs: vec![],- outputs: vec![FieldSchema {- name: "installed",- ty: TypeSchema::Array(Box::new(TypeSchema::Ref("InstalledServer"))),- comment: "Installed server records (env values omitted).",- required: true,- }],- },-- "install" => ControllerSchema {- namespace: "mcp_clients",- function: "install",- description: "Install an MCP server from the Smithery registry.",- inputs: vec![- FieldSchema {- name: "qualified_name",- ty: TypeSchema::String,- comment: "Registry qualified name.",- required: true,- },- FieldSchema {- name: "env",- ty: TypeSchema::Map(Box::new(TypeSchema::String)),- comment: "Environment variable values required by the server. Values are stored encrypted and never returned.",- required: true,- },- FieldSchema {- name: "config",- ty: TypeSchema::Option(Box::new(TypeSchema::Json)),- comment: "Optional JSON configuration blob.",- required: false,- },- ],- outputs: vec![FieldSchema {- name: "server",- ty: TypeSchema::Ref("InstalledServer"),- comment: "The newly installed server record.",- required: true,- }],- },-- "add_custom" => ControllerSchema {- namespace: "mcp_clients",- function: "add_custom",- description: "Add an MCP server by hand, for servers that are not published in any registry. `stdio` runs a local command; `http_remote` dials a URL. The record is created disconnected — call `connect` afterwards.",- inputs: vec![- FieldSchema {- name: "display_name",- ty: TypeSchema::String,- comment: "Human-readable name shown in the UI.",- required: true,- },- FieldSchema {- name: "transport",- ty: TypeSchema::Enum {- variants: vec!["stdio", "http_remote"],- },- comment: "`stdio` for a local subprocess, `http_remote` for a hosted endpoint.",- required: true,- },- FieldSchema {- name: "command",- ty: TypeSchema::Option(Box::new(TypeSchema::String)),- comment: "Launch binary for stdio servers (`npx`, `uvx`, an absolute path, …). Required when transport=stdio, ignored otherwise.",- required: false,- },- FieldSchema {- name: "args",- ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(- TypeSchema::String,- )))),- comment: "Arguments passed to `command`. Ignored when transport=http_remote.",- required: false,- },- FieldSchema {- name: "url",- ty: TypeSchema::Option(Box::new(TypeSchema::String)),- comment: "Absolute http(s) endpoint. Required when transport=http_remote, ignored otherwise.",- required: false,- },- FieldSchema {- name: "env",- ty: TypeSchema::Option(Box::new(TypeSchema::Map(Box::new(TypeSchema::String)))),- comment: "stdio: subprocess environment variables. http_remote: request headers (key = header name). Values are stored locally and never returned. Keys starting with `__` are reserved.",- required: false,- },- FieldSchema {- name: "description",- ty: TypeSchema::Option(Box::new(TypeSchema::String)),- comment: "Optional note shown alongside the server.",- required: false,- },- ],- outputs: vec![FieldSchema {- name: "server",- ty: TypeSchema::Ref("InstalledServer"),- comment: "The newly added server record (env values omitted).",- required: true,- }],- },-- "update_custom" => ControllerSchema {- namespace: "mcp_clients",- function: "update_custom",- description: "Replace the connection details of a hand-added server. Rejects registry installs, whose command and endpoint come from the catalog listing. Drops any live connection so the next connect uses the new settings.",- inputs: vec![- FieldSchema {- name: "server_id",- ty: TypeSchema::String,- comment: "UUID of the custom server to edit.",- required: true,- },- FieldSchema {- name: "display_name",- ty: TypeSchema::String,- comment: "Human-readable name shown in the UI.",- required: true,- },- FieldSchema {- name: "transport",- ty: TypeSchema::Enum {- variants: vec!["stdio", "http_remote"],- },- comment: "`stdio` for a local subprocess, `http_remote` for a hosted endpoint.",- required: true,- },- FieldSchema {- name: "command",- ty: TypeSchema::Option(Box::new(TypeSchema::String)),- comment: "Launch binary for stdio servers. Required when transport=stdio.",- required: false,- },- FieldSchema {- name: "args",- ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(- TypeSchema::String,- )))),- comment: "Arguments passed to `command`. Ignored when transport=http_remote.",- required: false,- },- FieldSchema {- name: "url",- ty: TypeSchema::Option(Box::new(TypeSchema::String)),- comment: "Absolute http(s) endpoint. Required when transport=http_remote.",- required: false,- },- FieldSchema {- name: "env",- ty: TypeSchema::Option(Box::new(TypeSchema::Map(Box::new(TypeSchema::String)))),- comment: "Replacement env/header map — omitted keys are removed. Values are stored locally and never returned.",- required: false,- },- FieldSchema {- name: "description",- ty: TypeSchema::Option(Box::new(TypeSchema::String)),- comment: "Optional note shown alongside the server.",- required: false,- },- ],- outputs: vec![FieldSchema {- name: "server",- ty: TypeSchema::Ref("InstalledServer"),- comment: "The updated server record (env values omitted).",- required: true,- }],- },-- "update_env" => ControllerSchema {- namespace: "mcp_clients",- function: "update_env",- description: "Replace the stored env values for an installed server and reconnect so the new credentials take effect (reconfigure / rotate keys without reinstalling).",- inputs: vec![- FieldSchema {- name: "server_id",- ty: TypeSchema::String,- comment: "UUID of the installed server to reconfigure.",- required: true,- },- FieldSchema {- name: "env",- ty: TypeSchema::Map(Box::new(TypeSchema::String)),- comment: "Replacement environment variable values. Stored encrypted and never returned.",- required: true,- },- ],- outputs: vec![- FieldSchema {- name: "server_id",- ty: TypeSchema::String,- comment: "The reconfigured server id.",- required: true,- },- FieldSchema {- name: "status",- ty: TypeSchema::Enum {- variants: vec!["connected", "disconnected"],- },- comment: "`connected` if the reconnect succeeded, `disconnected` if env was saved but reconnect failed.",- required: true,- },- FieldSchema {- name: "env_keys",- ty: TypeSchema::Array(Box::new(TypeSchema::String)),- comment: "Env key names after the update (values omitted).",- required: true,- },- FieldSchema {- name: "tools",- ty: TypeSchema::Array(Box::new(TypeSchema::Ref("McpTool"))),- comment: "Tools exposed after reconnect (present only when status=connected).",- required: false,- },- ],- },-- "uninstall" => ControllerSchema {- namespace: "mcp_clients",- function: "uninstall",- description: "Uninstall a locally installed MCP server.",- inputs: vec![FieldSchema {- name: "server_id",- ty: TypeSchema::String,- comment: "UUID of the server to remove.",- required: true,- }],- outputs: vec![- FieldSchema {- name: "server_id",- ty: TypeSchema::String,- comment: "The server id that was targeted.",- required: true,- },- FieldSchema {- name: "removed",- ty: TypeSchema::Bool,- comment: "True when the server was actually removed.",- required: true,- },- ],- },-- "detect_auth" => ControllerSchema {- namespace: "mcp_clients",- function: "detect_auth",- description: "Probe a server to classify how it authenticates (none / token / oauth).",- inputs: vec![FieldSchema {- name: "server_id",- ty: TypeSchema::String,- comment: "UUID of the installed server to probe.",- required: true,- }],- outputs: vec![- FieldSchema {- name: "kind",- ty: TypeSchema::Enum {- variants: vec!["none", "token", "oauth"],- },- comment: "`none` (open), `token` (static bearer/API key), or `oauth` (browser sign-in).",- required: true,- },- FieldSchema {- name: "authorization_endpoint",- ty: TypeSchema::Option(Box::new(TypeSchema::String)),- comment: "OAuth authorization endpoint, when kind is `oauth`.",- required: false,- },- FieldSchema {- name: "grant_types",- ty: TypeSchema::Array(Box::new(TypeSchema::String)),- comment: "Grant types the authorization server supports.",- required: true,- },- ],- },-- "oauth_begin" => ControllerSchema {- namespace: "mcp_clients",- function: "oauth_begin",- description: "Begin browser OAuth: discover + dynamically register a client + PKCE, returning the authorize URL to open.",- inputs: vec![FieldSchema {- name: "server_id",- ty: TypeSchema::String,- comment: "UUID of the installed server to authenticate.",- required: true,- }],- outputs: vec![FieldSchema {- name: "authorize_url",- ty: TypeSchema::String,- comment: "Live OAuth authorize URL to open in the browser; the /oauth/mcp/callback route completes sign-in.",- required: true,- }],- },-- "connect" => ControllerSchema {- namespace: "mcp_clients",- function: "connect",- description: "Spawn the MCP server subprocess and run the initialize handshake.",- inputs: vec![FieldSchema {- name: "server_id",- ty: TypeSchema::String,- comment: "UUID of the installed server to connect.",- required: true,- }],- outputs: vec![- FieldSchema {- name: "server_id",- ty: TypeSchema::String,- comment: "Connected server id.",- required: true,- },- FieldSchema {- name: "status",- ty: TypeSchema::Enum {- variants: vec!["connected"],- },- comment: "Always `connected` on success.",- required: true,- },- FieldSchema {- name: "tools",- ty: TypeSchema::Array(Box::new(TypeSchema::Ref("McpTool"))),- comment: "Tools exposed by the connected server.",- required: true,- },- ],- },-- "disconnect" => ControllerSchema {- namespace: "mcp_clients",- function: "disconnect",- description: "Disconnect a running MCP server and stop its process.",- inputs: vec![FieldSchema {- name: "server_id",- ty: TypeSchema::String,- comment: "UUID of the server to disconnect.",- required: true,- }],- outputs: vec![- FieldSchema {- name: "server_id",- ty: TypeSchema::String,- comment: "Disconnected server id.",- required: true,- },- FieldSchema {- name: "status",- ty: TypeSchema::Enum {- variants: vec!["disconnected"],- },- comment: "Always `disconnected` on success.",- required: true,- },- ],- },-- "status" => ControllerSchema {- namespace: "mcp_clients",- function: "status",- description: "Return connection status for all installed MCP servers.",- inputs: vec![],- outputs: vec![FieldSchema {- name: "servers",- ty: TypeSchema::Array(Box::new(TypeSchema::Ref("ConnStatus"))),- comment: "Per-server connection status summaries.",- required: true,- }],- },-- "tool_call" => ControllerSchema {- namespace: "mcp_clients",- function: "tool_call",- description: "Invoke a tool on a connected MCP server.",- inputs: vec![- FieldSchema {- name: "server_id",- ty: TypeSchema::String,- comment: "UUID of the connected server.",- required: true,- },- FieldSchema {- name: "tool_name",- ty: TypeSchema::String,- comment: "Name of the tool to call.",- required: true,- },- FieldSchema {- name: "arguments",- ty: TypeSchema::Json,- comment: "Tool arguments as a JSON value.",- required: true,- },- ],- outputs: vec![- FieldSchema {- name: "result",- ty: TypeSchema::Json,- comment: "Tool result value.",- required: true,- },- FieldSchema {- name: "is_error",- ty: TypeSchema::Bool,- comment: "True when the tool returned an error.",- required: true,- },- ],- },-- "config_assist" => ControllerSchema {- namespace: "mcp_clients",- function: "config_assist",- description: "AI assistant that helps configure an MCP server's required env vars.",- inputs: vec![- FieldSchema {- name: "qualified_name",- ty: TypeSchema::String,- comment: "Registry qualified name of the server being configured.",- required: true,- },- FieldSchema {- name: "user_message",- ty: TypeSchema::String,- comment: "User's question or reply.",- required: true,- },- FieldSchema {- name: "history",- ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(TypeSchema::Ref(- "ChatTurn",- ))))),- comment: "Prior conversation turns `[{role, content}]`.",- required: false,- },- ],- outputs: vec![- FieldSchema {- name: "reply",- ty: TypeSchema::String,- comment: "Assistant reply (markdown).",- required: true,- },- FieldSchema {- name: "suggested_env",- ty: TypeSchema::Option(Box::new(TypeSchema::Map(Box::new(TypeSchema::String)))),- comment: "Env vars extracted from the user's message, if any.",- required: false,- },- ],- },-- "registry_settings_get" => ControllerSchema {- namespace: "mcp_clients",- function: "registry_settings_get",- description: "Report which registry credentials are configured (Smithery key, official-registry base/token). Never returns secret values — only `*_set` booleans plus the non-secret base URL override.",- inputs: vec![],- outputs: vec![- FieldSchema {- name: "smithery_api_key_set",- ty: TypeSchema::Bool,- comment: "True when a Smithery API key is set (config or env).",- required: true,- },- FieldSchema {- name: "mcp_official_token_set",- ty: TypeSchema::Bool,- comment: "True when an official-registry bearer token is set (config or env).",- required: true,- },- FieldSchema {- name: "mcp_official_base",- ty: TypeSchema::Option(Box::new(TypeSchema::String)),- comment: "User-configured official-registry base URL override (non-secret).",- required: false,- },- ],- },-- "registry_settings_set" => ControllerSchema {- namespace: "mcp_clients",- function: "registry_settings_set",- description: "Persist registry credentials. Per field: omit to leave unchanged, empty string to clear, value to set. Secrets are write-only; the response is the same non-secret snapshot as registry_settings_get.",- inputs: vec![- FieldSchema {- name: "smithery_api_key",- ty: TypeSchema::Option(Box::new(TypeSchema::String)),- comment: "New Smithery API key (empty string clears).",- required: false,- },- FieldSchema {- name: "mcp_official_base",- ty: TypeSchema::Option(Box::new(TypeSchema::String)),- comment: "New official-registry base URL override (empty string clears).",- required: false,- },- FieldSchema {- name: "mcp_official_token",- ty: TypeSchema::Option(Box::new(TypeSchema::String)),- comment: "New official-registry bearer token (empty string clears).",- required: false,- },- ],- outputs: vec![- FieldSchema {- name: "smithery_api_key_set",- ty: TypeSchema::Bool,- comment: "True when a Smithery API key is set after the update.",- required: true,- },- FieldSchema {- name: "mcp_official_token_set",- ty: TypeSchema::Bool,- comment: "True when an official-registry token is set after the update.",- required: true,- },- FieldSchema {- name: "mcp_official_base",- ty: TypeSchema::Option(Box::new(TypeSchema::String)),- comment: "Official-registry base URL override after the update.",- required: false,- },- ],- },-- "set_enabled" => ControllerSchema {- namespace: "mcp_clients",- function: "set_enabled",- description: "Enable or disable an installed MCP server. Disabling auto-disconnects any live session and hides the server's tools from the agent; the install row and env values are kept so re-enabling does not require re-entry.",- inputs: vec![- FieldSchema {- name: "server_id",- ty: TypeSchema::String,- comment: "UUID of the installed server.",- required: true,- },- FieldSchema {- name: "enabled",- ty: TypeSchema::Bool,- comment: "Target state; `false` also disconnects.",- required: true,- },- ],- outputs: vec![- FieldSchema {- name: "server_id",- ty: TypeSchema::String,- comment: "Echoed server id.",- required: true,- },- FieldSchema {- name: "enabled",- ty: TypeSchema::Bool,- comment: "Effective enabled state after the call.",- required: true,- },- ],- },-- // Handled by setup_schemas() — surface a clearer error rather than- // falling through to the generic unknown sink.- "setup_search"- | "setup_get"- | "setup_request_secret"- | "setup_submit_secret"- | "setup_test_connection"- | "setup_install_and_connect" => setup_schemas(function.trim_start_matches("setup_")),-- _other => ControllerSchema {- namespace: "mcp_clients",- function: "unknown",- description: "Unknown mcp_clients controller function.",- inputs: vec![FieldSchema {- name: "function",- ty: TypeSchema::String,- comment: "Unknown function requested for schema lookup.",- required: true,- }],- outputs: vec![FieldSchema {- name: "error",- ty: TypeSchema::String,- comment: "Lookup error details.",- required: true,- }],- },- }-}--// ── Handler implementations ──────────────────────────────────────────────────--fn handle_registry_search(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let config = config_rpc::load_config_with_timeout().await?;- let query = read_optional_string(¶ms, "query")?;- let transport = read_optional_string(¶ms, "transport")?;- let page = read_optional_u32(¶ms, "page")?;- let page_size = read_optional_u32(¶ms, "page_size")?;- to_json(- crate::openhuman::mcp::registry::ops::mcp_clients_registry_search(- &config, query, transport, page, page_size,- )- .await?,- )- })-}--fn handle_registry_get(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let config = config_rpc::load_config_with_timeout().await?;- let qualified_name = read_required::<String>(¶ms, "qualified_name")?;- to_json(- crate::openhuman::mcp::registry::ops::mcp_clients_registry_get(&config, qualified_name)- .await?,- )- })-}--fn handle_installed_list(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let _ = params;- let config = config_rpc::load_config_with_timeout().await?;- to_json(crate::openhuman::mcp::registry::ops::mcp_clients_installed_list(&config).await?)- })-}--fn handle_install(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let config = config_rpc::load_config_with_timeout().await?;- let qualified_name = read_required::<String>(¶ms, "qualified_name")?;- let env = read_required::<std::collections::HashMap<String, String>>(¶ms, "env")?;- let config_value = read_optional_json(¶ms, "config")?;- to_json(- crate::openhuman::mcp::registry::ops::mcp_clients_install(- &config,- qualified_name,- env,- config_value,- )- .await?,- )- })-}--/// Shared param reader for `add_custom` / `update_custom` — both take the same-/// user-editable body, so a single reader keeps their validation identical.-fn read_custom_input(- params: &Map<String, Value>,-) -> Result<crate::openhuman::mcp::registry::custom::CustomServerInput, String> {- Ok(crate::openhuman::mcp::registry::custom::CustomServerInput {- display_name: read_required::<String>(params, "display_name")?,- transport: read_required::<String>(params, "transport")?,- command: read_optional_string(params, "command")?,- args: read_optional::<Vec<String>>(params, "args")?.unwrap_or_default(),- url: read_optional_string(params, "url")?,- env: read_optional::<std::collections::HashMap<String, String>>(params, "env")?- .unwrap_or_default(),- description: read_optional_string(params, "description")?,- })-}--fn handle_add_custom(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let config = config_rpc::load_config_with_timeout().await?;- let input = read_custom_input(¶ms)?;- to_json(- crate::openhuman::mcp::registry::custom::ops::mcp_clients_add_custom(&config, input)- .await?,- )- })-}--fn handle_update_custom(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let config = config_rpc::load_config_with_timeout().await?;- let server_id = read_required::<String>(¶ms, "server_id")?;- let input = read_custom_input(¶ms)?;- to_json(- crate::openhuman::mcp::registry::custom::ops::mcp_clients_update_custom(- &config, server_id, input,- )- .await?,- )- })-}--fn handle_update_env(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let config = config_rpc::load_config_with_timeout().await?;- let server_id = read_required::<String>(¶ms, "server_id")?;- let env = read_required::<std::collections::HashMap<String, String>>(¶ms, "env")?;- to_json(- crate::openhuman::mcp::registry::ops::mcp_clients_update_env(&config, server_id, env)- .await?,- )- })-}--fn handle_uninstall(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let config = config_rpc::load_config_with_timeout().await?;- let server_id = read_required::<String>(¶ms, "server_id")?;- to_json(- crate::openhuman::mcp::registry::ops::mcp_clients_uninstall(&config, server_id).await?,- )- })-}--fn handle_detect_auth(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let config = config_rpc::load_config_with_timeout().await?;- let server_id = read_required::<String>(¶ms, "server_id")?;- to_json(- crate::openhuman::mcp::registry::ops::mcp_clients_detect_auth(&config, server_id)- .await?,- )- })-}--fn handle_oauth_begin(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let config = config_rpc::load_config_with_timeout().await?;- let server_id = read_required::<String>(¶ms, "server_id")?;- to_json(- crate::openhuman::mcp::registry::ops::mcp_clients_oauth_begin(&config, server_id)- .await?,- )- })-}--fn handle_connect(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let config = config_rpc::load_config_with_timeout().await?;- let server_id = read_required::<String>(¶ms, "server_id")?;- to_json(- crate::openhuman::mcp::registry::ops::mcp_clients_connect(&config, server_id).await?,- )- })-}--fn handle_disconnect(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let server_id = read_required::<String>(¶ms, "server_id")?;- to_json(crate::openhuman::mcp::registry::ops::mcp_clients_disconnect(server_id).await?)- })-}--fn handle_set_enabled(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let config = config_rpc::load_config_with_timeout().await?;- let server_id = read_required::<String>(¶ms, "server_id")?;- let enabled = read_required::<bool>(¶ms, "enabled")?;- to_json(- crate::openhuman::mcp::registry::ops::mcp_clients_set_enabled(- &config, server_id, enabled,- )- .await?,- )- })-}--fn handle_status(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let _ = params;- let config = config_rpc::load_config_with_timeout().await?;- to_json(crate::openhuman::mcp::registry::ops::mcp_clients_status(&config).await?)- })-}--fn handle_tool_call(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let server_id = read_required::<String>(¶ms, "server_id")?;- let tool_name = read_required::<String>(¶ms, "tool_name")?;- let arguments = params- .get("arguments")- .cloned()- .unwrap_or(Value::Object(Map::new()));- to_json(- crate::openhuman::mcp::registry::ops::mcp_clients_tool_call(- server_id, tool_name, arguments,- )- .await?,- )- })-}--fn handle_config_assist(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let config = config_rpc::load_config_with_timeout().await?;- let qualified_name = read_required::<String>(¶ms, "qualified_name")?;- let user_message = read_required::<String>(¶ms, "user_message")?;- let history = read_optional::<Vec<crate::openhuman::mcp::registry::types::ChatTurn>>(- ¶ms, "history",- )?;- to_json(- crate::openhuman::mcp::registry::ops::mcp_clients_config_assist(- &config,- qualified_name,- user_message,- history,- )- .await?,- )- })-}--fn handle_registry_settings_get(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let _ = params;- let config = config_rpc::load_config_with_timeout().await?;- to_json(- crate::openhuman::mcp::registry::ops::mcp_clients_registry_settings_get(&config)- .await?,- )- })-}--fn handle_registry_settings_set(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let smithery_api_key = read_optional::<String>(¶ms, "smithery_api_key")?;- let mcp_official_base = read_optional::<String>(¶ms, "mcp_official_base")?;- let mcp_official_token = read_optional::<String>(¶ms, "mcp_official_token")?;- let mut config = config_rpc::load_config_with_timeout().await?;- to_json(- crate::openhuman::mcp::registry::ops::mcp_clients_registry_settings_set(- &mut config,- smithery_api_key,- mcp_official_base,- mcp_official_token,- )- .await?,- )- })-}--// ── mcp_setup_* schemas + handlers ────────────────────────────────────────────--/// All setup-agent schemas under the `mcp_setup` RPC namespace. Kept in a-/// separate function so the setup surface can evolve independently of the-/// existing `mcp_clients_*` controllers.-pub fn setup_schemas(function: &str) -> ControllerSchema {- match function {- "search" => ControllerSchema {- namespace: "mcp_setup",- function: "search",- description: "Search all enabled MCP registries (Smithery + official).",- inputs: vec![- FieldSchema {- name: "query",- ty: TypeSchema::Option(Box::new(TypeSchema::String)),- comment: "Free-text search query.",- required: false,- },- FieldSchema {- name: "page",- ty: TypeSchema::Option(Box::new(TypeSchema::U64)),- comment: "1-based page number (default: 1).",- required: false,- },- FieldSchema {- name: "page_size",- ty: TypeSchema::Option(Box::new(TypeSchema::U64)),- comment: "Results per page (default: 20).",- required: false,- },- ],- outputs: vec![- FieldSchema {- name: "servers",- ty: TypeSchema::Array(Box::new(TypeSchema::Ref("SmitheryServerSummary"))),- comment: "Merged summaries; each row tagged with its `source` (`smithery` | `mcp_official`).",- required: true,- },- FieldSchema {- name: "page",- ty: TypeSchema::U64,- comment: "Current page number.",- required: true,- },- FieldSchema {- name: "total_pages",- ty: TypeSchema::U64,- comment: "Upper-bound page count across registries.",- required: true,- },- ],- },- "get" => ControllerSchema {- namespace: "mcp_setup",- function: "get",- description: "Fetch full details for one server. Adds `required_env_keys` derived from the connection schema.",- inputs: vec![FieldSchema {- name: "qualified_name",- ty: TypeSchema::String,- comment: "Registry qualified name. May be prefixed with `<source>::` to pin a registry.",- required: true,- }],- outputs: vec![FieldSchema {- name: "server",- ty: TypeSchema::Ref("SmitheryServerDetail"),- comment: "Full detail with `required_env_keys` injected.",- required: true,- }],- },- "request_secret" => ControllerSchema {- namespace: "mcp_setup",- function: "request_secret",- description: "Ask the user out-of-band for a secret value. Blocks until the UI submits via `submit_secret` (5-minute timeout). Returns an opaque ref; the raw value never enters the agent's context.",- inputs: vec![- FieldSchema {- name: "key_name",- ty: TypeSchema::String,- comment: "Display name of the env var (e.g. `NOTION_API_KEY`).",- required: true,- },- FieldSchema {- name: "prompt",- ty: TypeSchema::String,- comment: "Plain-English instruction shown to the user in the native input box.",- required: true,- },- ],- outputs: vec![- FieldSchema {- name: "ref",- ty: TypeSchema::String,- comment: "Opaque handle like `secret://<hex>`. Pass back via `test_connection` / `install_and_connect`.",- required: true,- },- FieldSchema {- name: "key_name",- ty: TypeSchema::String,- comment: "Echoed key name.",- required: true,- },- ],- },- "submit_secret" => ControllerSchema {- namespace: "mcp_setup",- function: "submit_secret",- description: "UI-side: fulfill a pending `request_secret` with the user-entered value. Not intended for agent use.",- inputs: vec![- FieldSchema {- name: "ref_id",- ty: TypeSchema::String,- comment: "The `secret://<hex>` ref returned by `request_secret`.",- required: true,- },- FieldSchema {- name: "value",- ty: TypeSchema::String,- comment: "Raw secret value. NEVER log this.",- required: true,- },- ],- outputs: vec![- FieldSchema {- name: "ref",- ty: TypeSchema::String,- comment: "Echoed ref.",- required: true,- },- FieldSchema {- name: "fulfilled",- ty: TypeSchema::Bool,- comment: "True on success.",- required: true,- },- ],- },- "test_connection" => ControllerSchema {- namespace: "mcp_setup",- function: "test_connection",- description: "Dry-run install: spawn a candidate server in a scratch process with the supplied secret refs, list its tools, tear down. Nothing persisted.",- inputs: vec![- FieldSchema {- name: "qualified_name",- ty: TypeSchema::String,- comment: "Registry qualified name.",- required: true,- },- FieldSchema {- name: "env_refs",- ty: TypeSchema::Map(Box::new(TypeSchema::String)),- comment: "Map `{ENV_KEY: secret://<hex>}` produced by `request_secret`.",- required: true,- },- ],- outputs: vec![- FieldSchema {- name: "ok",- ty: TypeSchema::Bool,- comment: "True if initialize + tools/list succeeded.",- required: true,- },- FieldSchema {- name: "tools",- ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(TypeSchema::Ref(- "McpRemoteTool",- ))))),- comment: "Tools advertised by the candidate. Present iff `ok`.",- required: false,- },- FieldSchema {- name: "error",- ty: TypeSchema::Option(Box::new(TypeSchema::String)),- comment: "Error string. Present iff `ok` is false.",- required: false,- },- ],- },- "install_and_connect" => ControllerSchema {- namespace: "mcp_setup",- function: "install_and_connect",- description: "Commit: persist the install + secrets (consuming the refs), then connect immediately and return the tool list.",- inputs: vec![- FieldSchema {- name: "qualified_name",- ty: TypeSchema::String,- comment: "Registry qualified name.",- required: true,- },- FieldSchema {- name: "env_refs",- ty: TypeSchema::Map(Box::new(TypeSchema::String)),- comment: "Map `{ENV_KEY: secret://<hex>}`. Refs are consumed (removed from the in-memory map) on success.",- required: true,- },- ],- outputs: vec![- FieldSchema {- name: "server_id",- ty: TypeSchema::String,- comment: "Freshly-minted server UUID.",- required: true,- },- FieldSchema {- name: "status",- ty: TypeSchema::String,- comment: "`connected` or `installed_disconnected` (install succeeded, connect failed).",- required: true,- },- FieldSchema {- name: "tools",- ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(TypeSchema::Ref(- "McpTool",- ))))),- comment: "Tool list iff `status == connected`.",- required: false,- },- FieldSchema {- name: "error",- ty: TypeSchema::Option(Box::new(TypeSchema::String)),- comment: "Connect error iff `status != connected`.",- required: false,- },- ],- },- _ => ControllerSchema {- namespace: "mcp_setup",- function: "unknown",- description: "Unknown mcp_setup controller function.",- inputs: vec![FieldSchema {- name: "function",- ty: TypeSchema::String,- comment: "Unknown function requested for schema lookup.",- required: true,- }],- outputs: vec![FieldSchema {- name: "error",- ty: TypeSchema::String,- comment: "Lookup error details.",- required: true,- }],- },- }-}--fn handle_setup_search(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let config = config_rpc::load_config_with_timeout().await?;- let query = read_optional_string(¶ms, "query")?;- let page = read_optional_u32(¶ms, "page")?;- let page_size = read_optional_u32(¶ms, "page_size")?;- to_json(- crate::openhuman::mcp::registry::setup_ops::mcp_setup_search(- &config, query, page, page_size,- )- .await?,- )- })-}--fn handle_setup_get(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let config = config_rpc::load_config_with_timeout().await?;- let qualified_name = read_required::<String>(¶ms, "qualified_name")?;- to_json(- crate::openhuman::mcp::registry::setup_ops::mcp_setup_get(&config, qualified_name)- .await?,- )- })-}--fn handle_setup_request_secret(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let key_name = read_required::<String>(¶ms, "key_name")?;- let prompt = read_required::<String>(¶ms, "prompt")?;- to_json(- crate::openhuman::mcp::registry::setup_ops::mcp_setup_request_secret(key_name, prompt)- .await?,- )- })-}--fn handle_setup_submit_secret(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let ref_id = read_required::<String>(¶ms, "ref_id")?;- let value = read_required::<String>(¶ms, "value")?;- to_json(- crate::openhuman::mcp::registry::setup_ops::mcp_setup_submit_secret(ref_id, value)- .await?,- )- })-}--fn handle_setup_test_connection(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let config = config_rpc::load_config_with_timeout().await?;- let qualified_name = read_required::<String>(¶ms, "qualified_name")?;- let env_refs =- read_required::<std::collections::HashMap<String, String>>(¶ms, "env_refs")?;- to_json(- crate::openhuman::mcp::registry::setup_ops::mcp_setup_test_connection(- &config,- qualified_name,- env_refs,- )- .await?,- )- })-}--fn handle_setup_install_and_connect(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let config = config_rpc::load_config_with_timeout().await?;- let qualified_name = read_required::<String>(¶ms, "qualified_name")?;- let env_refs =- read_required::<std::collections::HashMap<String, String>>(¶ms, "env_refs")?;- to_json(- crate::openhuman::mcp::registry::setup_ops::mcp_setup_install_and_connect(- &config,- qualified_name,- env_refs,- )- .await?,- )- })-}--// ── Param helpers ─────────────────────────────────────────────────────────────--fn read_required<T: DeserializeOwned>(params: &Map<String, Value>, key: &str) -> Result<T, String> {- let value = params- .get(key)- .cloned()- .ok_or_else(|| format!("missing required param '{key}'"))?;- serde_json::from_value(value).map_err(|e| format!("invalid '{key}': {e}"))-}--fn read_optional<T: DeserializeOwned>(- params: &Map<String, Value>,- key: &str,-) -> Result<Option<T>, String> {- match params.get(key) {- None | Some(Value::Null) => Ok(None),- Some(v) => serde_json::from_value(v.clone())- .map(Some)- .map_err(|e| format!("invalid '{key}': {e}")),- }-}--fn read_optional_string(params: &Map<String, Value>, key: &str) -> Result<Option<String>, String> {- read_optional::<String>(params, key)-}--fn read_optional_u32(params: &Map<String, Value>, key: &str) -> Result<Option<u32>, String> {- match params.get(key) {- None | Some(Value::Null) => Ok(None),- Some(Value::Number(n)) => n- .as_u64()- .and_then(|v| u32::try_from(v).ok())- .map(Some)- .ok_or_else(|| format!("invalid '{key}': expected u32")),- Some(other) => Err(format!(- "invalid '{key}': expected number, got {}",- type_name(other)- )),- }-}--fn read_optional_json(params: &Map<String, Value>, key: &str) -> Result<Option<Value>, String> {- match params.get(key) {- None | Some(Value::Null) => Ok(None),- Some(v) => Ok(Some(v.clone())),- }-}--fn to_json<T: serde::Serialize>(outcome: RpcOutcome<T>) -> Result<Value, String> {- serde_json::to_value(outcome.value).map_err(|e| e.to_string())-}--fn type_name(value: &Value) -> &'static str {- match value {- Value::Null => "null",- Value::Bool(_) => "bool",- Value::Number(_) => "number",- Value::String(_) => "string",- Value::Array(_) => "array",- Value::Object(_) => "object",- }-}-#[cfg(test)]#[path = "schemas_tests.rs"]mod tests;+include!("schemas_part_01.rs");+include!("schemas_part_02.rs");diff --git a/src/openhuman/mcp/registry/setup_ops.rs b/src/openhuman/mcp/registry/setup_ops.rsindex 4a05077e14..55d5132117 100644--- a/src/openhuman/mcp/registry/setup_ops.rs+++ b/src/openhuman/mcp/registry/setup_ops.rs@@ -1,37 +1,51 @@-//! RPC handlers for the MCP setup agent. See `docs/MCP_SETUP_AGENT.md`.+//! RPC handlers for the guided setup flow (`mcp_setup`).//!-//! These handlers form the agent-facing tool surface:+//! Every function keeps the signature and the JSON shape it had before the+//! client moved to `tinymcp`, and delegates to the service [`super::super::host`]+//! holds.//!-//! - `mcp_setup_search` / `mcp_setup_get` — thin wrappers over-//! [`super::registry`] so the agent browses upstream registries.-//! - `mcp_setup_request_secret` — block on a fresh ref until the UI-//! submits a value.-//! - `mcp_setup_submit_secret` — UI-side fulfillment.-//! - `mcp_setup_test_connection` — spawn a candidate subprocess in a-//! scratch workspace, list its tools, tear it down. No persistence.-//! - `mcp_setup_install_and_connect` — commit: persist install + env,-//! call [`super::connections::connect`].+//! # The secret handles have not changed shape//!-//! Raw secret values flow only through `submit_secret` and the-//! just-in-time resolve inside `test_connection` / `install_and_connect`.-//! They are never echoed in responses or logged.+//! The flow is still: mint an opaque `secret://…` handle, prompt the user out+//! of band, and resolve the handle inside the operation that needs the value.+//! The raw value never crosses the model-facing surface. `tinymcp` owns the+//! vault; this layer keeps the part that is this application's — publishing the+//! event that makes the prompt appear, and waiting for the answer.use std::collections::HashMap;-use std::path::PathBuf;use serde_json::{json, Value};-use uuid::Uuid;-use crate::core::event_bus::{publish_global, DomainEvent};+use crate::core::bus::BUS;+use crate::core::events::DomainEvent;use crate::openhuman::config::Config;-use crate::openhuman::mcp::config_servers::McpStdioClient;-use crate::openhuman::mcp::http_client::McpHttpClient;use crate::rpc::RpcOutcome;-use super::ops::resolve_command;-use super::setup::{self, SecretRef};-use super::types::{CommandKind, InstalledServer, ServerProvenance, SmitheryConnection, Transport};-use super::{connections, registry, store};+use tinymcp::SecretRef;++use super::helpers::{encode, inject_required_env_keys, require, resolve};+use super::types::{ConnStatus, ServerStatus};++/// Reads a map of credential names to handles.+fn parse_handles(raw: HashMap<String, String>) -> Result<HashMap<String, SecretRef>, String> {+ raw.into_iter()+ .map(|(name, handle)| {+ SecretRef::parse(&handle)+ .map(|parsed| (name, parsed))+ .ok_or_else(|| format!("invalid ref_id `{handle}`"))+ })+ .collect()+}++/// Renders a detail record with the credential names an install would need.+fn detail_payload(+ detail: &tinymcp_bus::RegistryServerDetail,+ required_env_keys: &[String],+) -> Result<Value, String> {+ let mut value = encode(detail)?;+ inject_required_env_keys(&mut value, required_env_keys);+ Ok(value)+}// ── search ───────────────────────────────────────────────────────────────────@@ -43,13 +57,21 @@ pub async fn mcp_setup_search() -> Result<RpcOutcome<Value>, String> {let page = page.unwrap_or(1);let page_size = page_size.unwrap_or(20);- let (servers, total_pages) =- registry::registry_search(config, query.as_deref(), None, page, page_size)- .await- .map_err(|e| e.to_string())?;++ let found = resolve(config)?+ .dynamic()+ .registry_search(query.as_deref(), page, page_size)+ .await+ .map_err(|error| error.to_string())?;++ let count = found.servers.len();Ok(RpcOutcome::new(- json!({ "servers": servers, "page": page, "total_pages": total_pages }),- vec![format!("setup_search returned {} servers", servers.len())],+ json!({+ "servers": found.servers,+ "page": found.page,+ "total_pages": found.total_pages,+ }),+ vec![format!("setup_search returned {count} servers")],))}@@ -59,632 +81,288 @@ pub async fn mcp_setup_get(config: &Config,qualified_name: String,) -> Result<RpcOutcome<Value>, String> {- let q = qualified_name.trim();- if q.is_empty() {- return Err("qualified_name must not be empty".to_string());- }- let detail = registry::registry_get(config, q)+ let qualified_name = require(&qualified_name, "qualified_name")?;++ let (detail, required_env_keys) = resolve(config)?+ .dynamic()+ .registry_get(&qualified_name).await- .map_err(|e| e.to_string())?;- let required_env_keys = collect_required_env_keys(&detail);- let mut value = serde_json::to_value(&detail).map_err(|e| format!("ser: {e}"))?;- if let Some(obj) = value.as_object_mut() {- obj.insert("required_env_keys".into(), json!(required_env_keys));- }+ .map_err(|error| error.to_string())?;+Ok(RpcOutcome::new(- json!({ "server": value }),- vec![format!("setup_get ok qualified_name={q}")],+ json!({ "server": detail_payload(&detail, &required_env_keys)? }),+ vec![format!("setup_get ok qualified_name={qualified_name}")],))}// ── request_secret ───────────────────────────────────────────────────────────+/// Mints a handle, asks the user for the value, and waits for it.+///+/// The wait is here rather than in `tinymcp` because the prompt is: this layer+/// publishes the event a user interface renders, so it is the layer that knows+/// when an answer can arrive.pub async fn mcp_setup_request_secret(+ config: &Config,key_name: String,prompt: String,) -> Result<RpcOutcome<Value>, String> {- let key_name = key_name.trim().to_string();- let prompt = prompt.trim().to_string();- if key_name.is_empty() {- return Err("key_name must not be empty".to_string());- }- if prompt.is_empty() {- return Err("prompt must not be empty".to_string());- }+ let key_name = require(&key_name, "key_name")?;+ let prompt = require(&prompt, "prompt")?;- let (r, rx) = setup::mint_request(&key_name).await;+ let service = resolve(config)?;+ let vault = service.dynamic().vault();+ let (handle, receiver) = vault.request(&key_name).await;- publish_global(DomainEvent::McpSetupSecretRequested {- ref_id: r.as_str().to_string(),+ BUS.publish(DomainEvent::McpSetupSecretRequested {+ ref_id: handle.as_str().to_string(),key_name: key_name.clone(),- prompt: prompt.clone(),+ prompt,});tracing::info!(- "[mcp-setup] request_secret ref={} key_name={} (awaiting UI submit)",- r.as_str(),- key_name+ handle = handle.as_str(),+ key_name,+ "[mcp-setup] awaiting a secret from the user");- setup::await_fulfillment(&r, rx)+ vault+ .await_fulfillment(&handle, receiver).await- .map_err(|e| e.to_string())?;+ .map_err(|error| error.to_string())?;++ tracing::info!(handle = handle.as_str(), "[mcp-setup] the secret arrived");- tracing::info!("[mcp-setup] request_secret fulfilled ref={}", r.as_str());Ok(RpcOutcome::new(- json!({ "ref": r.as_str(), "key_name": key_name }),+ json!({ "ref": handle.as_str(), "key_name": key_name }),vec![format!("collected secret for key={key_name}")],))}-// ── submit_secret (UI side) ──────────────────────────────────────────────────+// ── submit_secret ────────────────────────────────────────────────────────────pub async fn mcp_setup_submit_secret(+ config: &Config,ref_id: String,value: String,) -> Result<RpcOutcome<Value>, String> {- let r = SecretRef::parse(&ref_id).ok_or_else(|| format!("invalid ref_id `{ref_id}`"))?;- let ok = setup::fulfill(&r, value).await;- if !ok {- return Err(format!("ref {} unknown or already submitted", r.as_str()));+ let handle = SecretRef::parse(&ref_id).ok_or_else(|| format!("invalid ref_id `{ref_id}`"))?;++ let accepted = resolve(config)?+ .dynamic()+ .vault()+ .submit(&handle, value)+ .await;++ if !accepted {+ return Err(format!(+ "ref {} unknown or already submitted",+ handle.as_str()+ ));}+Ok(RpcOutcome::new(- json!({ "ref": r.as_str(), "fulfilled": true }),- vec![format!("submitted secret for ref={}", r.as_str())],+ json!({ "ref": handle.as_str(), "fulfilled": true }),+ vec![format!("submitted secret for ref={}", handle.as_str())],))}// ── test_connection ──────────────────────────────────────────────────────────+/// Dials a server with the collected credentials without installing it.+///+/// A dial that fails is reported as `ok: false` with the reason rather than as+/// an error: the operation asked for — finding out whether it works — succeeded,+/// and the agent needs the reason to tell the user what to fix.pub async fn mcp_setup_test_connection(config: &Config,qualified_name: String,env_refs: HashMap<String, String>,) -> Result<RpcOutcome<Value>, String> {- let q = qualified_name.trim();- if q.is_empty() {- return Err("qualified_name must not be empty".to_string());- }+ let qualified_name = require(&qualified_name, "qualified_name")?;+ let handles = parse_handles(env_refs)?;- let parsed_refs = parse_ref_map(env_refs)?;- let env = setup::resolve_refs(&parsed_refs)+ match resolve(config)?+ .dynamic()+ .setup_test_connection(&qualified_name, &handles).await- .map_err(|e| e.to_string())?;-- let detail = registry::registry_get(config, q)- .await- .map_err(|e| e.to_string())?;- let picked = pick_connection(&detail.connections).ok_or_else(|| {- format!("server `{q}` exposes neither stdio nor http_remote connections; nothing to test")- })?;-- let identity = config.mcp_client.client_identity.clone();-- // Scratch session — initialise + list_tools, then close. Nothing- // persisted. Errors bubble up so the agent can show them to the user.- let (init_ok, tools) = match picked.transport_kind() {- "stdio" => {- let (_kind, command, args) = resolve_command(q, Some(picked));- let cwd: Option<PathBuf> = None;- let client = McpStdioClient::new(command, args, env, cwd, identity);- if let Err(err) = client.initialize().await {- return Ok(RpcOutcome::new(- json!({ "ok": false, "error": err.to_string() }),- vec![format!("test_connection failed for {q}: {err}")],- ));- }- match client.list_tools().await {- Ok(t) => {- let _ = client.close_session().await;- (true, t)- }- Err(err) => {- let _ = client.close_session().await;- return Ok(RpcOutcome::new(- json!({ "ok": false, "error": err.to_string() }),- vec![format!("test_connection list_tools failed for {q}: {err}")],- ));- }- }- }- // HTTP-remote path: dial the published deployment_url over- // Streamable HTTP. No subprocess, no env injection needed at- // dial time (env vars for HTTP-remote installs are typically- // OAuth tokens that the McpHttpClient picks up from its own- // auth config — out of scope for this scratch test).- "http_remote" => {- let endpoint = picked.deployment_url.clone().unwrap_or_default();- if endpoint.is_empty() {- return Ok(RpcOutcome::new(- json!({ "ok": false, "error": "deployment_url is empty for http_remote connection" }),- vec![format!(- "test_connection failed for {q}: empty deployment_url"- )],- ));- }- let client = McpHttpClient::new(endpoint.clone(), 30);- if let Err(err) = client.initialize().await {- return Ok(RpcOutcome::new(- json!({ "ok": false, "error": err.to_string() }),- vec![format!("test_connection (http) failed for {q}: {err}")],- ));- }- match client.list_tools().await {- Ok(t) => {- let _ = client.close_session().await;- (true, t)- }- Err(err) => {- let _ = client.close_session().await;- return Ok(RpcOutcome::new(- json!({ "ok": false, "error": err.to_string() }),- vec![format!(- "test_connection (http) list_tools failed for {q}: {err}"- )],- ));- }- }- }- other => {- return Ok(RpcOutcome::new(- json!({ "ok": false, "error": format!("unsupported transport `{other}`") }),+ {+ Ok(tools) => {+ let tools = super::tools_safe_for_agent(&qualified_name, tools);+ let count = tools.len();+ Ok(RpcOutcome::new(+ json!({ "ok": true, "tools": tools }),vec![format!(- "test_connection failed for {q}: unsupported transport `{other}`"+ "test_connection ok for {qualified_name}: {count} tools")],- ));+ ))}- };-- let names: Vec<&str> = tools.iter().map(|t| t.name.as_str()).collect();- Ok(RpcOutcome::new(- json!({ "ok": init_ok, "tools": tools, "transport": picked.transport_kind() }),- vec![format!(- "test_connection ok for {q} via {}: {} tools ({:?})",- picked.transport_kind(),- tools.len(),- names- )],- ))-}--// ── install_and_connect ──────────────────────────────────────────────────────--pub async fn mcp_setup_install_and_connect(- config: &Config,- qualified_name: String,- env_refs: HashMap<String, String>,-) -> Result<RpcOutcome<Value>, String> {- let q = qualified_name.trim();- if q.is_empty() {- return Err("qualified_name must not be empty".to_string());- }-- let parsed_refs = parse_ref_map(env_refs)?;-- let detail = registry::registry_get(config, q)- .await- .map_err(|e| e.to_string())?;- let picked = pick_connection(&detail.connections).ok_or_else(|| {- format!(- "server `{q}` exposes neither stdio nor http_remote connections; nothing to install"- )- })?;-- // Branch on the picked transport. Stdio installs still populate- // command/args (current behavior). HTTP-remote installs leave them- // empty and stash the deployment URL in `transport`.- let (transport, command_kind, command, args) = build_install_transport(q, picked)?;-- // Consume refs only after `registry_get` succeeds — that way a- // misconfigured server name doesn't burn the user's collected- // secrets.- let env_pairs = setup::consume_refs(&parsed_refs)- .await- .map_err(|e| e.to_string())?;- let env_map: HashMap<String, String> = env_pairs.into_iter().collect();-- let server_id = Uuid::new_v4().to_string();- let now_ms = std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .map(|d| d.as_millis() as i64)- .unwrap_or(0);- let env_keys: Vec<String> = env_map.keys().cloned().collect();-- let server = InstalledServer {- server_id: server_id.clone(),- qualified_name: q.to_string(),- display_name: detail.display_name.clone(),- description: detail.description.clone(),- icon_url: detail.icon_url.clone(),- command_kind,- command,- args,- env_keys,- config: None,- installed_at: now_ms,- last_connected_at: None,- transport,- enabled: true,- provenance: ServerProvenance::Registry,- };-- store::insert_server(config, &server).map_err(|e| e.to_string())?;- store::set_env_values(config, &server_id, &env_map).map_err(|e| e.to_string())?;-- publish_global(DomainEvent::McpServerInstalled {- server_id: server_id.clone(),- qualified_name: server.qualified_name.clone(),- });-- // Connect immediately so the agent gets the tool list in the same- // response. A connect failure does not roll back the install — the- // user can retry via `mcp_clients_connect` later.- match connections::connect(config, &server).await {- Ok(tools) => Ok(RpcOutcome::new(- json!({- "server_id": server_id,- "status": "connected",- "tools": tools,- }),+ Err(error) => Ok(RpcOutcome::new(+ json!({ "ok": false, "error": error.to_string() }),vec![format!(- "install_and_connect ok server_id={server_id} tools={}",- tools.len()+ "test_connection failed for {qualified_name}: {error}")],)),- Err(err) => Ok(RpcOutcome::new(- json!({- "server_id": server_id,- "status": "installed_disconnected",- "error": err.to_string(),- }),- vec![format!(- "install_and_connect installed server_id={server_id} \- but connect failed: {err}"- )],- )),- }-}--// ── Helpers ──────────────────────────────────────────────────────────────────--fn parse_ref_map(raw: HashMap<String, String>) -> Result<HashMap<String, SecretRef>, String> {- let mut out = HashMap::with_capacity(raw.len());- for (k, v) in raw {- let r = SecretRef::parse(&v)- .ok_or_else(|| format!("env_refs[{k}] is not a valid secret ref"))?;- out.insert(k, r);- }- Ok(out)-}--/// Best-effort scan of a Smithery `config_schema` for required env keys.-/// Mirrors the legacy helper in `ops.rs` so the setup agent does not-/// depend on its private wiring.-pub(crate) fn collect_required_env_keys(- detail: &super::types::SmitheryServerDetail,-) -> Vec<String> {- // Derive required inputs from the connection the install will actually use,- // not from every connection. Hosted HTTP-remote is now preferred over a- // local stdio package (see `pick_connection`), so a server that offers both- // must not demand the stdio package's env vars for an install that connects- // over HTTP and never consumes them. `config_schema.properties` carries the- // stdio env vars or the HTTP remote's headers depending on the picked- // transport, so reading the picked connection covers both.- let Some(conn) = pick_connection(&detail.connections) else {- return Vec::new();- };- let mut keys = Vec::new();- if let Some(props) = conn- .config_schema- .as_ref()- .and_then(|schema| schema.get("properties"))- .and_then(Value::as_object)- {- for k in props.keys() {- if !keys.contains(k) {- keys.push(k.clone());- }- }}- keys}-// Compile-time anchor so a missing CommandKind import surfaces here, not-// at the call site.-#[allow(dead_code)]-const _: Option<CommandKind> = None;+// ── install_and_connect ──────────────────────────────────────────────────────-/// Choose the best [`SmitheryConnection`] from a registry detail response.+/// The schema's `status` discriminator, and the `error` that accompanies a+/// non-connected result.///-/// Preference order — **hosted remote first**:-/// 1. **Published `http_remote`** — the hosted endpoint. Connecting here avoids-/// spawning a local subprocess (no node/uvx runtime, no package resolution,-/// no broken-package failures) and routes auth to the server's OAuth/token-/// challenge, which is far more likely to succeed than a local spawn.-/// 2. **Any `http_remote`** (even unpublished).-/// 3. **Published `stdio`** — local subprocess fallback for servers with no-/// hosted endpoint.-/// 4. **Any `stdio`**.-/// 5. `None` — nothing dialable.+/// Split out as a pure function so both arms are testable without standing up a+/// registry and a reachable MCP server.///-/// Rationale: most registry servers expose both a stdio package and a hosted-/// remote. Preferring stdio meant the local subprocess had to spawn and find-/// its runtime + credentials, which fails for the majority of community-/// servers. Preferring the hosted remote eliminates that failure class. The-/// trade-off is that data flows to the hosted endpoint and a network is-/// required — a deliberate choice favouring "it connects" over local-first.-pub(super) fn pick_connection(connections: &[SmitheryConnection]) -> Option<&SmitheryConnection> {- // Treat the canonical wire names ("stdio", "http") AND the persisted- // dispatch kinds ("http_remote") as equivalent — registry payloads- // historically use "http" while our `Transport` discriminator uses- // "http_remote". `transport_kind` normalises that mapping.- let http_pub = connections- .iter()- .find(|c| c.transport_kind() == "http_remote" && c.published);- if http_pub.is_some() {- return http_pub;- }- let http_any = connections- .iter()- .find(|c| c.transport_kind() == "http_remote");- if http_any.is_some() {- return http_any;- }- let stdio_pub = connections- .iter()- .find(|c| c.transport_kind() == "stdio" && c.published);- if stdio_pub.is_some() {- return stdio_pub;+/// **Why the verdict comes from `ConnStatus` and not from the call's own+/// return.** `McpRegistry::setup_install_and_connect` turns a failed connect+/// into `Ok(ConnectOutcome { server_id, tools: vec![] })` — it logs the reason+/// and drops it. `ConnectOutcome` carries only `server_id` and `tools`, so a+/// failed connect is byte-identical to a server that connected and advertises+/// no tools, which is a legitimate state (a server exposing only resources or+/// prompts). Counting tools therefore cannot answer the question. The registry's+/// own `ConnStatus` can: it carries the live [`ServerStatus`] plus `last_error`.+///+/// A status we cannot read back is reported as `installed_disconnected` rather+/// than assumed connected: the install is confirmed either way, and claiming a+/// connection we did not observe is the failure mode this change exists to+/// remove (#6110).+///+/// The three inputs are deliberately distinct, because they are three different+/// facts and a caller acts on them differently:+///+/// - `Ok(Some(entry))` — the registry answered and knows this server.+/// - `Ok(None)` — the registry answered but has no row for it.+/// - `Err(reason)` — the status query itself failed. The reason is carried into+/// the message rather than being left in a log line the user never sees:+/// "the registry could not be asked" is not the same fact as "the server is+/// not connected", and a transient store error must not read as the latter.+fn classify_install_connect(+ status: Result<Option<&ConnStatus>, &str>,+) -> (&'static str, Option<String>) {+ match status {+ Ok(Some(entry)) if matches!(entry.status, ServerStatus::Connected) => ("connected", None),+ // `last_error` is the connect failure the registry recorded, not a+ // description of some later state: `connections::connect` builds a+ // `ConnectFailure` from the original error and stores it, and+ // `classify` surfaces it here. The synthetic arm below is reached only+ // when a non-connected server has no recorded failure at all (a+ // `Disabled` install, say), where naming the state is the whole answer.+ Ok(Some(entry)) => (+ "installed_disconnected",+ Some(entry.last_error.clone().unwrap_or_else(|| {+ format!(+ "installed, but the server is `{}` rather than connected",+ entry.status.as_str()+ )+ })),+ ),+ Ok(None) => (+ "installed_disconnected",+ Some("installed, but the registry reported no status row for this server".to_string()),+ ),+ Err(reason) => (+ "installed_disconnected",+ Some(format!(+ "installed, but the server's connection state could not be read back: {reason}"+ )),+ ),}- connections.iter().find(|c| c.transport_kind() == "stdio")}-/// Resolve the persisted [`Transport`] + launch command for an install from the-/// connection the picker selected. Stdio installs populate `command`/`args`;-/// HTTP-remote installs leave them empty and stash the deployment URL in the-/// `Transport`. Shared by the setup-agent path-/// ([`mcp_setup_install_and_connect`]) and the manual install dialog path-/// ([`super::ops::mcp_clients_install`]) so both transports behave identically-/// (issue #3039 gap A2).-pub(super) fn build_install_transport(+/// Builds the reply for `install_and_connect`, honouring the two conditional+/// fields the controller schema declares: `tools` iff `status == connected`,+/// `error` iff it is not. Pure, so the shape is testable without a registry.+fn install_and_connect_payload(+ server_id: &str,qualified_name: &str,- picked: &SmitheryConnection,-) -> Result<(Transport, CommandKind, String, Vec<String>), String> {- match picked.transport_kind() {- "http_remote" => {- let url = picked.deployment_url.clone().unwrap_or_default();- if url.is_empty() {- return Err(format!(- "server `{qualified_name}` http_remote connection has empty deployment_url"- ));- }- Ok((- Transport::HttpRemote { url },- CommandKind::Node, // unused for HTTP, but a sensible default- String::new(),- Vec::new(),- ))- }- _ => {- let (kind, command, args) = resolve_command(qualified_name, Some(picked));- Ok((Transport::Stdio, kind, command, args))- }- }+ status: &str,+ error: Option<String>,+ tools: Vec<tinymcp_bus::McpTool>,+) -> Value {+ let mut payload = serde_json::Map::new();+ payload.insert("server_id".to_string(), json!(server_id));+ payload.insert("qualified_name".to_string(), json!(qualified_name));+ payload.insert("status".to_string(), json!(status));+ if status == "connected" {+ payload.insert("tools".to_string(), json!(tools));+ }+ if let Some(error) = error {+ payload.insert("error".to_string(), json!(error));+ }+ Value::Object(payload)}-/// Normalise a [`SmitheryConnection::r#type`] string into the same vocabulary-/// the persisted [`Transport`] enum uses. The registry side uses `"http"`-/// in its DTOs; we route those into the `"http_remote"` install path.-pub(super) trait ConnectionKind {- fn transport_kind(&self) -> &str;-}--impl ConnectionKind for SmitheryConnection {- fn transport_kind(&self) -> &str {- match self.r#type.as_str() {- "stdio" => "stdio",- "http" | "http_remote" | "sse" => "http_remote",- other => other,- }- }-}--#[cfg(test)]-mod tests {- use super::*;-- fn conn(kind: &str, published: bool, url: Option<&str>) -> SmitheryConnection {- SmitheryConnection {- r#type: kind.to_string(),- deployment_url: url.map(String::from),- config_schema: None,- example_config: None,- published,- extra: std::collections::HashMap::new(),- }- }-- /// Hosted remote wins when both transports are offered — connecting to the- /// endpoint avoids the local-spawn failure class that broke most servers.- #[test]- fn pick_connection_prefers_http_over_stdio() {- let conns = vec![- conn("stdio", true, None),- conn("http", true, Some("https://x.io/mcp")),- ];- let picked = pick_connection(&conns).expect("http_remote should be picked");- assert_eq!(picked.transport_kind(), "http_remote");- }-- /// Even an *unpublished* hosted remote beats a published stdio package —- /// the hosted endpoint is still preferred over spawning locally.- #[test]- fn pick_connection_prefers_unpublished_http_over_published_stdio() {- let conns = vec![- conn("stdio", true, None),- conn("http", false, Some("https://x.io/mcp")),- ];- let picked = pick_connection(&conns).expect("http_remote should be picked");- assert_eq!(picked.transport_kind(), "http_remote");- }-- /// Published http beats unpublished http.- #[test]- fn pick_connection_prefers_published_http_first() {- let conns = vec![- conn("http", false, Some("https://any.io/mcp")),- conn("http", true, Some("https://pub.io/mcp")),- ];- let picked = pick_connection(&conns).expect("published http should win");- assert!(picked.published);- assert_eq!(picked.deployment_url.as_deref(), Some("https://pub.io/mcp"));- }-- /// With no hosted remote, stdio is the fallback — published stdio first.- #[test]- fn pick_connection_falls_back_to_stdio_when_no_http() {- let conns = vec![conn("stdio", false, None), conn("stdio", true, None)];- let picked = pick_connection(&conns).expect("published stdio should win");- assert_eq!(picked.transport_kind(), "stdio");- assert!(picked.published);- }-- /// When the server is HTTP-remote-only (the Smithery-typical case),- /// the picker returns the HTTP-remote connection instead of `None` —- /// this is the core gap the PR closes.- #[test]- fn pick_connection_falls_back_to_http_remote_when_no_stdio() {- let conns = vec![conn("http", true, Some("https://x.io/mcp"))];- let picked = pick_connection(&conns).expect("http_remote fallback");- assert_eq!(picked.transport_kind(), "http_remote");- assert_eq!(picked.deployment_url.as_deref(), Some("https://x.io/mcp"));- }-- /// Smithery DTOs use `"http"`, our `Transport` discriminator uses- /// `"http_remote"`. Normalisation pins both as the same install path.- #[test]- fn connection_kind_normalises_http_variants() {- assert_eq!(conn("http", true, None).transport_kind(), "http_remote");- assert_eq!(- conn("http_remote", true, None).transport_kind(),- "http_remote"- );- assert_eq!(conn("sse", true, None).transport_kind(), "http_remote");- assert_eq!(conn("stdio", true, None).transport_kind(), "stdio");- // Unknown kinds fall through untouched so the picker can ignore them.- assert_eq!(conn("ws", true, None).transport_kind(), "ws");- }-- /// No dialable connection → picker returns None so callers can return- /// a clean error instead of dialing garbage.- #[test]- fn pick_connection_returns_none_for_only_unknown_kinds() {- let conns = vec![conn("websocket-future", true, None)];- assert!(pick_connection(&conns).is_none());- }-- /// `build_install_transport` turns a picked stdio connection into a- /// `Transport::Stdio` with a resolved launch command (npx default when the- /// example_config has no command). Shared by both install paths (gap A2).- #[test]- fn build_install_transport_stdio_resolves_command() {- let picked = conn("stdio", true, None);- let (transport, _kind, command, args) =- build_install_transport("@scope/echo", &picked).expect("stdio install resolves");- assert_eq!(transport, Transport::Stdio);- assert_eq!(command, "npx");- assert_eq!(args, vec!["-y".to_string(), "@scope/echo".to_string()]);- }-- /// A picked http_remote connection becomes `Transport::HttpRemote { url }`- /// with empty command/args — the manual install dialog can now install- /// Smithery's HTTP-only listings (gap A2).- #[test]- fn build_install_transport_http_remote_uses_deployment_url() {- let picked = conn("http", true, Some("https://x.io/mcp"));- let (transport, _kind, command, args) =- build_install_transport("io.x/remote", &picked).expect("http install resolves");- assert_eq!(- transport,- Transport::HttpRemote {- url: "https://x.io/mcp".to_string()- }- );- assert!(command.is_empty());- assert!(args.is_empty());- }-- /// An http_remote connection with no deployment URL is a hard error rather- /// than installing an undialable server.- #[test]- fn build_install_transport_http_remote_requires_url() {- let picked = conn("http", true, None);- let err = build_install_transport("io.x/remote", &picked)- .expect_err("missing deployment_url must error");- assert!(err.contains("deployment_url"), "got: {err}");- }-- fn conn_schema(kind: &str, url: Option<&str>, props: &[&str]) -> SmitheryConnection {- let properties: serde_json::Map<String, Value> = props- .iter()- .map(|k| (k.to_string(), serde_json::json!({ "type": "string" })))- .collect();- SmitheryConnection {- r#type: kind.to_string(),- deployment_url: url.map(String::from),- config_schema: Some(serde_json::json!({ "properties": properties })),- example_config: None,- published: true,- extra: std::collections::HashMap::new(),- }- }-- fn detail_with(conns: Vec<SmitheryConnection>) -> super::super::types::SmitheryServerDetail {- super::super::types::SmitheryServerDetail {- qualified_name: "@t/s".to_string(),- display_name: "T".to_string(),- description: None,- icon_url: None,- connections: conns,- source: "smithery".to_string(),- extra: Default::default(),+pub async fn mcp_setup_install_and_connect(+ config: &Config,+ qualified_name: String,+ env_refs: HashMap<String, String>,+) -> Result<RpcOutcome<Value>, String> {+ let qualified_name = require(&qualified_name, "qualified_name")?;+ let handles = parse_handles(env_refs)?;++ let host = resolve(config)?;+ // Still `?`: this arm is reached only when the *install* failed, and there+ // is no server to report a status for. A failed *connect* does not come+ // through here — see `classify_install_connect`.+ let outcome = host+ .dynamic()+ .setup_install_and_connect(&qualified_name, &handles, None)+ .await+ .map_err(|error| error.to_string())?;++ let server_id = outcome.server_id.clone();+ let connection = match host.dynamic().status().await {+ Ok(all) => Ok(all.into_iter().find(|entry| entry.server_id == server_id)),+ Err(error) => {+ log::warn!(+ "[mcp_setup] install_and_connect could not read back status for \+ server_id={server_id}: {error}"+ );+ Err(error.to_string())}- }-- /// Mixed-transport server: install prefers the hosted http connection, so the- /// required keys must be the http connection's headers — NOT the stdio- /// package's env vars the install will never consume.- #[test]- fn required_env_keys_uses_picked_http_connection_headers() {- let detail = detail_with(vec![- conn_schema("stdio", None, &["STDIO_KEY"]),- conn_schema("http", Some("https://x.io/mcp"), &["Authorization"]),- ]);- let keys = collect_required_env_keys(&detail);- assert_eq!(keys, vec!["Authorization".to_string()]);- assert!(!keys.contains(&"STDIO_KEY".to_string()));- }-- /// Stdio-only server still surfaces its declared env vars.- #[test]- fn required_env_keys_stdio_only_returns_its_keys() {- let detail = detail_with(vec![conn_schema("stdio", None, &["API_KEY", "ENDPOINT"])]);- let keys = collect_required_env_keys(&detail);- assert!(keys.contains(&"API_KEY".to_string()));- assert!(keys.contains(&"ENDPOINT".to_string()));- }+ };+ let (status, error) = classify_install_connect(+ connection+ .as_ref()+ .map(Option::as_ref)+ .map_err(String::as_str),+ );+ let connected = status == "connected";- /// A picked http connection with no declared schema needs no user input.- #[test]- fn required_env_keys_http_without_schema_is_empty() {- let detail = detail_with(vec![conn("http", true, Some("https://x.io/mcp"))]);- assert!(collect_required_env_keys(&detail).is_empty());- }+ let tools = super::tools_safe_for_agent(&server_id, outcome.tools);+ let tool_count = u32::try_from(tools.len()).unwrap_or(u32::MAX);- /// No dialable connection (only an unknown transport) → no keys, mirroring- /// the install path which would reject the server entirely.- #[test]- fn required_env_keys_empty_when_no_dialable_connection() {- let detail = detail_with(vec![conn("ws", true, Some("wss://x.io"))]);- assert!(collect_required_env_keys(&detail).is_empty());- }+ BUS.publish(DomainEvent::McpServerInstalled {+ server_id: server_id.clone(),+ qualified_name: qualified_name.clone(),+ });+ // Only when the server is actually connected. This used to fire+ // unconditionally, so an install whose connect failed announced+ // `McpServerConnected { tool_count: 0 }` to every subscriber — the same+ // false claim the `status` field now avoids making to the caller (#6110).+ // A connected server with zero tools still publishes: `connected` is read+ // from `ServerStatus`, never from the tool count.+ if connected {+ BUS.publish(DomainEvent::McpServerConnected {+ server_id: server_id.clone(),+ tool_count,+ });+ }++ let log = if connected {+ format!("installed and connected server_id={server_id} tools={tool_count}")+ } else {+ format!(+ "installed server_id={server_id}, but connecting did not succeed: {}",+ error.as_deref().unwrap_or("no reason reported")+ )+ };+ Ok(RpcOutcome::new(+ install_and_connect_payload(&server_id, &qualified_name, status, error, tools),+ vec![log],+ ))}++#[cfg(test)]+#[path = "setup_ops_tests.rs"]+mod tests;