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
chore: remove the mcp_setup agent and its supporting infrastructure
Steven Enamakel35e3bda929f7
diff --git a/crates/openhuman-core/src/agent/registry/agents/mcp_setup/agent.toml b/crates/openhuman-core/src/agent/registry/agents/mcp_setup/agent.tomldeleted file mode 100644index 0aadfb432a..0000000000--- a/crates/openhuman-core/src/agent/registry/agents/mcp_setup/agent.toml+++ /dev/null@@ -1,28 +0,0 @@-id = "mcp_setup"-display_name = "MCP Setup Agent"-delegate_name = "setup_mcp_server"-when_to_use = "Walks the user through installing and connecting an MCP server end-to-end. Use when the user asks to add / install / set up an MCP server (e.g. \"set up the Notion MCP\", \"connect the GitHub MCP server\"). Owns the full flow: search registries → ask the user for any required secrets via a native dialog (raw values never enter the agent context) → test the connection → commit the install."-temperature = 0.3-max_iterations = 12-iteration_policy = "extended"-sandbox_mode = "none"-omit_identity = true-omit_memory_context = true-omit_safety_preamble = false--[model]-hint = "agentic"--[tools]-# Tight allowlist — the agent must not have shell, filesystem, network,-# or any other capability that could exfiltrate a leaked secret ref.-# Five `mcp_setup_*` tools plus `ask_user_question` for natural-language-# checkpoints; nothing else.-named = [- "mcp_setup_search",- "mcp_setup_get",- "mcp_setup_request_secret",- "mcp_setup_test_connection",- "mcp_setup_install_and_connect",- "ask_user_clarification",-]diff --git a/crates/openhuman-core/src/agent/registry/agents/mcp_setup/mod.rs b/crates/openhuman-core/src/agent/registry/agents/mcp_setup/mod.rsdeleted file mode 100644index 8bf84783cb..0000000000--- a/crates/openhuman-core/src/agent/registry/agents/mcp_setup/mod.rs+++ /dev/null@@ -1 +0,0 @@-pub mod prompt;diff --git a/crates/openhuman-core/src/agent/registry/agents/mcp_setup/prompt.md b/crates/openhuman-core/src/agent/registry/agents/mcp_setup/prompt.mddeleted file mode 100644index a551bb947b..0000000000--- a/crates/openhuman-core/src/agent/registry/agents/mcp_setup/prompt.md+++ /dev/null@@ -1,49 +0,0 @@-# MCP Setup Agent--You guide the user through installing and connecting one MCP server end-to-end. Each spawn handles **one** server — if the user asks for several, install them one at a time.--## Your tool surface--- **`mcp_setup_search`** — keyword search across all enabled MCP registries (Smithery + the official `modelcontextprotocol/registry`). Returns server summaries with a `source` tag so you can attribute results.-- **`mcp_setup_get`** — full detail for one server, including `required_env_keys` derived from its connection schema. Use this to know which secrets to ask for.-- **`mcp_setup_request_secret`** — pop a native input dialog in front of the user to collect one secret. Returns an opaque ref like `secret://abc123`. **The raw value never enters your context.** You only get the ref; the core resolves it to the real value just-in-time when you call test/install.-- **`mcp_setup_test_connection`** — dry-run: spawn the candidate server with the collected secret refs, list its tools, tear it down. Nothing persisted. Use this to validate the user's input before committing.-- **`mcp_setup_install_and_connect`** — commit: persist the install + the secrets (consuming the refs), connect immediately, return the tool list now available to the main agent.-- **`ask_user_clarification`** — natural-language checkpoints ("Did you mean X or Y?", "Ready to install?", etc.).--You have **nothing else** — no shell, no file I/O, no general HTTP. Stay inside this surface.--## Standard flow--1. **Identify the server.** From the user's request, search with `mcp_setup_search`. If multiple candidates match, summarise the top 2–3 and ask the user to confirm via `ask_user_clarification`. Prefer servers with `is_deployed: true` and higher `use_count` when the user is non-specific.-2. **Fetch detail.** Once a `qualified_name` is locked, call `mcp_setup_get(qualified_name)`. Read `required_env_keys` — that's your secret-collection checklist.-3. **Collect secrets, one per key.** For each key in `required_env_keys`, call `mcp_setup_request_secret({key_name, prompt})` where `prompt` is a plain-English instruction the user sees in the native dialog. Examples:- - `NOTION_API_KEY` → `"Paste your Notion integration token. Get one at notion.so/my-integrations → New integration → Internal."`- - `GITHUB_TOKEN` → `"Paste a GitHub personal access token with repo + read:user scopes."`- - `OPENAI_API_KEY` → `"Paste your OpenAI API key (starts with sk-)."`-- Store every returned `ref` in a local map keyed by `key_name`. The call blocks for up to 5 minutes per secret — that's fine, the user is at the dialog.-4. **Test.** Call `mcp_setup_test_connection({qualified_name, env_refs})` with the full ref map. Three outcomes:- - `ok: true` → list `tools` to the user for a sanity check; proceed to install.- - `ok: false` → surface `error` plainly. Common causes: wrong/expired token, missing scope, server-side bug. Offer to re-collect the offending secret (call `mcp_setup_request_secret` again for that one key, replace its ref in your map, retry test).-5. **Install.** On a successful test, call `mcp_setup_install_and_connect({qualified_name, env_refs})`. Two outcomes:- - `status: "connected"` → tell the user the server is live and list the new tools (`tools[].name`) so they know what's available.- - `status: "installed_disconnected"` → the install persisted but the live connection failed. Surface `error`; tell the user they can retry via Settings → MCP Servers → Reconnect.--## Hard rules--- **You never see raw secret values.** If you somehow do (a bug somewhere), abort, do not log or repeat the value, and tell the user to remove the leak.-- **Refs are opaque.** Don't try to deserialise, decode, or reason about the `secret://` payload. It's a random hex handle, nothing more.-- **One server per spawn.** If the user asks for two, finish one cleanly, then suggest they spawn you again for the second.-- **Don't fabricate `required_env_keys`.** Pull them from `mcp_setup_get`. Asking the user for a key the server doesn't need wastes their time and may leak unrelated credentials into our store.-- **Don't skip the test step.** Always `test_connection` before `install_and_connect` so the user has a chance to fix typos before we persist anything to the secrets store.-- **Be honest about failures.** If a server's config is so under-documented that you can't figure out the keys, say so and stop. Don't guess.--## Telemetry / privacy reminders--- Tool calls are logged. Calls show `key_name` (safe) and `ref` (opaque). They never show secret values.-- The user's submitted secret value travels: native UI dialog → core IPC → `SETUP_SECRETS` in-memory map → encrypted `mcp_client_env` table on success. It never round-trips through the LLM at any point.--## When you're done--Return a short summary: which server, which tools are now available, and any caveats (e.g. "Notion integration only sees pages you've explicitly shared with it — share at least one page before using `notion_get_page`."). Hand control back to the user / orchestrator.diff --git a/crates/openhuman-core/src/agent/registry/agents/mcp_setup/prompt.rs b/crates/openhuman-core/src/agent/registry/agents/mcp_setup/prompt.rsdeleted file mode 100644index 6404a956dc..0000000000--- a/crates/openhuman-core/src/agent/registry/agents/mcp_setup/prompt.rs+++ /dev/null@@ -1,41 +0,0 @@-//! System prompt builder for the `mcp_setup` built-in agent.-//!-//! Straightforward: render the static archetype, then append the-//! tool block so the model sees the five `mcp_setup_*` tool schemas-//! plus `ask_user_clarification` (filtered down by the harness from the-//! `agent.toml` allowlist).--use crate::agent::prompts::{render_tools, render_user_files, render_workspace, PromptContext};-use anyhow::Result;--const ARCHETYPE: &str = include_str!("prompt.md");--pub fn build(ctx: &PromptContext<'_>) -> Result<String> {- let mut out = String::with_capacity(4096);- out.push_str(ARCHETYPE.trim_end());- out.push_str("\n\n");-- let user_files = render_user_files(ctx)?;- if !user_files.trim().is_empty() {- out.push_str(user_files.trim_end());- out.push_str("\n\n");- }-- let tools = render_tools(ctx)?;- if !tools.trim().is_empty() {- out.push_str(tools.trim_end());- out.push_str("\n\n");- }-- let workspace = render_workspace(ctx)?;- if !workspace.trim().is_empty() {- out.push_str(workspace.trim_end());- out.push('\n');- }-- Ok(out)-}--#[cfg(test)]-#[path = "prompt_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/agent/registry/agents/mcp_setup/prompt_tests.rs b/crates/openhuman-core/src/agent/registry/agents/mcp_setup/prompt_tests.rsdeleted file mode 100644index 316cb075b3..0000000000--- a/crates/openhuman-core/src/agent/registry/agents/mcp_setup/prompt_tests.rs+++ /dev/null@@ -1,56 +0,0 @@-use super::*;-use crate::agent::prompts::{LearnedContextData, ToolCallFormat};-use std::collections::HashSet;--fn empty_ctx() -> PromptContext<'static> {- static EMPTY_VISIBLE: std::sync::OnceLock<HashSet<String>> = std::sync::OnceLock::new();- let visible = EMPTY_VISIBLE.get_or_init(HashSet::new);- PromptContext {- workspace_dir: std::path::Path::new("."),- model_name: "test",- agent_id: "mcp_setup",- tools: &[],- workflows: &[],- dispatcher_instructions: "",- learned: LearnedContextData::default(),- visible_tool_names: visible,- tool_call_format: ToolCallFormat::PFormat,- connected_integrations: &[],- connected_identities_md: String::new(),- include_profile: false,- include_memory_md: false,- curated_snapshot: None,- user_identity: None,- personality_roster: vec![],- agents_md_global: None,- agents_md_local: None,- }-}--#[test]-fn build_returns_nonempty_body() {- let body = build(&empty_ctx()).unwrap();- assert!(body.contains("MCP Setup Agent"));-}--#[test]-fn archetype_documents_opaque_ref_invariant() {- let body = build(&empty_ctx()).unwrap();- assert!(body.contains("never enters your context"));- assert!(body.contains("secret://"));-}--#[test]-fn archetype_documents_standard_flow_steps() {- let body = build(&empty_ctx()).unwrap();- for needle in [- "mcp_setup_search",- "mcp_setup_get",- "mcp_setup_request_secret",- "mcp_setup_test_connection",- "mcp_setup_install_and_connect",- "ask_user_clarification",- ] {- assert!(body.contains(needle), "prompt missing `{needle}`");- }-}diff --git a/crates/openhuman-core/src/mcp/registry/schemas/setup_handlers.rs b/crates/openhuman-core/src/mcp/registry/schemas/setup_handlers.rsdeleted file mode 100644index 22634e991b..0000000000--- a/crates/openhuman-core/src/mcp/registry/schemas/setup_handlers.rs+++ /dev/null@@ -1,90 +0,0 @@-//! `mcp_setup` handler implementations — deserialise params and delegate-//! to `setup_ops.rs`.--use crate::mcp::registry::schemas::params::read_optional_string;-use crate::mcp::registry::schemas::params::read_optional_u32;-use serde_json::{Map, Value};--use crate::config::rpc as config_rpc;-use crate::core::all::ControllerFuture;--use super::params::{read_required, to_json};--pub(super) 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::mcp::registry::setup_ops::mcp_setup_search(&config, query, page, page_size)- .await?,- )- })-}--pub(super) 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::mcp::registry::setup_ops::mcp_setup_get(&config, qualified_name).await?)- })-}--pub(super) 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")?;- let config = config_rpc::load_config_with_timeout().await?;- to_json(- crate::mcp::registry::setup_ops::mcp_setup_request_secret(&config, key_name, prompt)- .await?,- )- })-}--pub(super) 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")?;- let config = config_rpc::load_config_with_timeout().await?;- to_json(- crate::mcp::registry::setup_ops::mcp_setup_submit_secret(&config, ref_id, value)- .await?,- )- })-}--pub(super) 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::mcp::registry::setup_ops::mcp_setup_test_connection(- &config,- qualified_name,- env_refs,- )- .await?,- )- })-}--pub(super) 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::mcp::registry::setup_ops::mcp_setup_install_and_connect(- &config,- qualified_name,- env_refs,- )- .await?,- )- })-}diff --git a/crates/openhuman-core/src/mcp/registry/schemas/setup_registry.rs b/crates/openhuman-core/src/mcp/registry/schemas/setup_registry.rsdeleted file mode 100644index 89499884a1..0000000000--- a/crates/openhuman-core/src/mcp/registry/schemas/setup_registry.rs+++ /dev/null@@ -1,249 +0,0 @@-//! All setup-agent schemas under the `mcp_setup` RPC namespace. Kept-//! separate from `registry.rs` so the setup surface can evolve-//! independently of the existing `mcp_clients_*` controllers.--use crate::core::{ControllerSchema, FieldSchema, TypeSchema};--pub(crate) 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: "qualified_name",- ty: TypeSchema::String,- comment: "Registry qualified name the install was made from — echoed back so a caller need not correlate on the request.",- 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,- }],- },- }-}diff --git a/crates/openhuman-core/src/mcp/registry/setup_ops.rs b/crates/openhuman-core/src/mcp/registry/setup_ops.rsdeleted file mode 100644index 2a45839671..0000000000--- a/crates/openhuman-core/src/mcp/registry/setup_ops.rs+++ /dev/null@@ -1,368 +0,0 @@-//! RPC handlers for the guided setup flow (`mcp_setup`).-//!-//! 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.-//!-//! # The secret handles have not changed shape-//!-//! 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 serde_json::{json, Value};--use crate::config::Config;-use crate::core::bus::BUS;-use crate::core::events::DomainEvent;-use crate::rpc::RpcOutcome;--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 ───────────────────────────────────────────────────────────────────--pub async fn mcp_setup_search(- config: &Config,- query: 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);-- 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": found.servers,- "page": found.page,- "total_pages": found.total_pages,- }),- vec![format!("setup_search returned {count} servers")],- ))-}--// ── get ──────────────────────────────────────────────────────────────────────--pub async fn mcp_setup_get(- config: &Config,- qualified_name: String,-) -> Result<RpcOutcome<Value>, String> {- let qualified_name = require(&qualified_name, "qualified_name")?;-- let (detail, required_env_keys) = resolve(config)?- .dynamic()- .registry_get(&qualified_name)- .await- .map_err(|error| error.to_string())?;-- Ok(RpcOutcome::new(- 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 = require(&key_name, "key_name")?;- let prompt = require(&prompt, "prompt")?;-- let service = resolve(config)?;- let vault = service.dynamic().vault();- let (handle, receiver) = vault.request(&key_name).await;-- BUS.publish(DomainEvent::McpSetupSecretRequested {- ref_id: handle.as_str().to_string(),- key_name: key_name.clone(),- prompt,- });- tracing::info!(- handle = handle.as_str(),- key_name,- "[mcp-setup] awaiting a secret from the user"- );-- vault- .await_fulfillment(&handle, receiver)- .await- .map_err(|error| error.to_string())?;-- tracing::info!(handle = handle.as_str(), "[mcp-setup] the secret arrived");-- Ok(RpcOutcome::new(- json!({ "ref": handle.as_str(), "key_name": key_name }),- vec![format!("collected secret for key={key_name}")],- ))-}--// ── submit_secret ────────────────────────────────────────────────────────────--pub async fn mcp_setup_submit_secret(- config: &Config,- ref_id: String,- value: String,-) -> Result<RpcOutcome<Value>, String> {- 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": 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 qualified_name = require(&qualified_name, "qualified_name")?;- let handles = parse_handles(env_refs)?;-- match resolve(config)?- .dynamic()- .setup_test_connection(&qualified_name, &handles)- .await- {- 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 ok for {qualified_name}: {count} tools"- )],- ))- }- Err(error) => Ok(RpcOutcome::new(- json!({ "ok": false, "error": error.to_string() }),- vec![format!(- "test_connection failed for {qualified_name}: {error}"- )],- )),- }-}--// ── install_and_connect ──────────────────────────────────────────────────────--/// The schema's `status` discriminator, and the `error` that accompanies a-/// non-connected result.-///-/// Split out as a pure function so both arms are testable without standing up a-/// registry and a reachable MCP server.-///-/// **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}"- )),- ),- }-}--/// 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,- 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)-}--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())- }- };- let (status, error) = classify_install_connect(- connection- .as_ref()- .map(Option::as_ref)- .map_err(String::as_str),- );- let connected = status == "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::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;diff --git a/crates/openhuman-core/src/mcp/registry/setup_ops_tests.rs b/crates/openhuman-core/src/mcp/registry/setup_ops_tests.rsdeleted file mode 100644index 2ac204d70f..0000000000--- a/crates/openhuman-core/src/mcp/registry/setup_ops_tests.rs+++ /dev/null@@ -1,242 +0,0 @@-//! Unit tests for the guided setup handlers.-//!-//! The handle parsing is what is testable without a running service, and it is-//! the part that matters: a handle the agent invented must be refused with a-//! message naming it, not silently looked up and missed.--use super::*;--#[test]-fn a_handle_map_is_parsed() {- let parsed = parse_handles(HashMap::from([(- "API_KEY".to_string(),- "secret://abc123".to_string(),- )]))- .expect("a valid handle");-- assert_eq!(parsed["API_KEY"].as_str(), "secret://abc123");-}--#[test]-fn a_bare_handle_is_accepted() {- // A caller may pass back either form.- let parsed = parse_handles(HashMap::from([(- "API_KEY".to_string(),- "abc123".to_string(),- )]))- .expect("a bare handle");-- assert_eq!(parsed["API_KEY"].as_str(), "secret://abc123");-}--#[test]-fn an_invented_handle_is_refused_and_named() {- let error = parse_handles(HashMap::from([(- "API_KEY".to_string(),- "not-a-handle".to_string(),- )]))- .expect_err("an invented handle");-- assert!(error.contains("not-a-handle"), "{error}");-}--#[test]-fn an_empty_handle_map_parses_to_nothing() {- assert!(parse_handles(HashMap::new()).unwrap().is_empty());-}--// ── install_and_connect status reporting (#6110) ─────────────────────────────-//-// `mcp_setup_install_and_connect` declared a `status` discriminator it never-// emitted, and the `installed_disconnected` half of it was unobservable: the-// registry's `setup_install_and_connect` turns a failed connect into-// `Ok(ConnectOutcome { server_id, tools: vec![] })`, so the handler reported-// success — and published `McpServerConnected` — for a server that never came-// up. These pin the classification and the reply shape; the two functions are-// pure so neither needs a registry or a reachable MCP server.--use super::super::types::{ConnStatus, ServerStatus};--fn conn_status(status: ServerStatus, last_error: Option<&str>) -> ConnStatus {- ConnStatus {- server_id: "srv-1".to_string(),- qualified_name: "acme/thing".to_string(),- display_name: "Thing".to_string(),- status,- tool_count: 0,- last_error: last_error.map(str::to_string),- auth_hint: None,- }-}--#[test]-fn a_connected_server_classifies_as_connected_with_no_error() {- let entry = conn_status(ServerStatus::Connected, None);- assert_eq!(- super::classify_install_connect(Ok(Some(&entry))),- ("connected", None)- );-}--#[test]-fn a_connected_server_with_no_tools_is_still_connected() {- // The state the old unconditional-success path existed to protect: a- // server exposing only resources or prompts connects with zero tools.- // `connected` reads from `ServerStatus`, never from the tool count.- let mut entry = conn_status(ServerStatus::Connected, None);- entry.tool_count = 0;- assert_eq!(- super::classify_install_connect(Ok(Some(&entry))).0,- "connected"- );-}--#[test]-fn a_failed_connect_reports_installed_disconnected_and_carries_the_reason() {- let entry = conn_status(ServerStatus::Error, Some("dial tcp: connection refused"));- let (status, error) = super::classify_install_connect(Ok(Some(&entry)));- assert_eq!(status, "installed_disconnected");- assert_eq!(error.as_deref(), Some("dial tcp: connection refused"));-}--#[test]-fn a_401_reports_installed_disconnected_rather_than_connected() {- // `Unauthorized` is reachable, distinct from `Error`, and is emphatically- // not connected — a caller offering a sign-in path needs to see that.- let entry = conn_status(ServerStatus::Unauthorized, Some("server answered 401"));- let (status, error) = super::classify_install_connect(Ok(Some(&entry)));- assert_eq!(status, "installed_disconnected");- assert_eq!(error.as_deref(), Some("server answered 401"));-}--#[test]-fn a_non_connected_status_without_a_reason_still_names_the_state() {- // `last_error` is `Option`; the schema's `error` is documented as present- // whenever `status != connected`, so it must not go missing here.- let entry = conn_status(ServerStatus::Disconnected, None);- let (status, error) = super::classify_install_connect(Ok(Some(&entry)));- assert_eq!(status, "installed_disconnected");- assert!(- error.as_deref().is_some_and(|e| e.contains("disconnected")),- "the reason must name the state it saw, got: {error:?}"- );-}--#[test]-fn a_missing_status_row_is_not_assumed_connected() {- let (status, error) = super::classify_install_connect(Ok(None));- assert_eq!(- status, "installed_disconnected",- "a server with no status row must never be reported as connected"- );- assert!(- error- .as_deref()- .is_some_and(|e| e.contains("no status row")),- "and it must say which of the two unknowns it hit, got: {error:?}"- );-}--#[test]-fn a_failed_status_query_surfaces_its_own_reason() {- // The status *method* failing is a different fact from the server being- // disconnected, and the reason must reach the caller rather than only a- // log line (tinysweeper on #6132).- let (status, error) = super::classify_install_connect(Err("store is poisoned"));- assert_eq!(status, "installed_disconnected");- let error = error.expect("a failed read-back must carry a reason");- assert!(- error.contains("store is poisoned"),- "the underlying error must be surfaced, not swallowed: {error}"- );- assert!(- error.contains("could not be read back"),- "and it must say the read-back is what failed: {error}"- );-}--#[test]-fn the_connected_payload_carries_tools_and_no_error() {- let payload =- super::install_and_connect_payload("srv-1", "acme/thing", "connected", None, Vec::new());- assert_eq!(- payload.get("server_id").and_then(|v| v.as_str()),- Some("srv-1")- );- assert_eq!(- payload.get("qualified_name").and_then(|v| v.as_str()),- Some("acme/thing")- );- assert_eq!(- payload.get("status").and_then(|v| v.as_str()),- Some("connected")- );- assert!(- payload.get("tools").is_some(),- "schema declares `tools` iff status == connected: {payload}"- );- assert!(- payload.get("error").is_none(),- "schema declares `error` iff status != connected: {payload}"- );-}--#[test]-fn the_disconnected_payload_carries_the_error_and_omits_tools() {- let payload = super::install_and_connect_payload(- "srv-1",- "acme/thing",- "installed_disconnected",- Some("connection refused".to_string()),- Vec::new(),- );- assert_eq!(- payload.get("status").and_then(|v| v.as_str()),- Some("installed_disconnected")- );- assert_eq!(- payload.get("error").and_then(|v| v.as_str()),- Some("connection refused")- );- assert!(- payload.get("tools").is_none(),- "`tools` must be absent when the server did not connect: {payload}"- );- // `server_id` stays required in both arms — the install did happen, and it- // is what a caller needs to retry or remove the half-finished server.- assert_eq!(- payload.get("server_id").and_then(|v| v.as_str()),- Some("srv-1")- );-}--#[test]-fn every_declared_output_name_is_one_the_handler_can_emit() {- // The drift #6110 is about: the catalog promised four fields, the handler- // emitted three others. Walk the declared set against both reply arms.- let declared: Vec<&str> = super::super::schemas::setup_schemas("install_and_connect")- .outputs- .iter()- .map(|field| field.name)- .collect();- let connected = super::install_and_connect_payload("s", "q", "connected", None, Vec::new());- let disconnected = super::install_and_connect_payload(- "s",- "q",- "installed_disconnected",- Some("boom".to_string()),- Vec::new(),- );- for name in ["server_id", "qualified_name", "status", "tools", "error"] {- assert!(- declared.contains(&name),- "`{name}` is emitted but not declared: {declared:?}"- );- }- for name in &declared {- assert!(- connected.get(*name).is_some() || disconnected.get(*name).is_some(),- "`{name}` is declared but neither reply arm emits it"- );- }-}diff --git a/crates/openhuman-core/src/tools/impl/network/mcp_setup.rs b/crates/openhuman-core/src/tools/impl/network/mcp_setup.rsdeleted file mode 100644index dcb728a51c..0000000000--- a/crates/openhuman-core/src/tools/impl/network/mcp_setup.rs+++ /dev/null@@ -1,360 +0,0 @@-//! Agent-facing tool wrappers around `mcp::registry::setup_ops`.-//!-//! Six thin tools the `mcp_setup` sub-agent uses to walk the user-//! through installing an MCP server. They are intentionally simple —-//! the real logic lives in-//! [`crate::mcp::registry::setup_ops`]; these structs only-//! marshall args ↔ `serde_json::Value` and turn `RpcOutcome` into a-//! `ToolResult`.-//!-//! Secret values **never** pass through these tools. `request_secret`-//! returns an opaque `secret://<hex>` ref; the agent stores the ref and-//! passes it back into `test_connection` / `install_and_connect` which-//! resolve it inside the core process.--use std::collections::HashMap;-use std::sync::Arc;--use async_trait::async_trait;-use serde_json::{json, Value};--use crate::config::Config;-use crate::mcp::registry::setup_ops;-use tinytools::{PermissionLevel, Tool, ToolCategory, ToolResult};--// ── Helpers ──────────────────────────────────────────────────────────────────--fn outcome_to_result(- outcome: Result<crate::rpc::RpcOutcome<Value>, String>,-) -> anyhow::Result<ToolResult> {- match outcome {- Ok(out) => Ok(ToolResult::json(out.value)),- Err(err) => Ok(ToolResult::error(err)),- }-}--fn read_str(args: &Value, key: &str) -> Result<String, String> {- args.get(key)- .and_then(Value::as_str)- .map(str::to_string)- .ok_or_else(|| format!("missing required string `{key}`"))-}--fn read_str_opt(args: &Value, key: &str) -> Option<String> {- args.get(key)- .and_then(Value::as_str)- .map(str::to_string)- .filter(|s| !s.is_empty())-}--fn read_u32_opt(args: &Value, key: &str) -> Option<u32> {- args.get(key).and_then(Value::as_u64).map(|v| v as u32)-}--fn read_str_map(args: &Value, key: &str) -> Result<HashMap<String, String>, String> {- let v = args- .get(key)- .ok_or_else(|| format!("missing required object `{key}`"))?;- let obj = v- .as_object()- .ok_or_else(|| format!("`{key}` must be an object"))?;- let mut out = HashMap::with_capacity(obj.len());- for (k, v) in obj {- let s = v- .as_str()- .ok_or_else(|| format!("`{key}[{k}]` must be a string"))?;- out.insert(k.clone(), s.to_string());- }- Ok(out)-}--// ── mcp_setup_search ─────────────────────────────────────────────────────────--pub struct McpSetupSearchTool {- config: Arc<Config>,-}--impl McpSetupSearchTool {- pub fn new(config: Arc<Config>) -> Self {- Self { config }- }-}--#[async_trait]-impl Tool for McpSetupSearchTool {- fn name(&self) -> &str {- "mcp_setup_search"- }-- fn description(&self) -> &str {- "Search all enabled MCP server registries (Smithery + modelcontextprotocol/registry). \- Returns merged results tagged with the upstream `source`. Use to discover candidate \- servers by keyword (e.g. 'notion', 'filesystem', 'github')."- }-- fn parameters_schema(&self) -> Value {- json!({- "type": "object",- "properties": {- "query": { "type": "string", "description": "Free-text search query." },- "page": { "type": "integer", "description": "1-based page number (default 1)." },- "page_size": { "type": "integer", "description": "Results per page (default 20)." }- }- })- }-- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::ReadOnly- }-- fn category(&self) -> ToolCategory {- ToolCategory::System- }-- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {- let query = read_str_opt(&args, "query");- let page = read_u32_opt(&args, "page");- let page_size = read_u32_opt(&args, "page_size");- outcome_to_result(setup_ops::mcp_setup_search(&self.config, query, page, page_size).await)- }-}--// ── mcp_setup_get ────────────────────────────────────────────────────────────--pub struct McpSetupGetTool {- config: Arc<Config>,-}--impl McpSetupGetTool {- pub fn new(config: Arc<Config>) -> Self {- Self { config }- }-}--#[async_trait]-impl Tool for McpSetupGetTool {- fn name(&self) -> &str {- "mcp_setup_get"- }-- fn description(&self) -> &str {- "Fetch full detail for one MCP server, including the `required_env_keys` array derived \- from its connection schema. Use to plan which secrets to request from the user."- }-- fn parameters_schema(&self) -> Value {- json!({- "type": "object",- "properties": {- "qualified_name": {- "type": "string",- "description": "Registry qualified name (e.g. `@notion/server-notion`). \- May be prefixed with `<source>::` to pin a registry."- }- },- "required": ["qualified_name"]- })- }-- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::ReadOnly- }-- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {- let qualified_name = match read_str(&args, "qualified_name") {- Ok(v) => v,- Err(e) => return Ok(ToolResult::error(e)),- };- outcome_to_result(setup_ops::mcp_setup_get(&self.config, qualified_name).await)- }-}--// ── mcp_setup_request_secret ─────────────────────────────────────────────────--pub struct McpSetupRequestSecretTool {- config: Arc<Config>,-}--impl McpSetupRequestSecretTool {- pub fn new(config: Arc<Config>) -> Self {- Self { config }- }-}--#[async_trait]-impl Tool for McpSetupRequestSecretTool {- fn name(&self) -> &str {- "mcp_setup_request_secret"- }-- fn description(&self) -> &str {- "Ask the user to provide a secret value (API key, OAuth token, etc.) via a native UI \- prompt. Returns an opaque ref like `secret://<hex>`. The raw value never enters this \- agent's context — only the ref does. Pass the ref back into `mcp_setup_test_connection` \- or `mcp_setup_install_and_connect`. Blocks for up to 5 minutes waiting on the user."- }-- fn parameters_schema(&self) -> Value {- json!({- "type": "object",- "properties": {- "key_name": {- "type": "string",- "description": "Env-var name (e.g. `NOTION_API_KEY`). Shown to the user as the field label."- },- "prompt": {- "type": "string",- "description": "Plain-English explanation the user sees, e.g. 'Paste your Notion integration token from notion.so/my-integrations.'"- }- },- "required": ["key_name", "prompt"]- })- }-- fn permission_level(&self) -> PermissionLevel {- // No filesystem / network — purely an IPC handshake. ReadOnly is- // wrong (it's user-input), but Write is too strong. The harness- // gates by `< Execute`, so ReadOnly keeps the agent able to call- // it.- PermissionLevel::ReadOnly- }-- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {- let key_name = match read_str(&args, "key_name") {- Ok(v) => v,- Err(e) => return Ok(ToolResult::error(e)),- };- let prompt = match read_str(&args, "prompt") {- Ok(v) => v,- Err(e) => return Ok(ToolResult::error(e)),- };- outcome_to_result(setup_ops::mcp_setup_request_secret(&self.config, key_name, prompt).await)- }-}--// ── mcp_setup_test_connection ────────────────────────────────────────────────--pub struct McpSetupTestConnectionTool {- config: Arc<Config>,-}--impl McpSetupTestConnectionTool {- pub fn new(config: Arc<Config>) -> Self {- Self { config }- }-}--#[async_trait]-impl Tool for McpSetupTestConnectionTool {- fn name(&self) -> &str {- "mcp_setup_test_connection"- }-- fn description(&self) -> &str {- "Dry-run install: spawn the candidate MCP server in a scratch process with the supplied \- secret refs, list its tools, tear it down. Nothing is persisted. Returns \- `{ ok: true, tools: [...] }` on success or `{ ok: false, error: ... }` on failure — \- use this to validate the user's secrets before committing."- }-- fn parameters_schema(&self) -> Value {- json!({- "type": "object",- "properties": {- "qualified_name": {- "type": "string",- "description": "Registry qualified name."- },- "env_refs": {- "type": "object",- "description": "Map `{ENV_KEY: \"secret://<hex>\"}` of refs collected from `mcp_setup_request_secret`.",- "additionalProperties": { "type": "string" }- }- },- "required": ["qualified_name", "env_refs"]- })- }-- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::Execute- }-- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {- let qualified_name = match read_str(&args, "qualified_name") {- Ok(v) => v,- Err(e) => return Ok(ToolResult::error(e)),- };- let env_refs = match read_str_map(&args, "env_refs") {- Ok(v) => v,- Err(e) => return Ok(ToolResult::error(e)),- };- outcome_to_result(- setup_ops::mcp_setup_test_connection(&self.config, qualified_name, env_refs).await,- )- }-}--// ── mcp_setup_install_and_connect ────────────────────────────────────────────--pub struct McpSetupInstallAndConnectTool {- config: Arc<Config>,-}--impl McpSetupInstallAndConnectTool {- pub fn new(config: Arc<Config>) -> Self {- Self { config }- }-}--#[async_trait]-impl Tool for McpSetupInstallAndConnectTool {- fn name(&self) -> &str {- "mcp_setup_install_and_connect"- }-- fn description(&self) -> &str {- "Commit: persist the MCP server install + the user's secrets (consuming the refs), then \- connect immediately. Returns the new `server_id` and (on success) the tool list now \- available to the agent. Only call after `mcp_setup_test_connection` returned ok."- }-- fn parameters_schema(&self) -> Value {- json!({- "type": "object",- "properties": {- "qualified_name": {- "type": "string",- "description": "Registry qualified name."- },- "env_refs": {- "type": "object",- "description": "Same shape as `mcp_setup_test_connection`. Refs are consumed (removed from the in-memory map) on success.",- "additionalProperties": { "type": "string" }- }- },- "required": ["qualified_name", "env_refs"]- })- }-- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::Write- }-- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {- let qualified_name = match read_str(&args, "qualified_name") {- Ok(v) => v,- Err(e) => return Ok(ToolResult::error(e)),- };- let env_refs = match read_str_map(&args, "env_refs") {- Ok(v) => v,- Err(e) => return Ok(ToolResult::error(e)),- };- outcome_to_result(- setup_ops::mcp_setup_install_and_connect(&self.config, qualified_name, env_refs).await,- )- }-}--#[cfg(test)]-#[path = "mcp_setup_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/tools/impl/network/mcp_setup_tests.rs b/crates/openhuman-core/src/tools/impl/network/mcp_setup_tests.rsdeleted file mode 100644index 35c542eabb..0000000000--- a/crates/openhuman-core/src/tools/impl/network/mcp_setup_tests.rs+++ /dev/null@@ -1,29 +0,0 @@-use super::*;--#[test]-fn names_are_stable() {- let cfg = Arc::new(Config::default());- assert_eq!(- McpSetupSearchTool::new(cfg.clone()).name(),- "mcp_setup_search"- );- assert_eq!(McpSetupGetTool::new(cfg.clone()).name(), "mcp_setup_get");- assert_eq!(- McpSetupRequestSecretTool::new(cfg.clone()).name(),- "mcp_setup_request_secret"- );- assert_eq!(- McpSetupTestConnectionTool::new(cfg.clone()).name(),- "mcp_setup_test_connection"- );- assert_eq!(- McpSetupInstallAndConnectTool::new(cfg).name(),- "mcp_setup_install_and_connect"- );-}--#[test]-fn read_str_map_rejects_non_string_values() {- let args = json!({ "env_refs": { "K": 42 } });- assert!(read_str_map(&args, "env_refs").is_err());-}diff --git a/tests/mcp_setup_e2e.rs b/tests/mcp_setup_e2e.rsdeleted file mode 100644index ba280cd9b4..0000000000--- a/tests/mcp_setup_e2e.rs+++ /dev/null@@ -1,117 +0,0 @@-//! End-to-end test for the MCP setup-agent flow.-//!-//! Exercises the ref machinery + install_and_connect path without going-//! through a real upstream registry — the test inserts an-//! `InstalledServer` row directly to stand in for what-//! `install_and_connect` would have synthesised from-//! `registry::registry_get`. The transport itself is the same-//! `test-mcp-stub` binary used by `mcp_registry_e2e.rs`.--// Exercises the gated `mcp_registry::setup` + `mcp_client` surface, so the-// whole suite is compiled only when the `mcp` feature is on — otherwise the-// slim build's `cargo test --no-default-features --tests` fails to compile against the removed APIs-// (#4799).-#![cfg(feature = "mcp")]--use std::collections::HashMap;-use std::time::Duration;--use openhuman_core::config::Config;-use tinymcp::{SecretRef, SecretVault};--/// A vault for one test.-///-/// Owned rather than process-wide: the machinery moved to `tinymcp`, where a-/// library installing a global would make two hosts share one map and make its-/// own tests order-dependent.-fn vault() -> SecretVault {- SecretVault::new()-}--#[tokio::test]-async fn request_secret_blocks_until_submit_then_resolves() {- // Shared because the two halves run in different tasks — which is the- // shape the real flow has: the model waits while a user interface answers.- let v = std::sync::Arc::new(vault());- // Caller mints + awaits in one task, fulfiller submits in another.- // The exact API the setup_ops::request_secret handler uses.- let (r, rx) = v.request("API_KEY").await;-- let r_for_submit = r.clone();- let v_for_submit = std::sync::Arc::clone(&v);- let submit_task = tokio::spawn(async move {- tokio::time::sleep(Duration::from_millis(20)).await;- let submitted = v_for_submit- .submit(&r_for_submit, "shh-secret".to_string())- .await;- assert!(submitted, "submit returns true the first time");- });-- // The await side: must not return before fulfill is called.- v.await_fulfillment(&r, rx)- .await- .expect("await_fulfillment completes once submit lands");- submit_task.await.unwrap();-- // Resolve maps {KEY: ref} -> {KEY: value} without exposing value to- // anywhere it shouldn't be.- let mut refs = HashMap::new();- refs.insert("API_KEY".to_string(), r.clone());- let resolved = v.resolve(&refs).await.expect("resolves");- assert_eq!(- resolved,- vec![("API_KEY".to_string(), "shh-secret".to_string())]- );-- // The setup-agent contract: once install_and_connect persists the- // values, the refs are gone.- let _ = v.consume(&refs).await.expect("consumes");- assert!(- v.resolve(&refs).await.is_err(),- "post-consume resolve fails"- );-}--#[tokio::test]-async fn test_connection_against_stub_returns_tools() {- let v = vault();- use openhuman_core::mcp::config_servers::McpStdioClient;-- // Mirror what setup_ops::test_connection does end-to-end, minus the- // registry::registry_get step (we don't want to hit a real upstream- // from CI). The point of this test is the spawn + initialize +- // list_tools + teardown lifecycle the setup agent relies on.- let (r, _rx) = v.request("ECHO_TOKEN").await;- assert!(v.submit(&r, "ignored-by-stub".to_string()).await);-- let mut refs = HashMap::new();- refs.insert("ECHO_TOKEN".to_string(), r);- let env = v.resolve(&refs).await.expect("resolves");- assert_eq!(env.len(), 1);-- let stub_path = env!("CARGO_BIN_EXE_test-mcp-stub");- // Through the host conversion, so the test builds the identity the same way- // the application does rather than reaching past it.- let cfg = Config::default();- let identity = openhuman_core::mcp::host::client_config(&cfg).client_identity;- let client = McpStdioClient::new(stub_path.to_string(), Vec::new(), env, None, &identity);-- client.initialize().await.expect("stub initialises");- let tools = client.list_tools().await.expect("stub lists tools");- assert_eq!(tools.len(), 1);- assert_eq!(tools[0].name, "echo");-- client.close_session().await.expect("stub closes");-}--#[tokio::test]-async fn invalid_ref_id_rejected_by_submit_secret() {- // The submit_secret handler parses the ref id via SecretRef::parse.- // Validate the parser independently here so an upstream regression- // doesn't silently re-admit unsafe inputs.- assert!(SecretRef::parse("secret://abc123").is_some());- assert!(SecretRef::parse("abc123").is_some());- assert!(SecretRef::parse("secret://not-hex!!").is_none());- assert!(SecretRef::parse("").is_none());- assert!(SecretRef::parse("../../etc/passwd").is_none());-}diff --git a/tests/raw_coverage/mcp_setup_clients_e2e.rs b/tests/raw_coverage/mcp_setup_clients_e2e.rsdeleted file mode 100644index 10eab7654d..0000000000--- a/tests/raw_coverage/mcp_setup_clients_e2e.rs+++ /dev/null@@ -1,1142 +0,0 @@-//! JSON-RPC E2E coverage for the MCP guided-setup surface (`mcp_setup_*`), the-//! four uncovered `mcp_clients_*` controllers, and `mcp_audit_list`.-//!-//! Run:-//! `cargo test --test raw_coverage_all --features "$(bash scripts/ci/product-features.sh)" mcp_setup_clients_e2e`-//!-//! ## The registry is a loopback fixture, not the live catalog-//!-//! `mcp_setup_search` / `mcp_setup_get` / `mcp_clients_registry_get` read the-//! official `modelcontextprotocol/registry` — `GET /v0/servers` to list, `GET-//! /v0/servers/{name}/versions` for detail-//! (`vendor/tinymcp/.../registry/sources/official/mod.rs:1-6`). Its base is-//! overridable via `MCP_OFFICIAL_REGISTRY_BASE` (`:353-360`), so this suite-//! stands up an axum server speaking that shape and points the resolver at it.-//! Nothing leaves the machine.-//!-//! Smithery, the second source, stays off: it is opt-in on an API key and this-//! suite configures none, so search resolves the official source alone and the-//! result set is exactly the fixture's (`sources/mod.rs:9-19`).-//!-//! ## The secret vault is driven through both of its RPCs at once-//!-//! `mcp_setup_request_secret` **blocks** until a UI answers — up to five-//! minutes — and only then returns the ref. The ref reaches the UI over the-//! event bus as `McpSetupSecretRequested`, so the pair can only be exercised-//! together: this suite initialises the in-process bus, subscribes, issues-//! `request_secret` on one task, reads the ref off the bus, and fulfils it with-//! `mcp_setup_submit_secret` from another. That is the real shape of the flow,-//! not a simulation of it.--use std::net::SocketAddr;-use std::path::Path;-use std::sync::{Arc, Mutex, OnceLock};-use std::time::Duration;--use axum::extract::Path as AxumPath;-use axum::http::header::AUTHORIZATION;-use axum::routing::get;-use axum::{Json, Router};-use serde_json::{json, Value};-use tempfile::{tempdir, TempDir};--use openhuman_core::core::auth::{init_rpc_token, CORE_TOKEN_ENV_VAR};-use openhuman_core::core::events::DomainEvent;-use openhuman_core::core::jsonrpc::build_core_http_router;--/// The bearer this suite *proposes*. It is only used if this suite happens to-/// be the first in the aggregated binary to initialise the token subsystem —-/// see `rpc_token()` below, which is what actually gets sent.-const PROPOSED_RPC_TOKEN: &str = "mcp-setup-clients-e2e-token";--static AUTH_INIT: OnceLock<()> = OnceLock::new();--/// The crate-wide env lock, not a private one.-static ENV_LOCK: &OnceLock<Mutex<()>> = &crate::SHARED_ENV_LOCK;--fn env_lock() -> std::sync::MutexGuard<'static, ()> {- ENV_LOCK- .get_or_init(|| Mutex::new(()))- .lock()- .unwrap_or_else(|poisoned| poisoned.into_inner())-}--// ── Env plumbing ────────────────────────────────────────────────────────────--struct EnvVarGuard {- key: &'static str,- old: Option<String>,-}--impl EnvVarGuard {- fn set_to_path(key: &'static str, path: &Path) -> Self {- let old = std::env::var(key).ok();- std::env::set_var(key, path.as_os_str());- Self { key, old }- }-- fn set(key: &'static str, value: &str) -> Self {- let old = std::env::var(key).ok();- std::env::set_var(key, value);- Self { key, old }- }-- fn unset(key: &'static str) -> Self {- let old = std::env::var(key).ok();- std::env::remove_var(key);- Self { key, old }- }-}--impl Drop for EnvVarGuard {- fn drop(&mut self) {- match &self.old {- Some(value) => std::env::set_var(self.key, value),- None => std::env::remove_var(self.key),- }- }-}--/// The bearer the running process will actually validate.-///-/// `core::auth::RPC_TOKEN` is a process-global `OnceLock` and `init_rpc_token`-/// returns early once it is set. Every `tests/raw_coverage/` suite now shares-/// one process, so the FIRST suite to initialise pins the token for all of-/// them; a suite that sent its own hard-coded literal would get 401 whenever it-/// lost that race, in an order that depends on libtest scheduling and load.-///-/// So: propose a token, initialise, then ask what the process settled on and-/// send that. Correct whether this suite wins the race or loses it.-fn rpc_token() -> &'static str {- AUTH_INIT.get_or_init(|| {- if std::env::var(CORE_TOKEN_ENV_VAR)- .map(|v| v.trim().is_empty())- .unwrap_or(true)- {- std::env::set_var(CORE_TOKEN_ENV_VAR, PROPOSED_RPC_TOKEN);- }- let token_dir = std::env::temp_dir().join("openhuman-mcp-setup-clients-e2e-auth");- std::fs::create_dir_all(&token_dir).expect("token dir");- init_rpc_token(&token_dir).expect("init rpc auth token");- });- openhuman_core::core::auth::get_rpc_token()- .expect("the token subsystem is initialised by the line above")-}--// ── Harness ─────────────────────────────────────────────────────────────────--const MIN_CONFIG: &str = r#"api_url = "http://127.0.0.1:9"-default_model = "mcp-e2e-model"--[secrets]-encrypt = false--[local_ai]-enabled = false--[memory]-provider = "none"-embedding_provider = "none"-embedding_model = "none"-embedding_dimensions = 0--[memory_tree]-embedding_strict = false-"#;--struct Harness {- _tmp: TempDir,- _guards: Vec<EnvVarGuard>,- workspace: std::path::PathBuf,- rpc_base: String,- join: tokio::task::JoinHandle<Result<(), std::io::Error>>,-}--async fn setup(extra: Vec<EnvVarGuard>) -> Harness {- let _ = rpc_token();-- let tmp = tempdir().expect("tempdir");- let home = tmp.path();- let openhuman_home = home.join(".openhuman");- std::fs::create_dir_all(&openhuman_home).expect("create .openhuman");- std::fs::write(openhuman_home.join("config.toml"), MIN_CONFIG).expect("write config.toml");- let _: openhuman_core::config::Config =- toml::from_str(MIN_CONFIG).expect("test config must match the config schema");-- let workspace = home.join("workspace");- std::fs::create_dir_all(&workspace).expect("create workspace");-- let mut guards = vec![- EnvVarGuard::set_to_path("HOME", home),- EnvVarGuard::set_to_path("OPENHUMAN_WORKSPACE", &workspace),- EnvVarGuard::unset("BACKEND_URL"),- EnvVarGuard::unset("VITE_BACKEND_URL"),- EnvVarGuard::unset("OPENHUMAN_API_URL"),- // No Smithery key: the second registry source stays off, so the fixture- // below is the only catalog in play.- EnvVarGuard::unset("SMITHERY_API_KEY"),- EnvVarGuard::unset("MCP_OFFICIAL_REGISTRY_TOKEN"),- EnvVarGuard::set("OPENHUMAN_KEYRING_BACKEND", "file"),- ];- guards.extend(extra);-- let listener = tokio::net::TcpListener::bind("127.0.0.1:0")- .await- .expect("bind rpc listener");- let addr: SocketAddr = listener.local_addr().expect("rpc listener addr");- let router = build_core_http_router(false);- let join = tokio::spawn(async move { axum::serve(listener, router).await });-- Harness {- _tmp: tmp,- _guards: guards,- workspace,- rpc_base: format!("http://{addr}"),- join,- }-}--async fn rpc(base: &str, id: i64, method: &str, params: Value) -> Value {- let client = reqwest::Client::builder()- .timeout(Duration::from_secs(120))- .build()- .expect("build client");- let url = format!("{}/rpc", base.trim_end_matches('/'));- let response = client- .post(&url)- .header(AUTHORIZATION, format!("Bearer {}", rpc_token()))- .json(&json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params }))- .send()- .await- .unwrap_or_else(|err| panic!("POST {url} {method}: {err}"));- assert!(- response.status().is_success(),- "HTTP {} for {method}",- response.status()- );- response- .json::<Value>()- .await- .unwrap_or_else(|err| panic!("json for {method}: {err}"))-}--fn ok<'a>(value: &'a Value, context: &str) -> &'a Value {- if let Some(error) = value.get("error") {- panic!("{context}: unexpected JSON-RPC error: {error}");- }- value- .get("result")- .unwrap_or_else(|| panic!("{context}: missing result: {value}"))-}--fn error_message<'a>(value: &'a Value, context: &str) -> &'a str {- value- .get("error")- .unwrap_or_else(|| panic!("{context}: expected a JSON-RPC error, got: {value}"))- .get("message")- .and_then(Value::as_str)- .unwrap_or_else(|| panic!("{context}: error carries no message: {value}"))-}--// ── The fixture registry ────────────────────────────────────────────────────--/// The two names the fixture catalog serves.-const INSTALLABLE: &str = "io.github.e2e/planted-server";-/// Declares neither a remote nor a package, so `is_installable()` is false and-/// the list adapter must drop it.-const UNINSTALLABLE: &str = "io.github.e2e/shell-only-row";--fn fixture_server_record(name: &str, installable: bool) -> Value {- let mut record = json!({- "name": name,- "title": "Planted E2E Server",- "description": "A planted MCP server record for the e2e suite.",- "websiteUrl": "https://example.invalid/planted",- "remotes": [],- "packages": []- });- if installable {- record["packages"] = json!([{- "registryType": "npm",- "identifier": "@e2e/planted-server",- "environmentVariables": [- {- "name": "PLANTED_API_KEY",- "description": "The credential the planted server needs.",- "isRequired": true,- "isSecret": true- }- ]- }]);- }- record-}--/// An axum server speaking the official registry's list + versions shapes.-async fn serve_fixture_registry() -> (- SocketAddr,- tokio::task::JoinHandle<Result<(), std::io::Error>>,-) {- async fn list() -> Json<Value> {- Json(json!({- "servers": [- { "server": fixture_server_record(INSTALLABLE, true) },- { "server": fixture_server_record(UNINSTALLABLE, false) }- ],- // Empty next cursor: the adapter treats it as absent, so the page- // bound stays at the current page rather than paging forever.- "metadata": { "nextCursor": "" }- }))- }-- async fn versions(AxumPath(name): AxumPath<String>) -> Json<Value> {- if name == INSTALLABLE {- Json(json!({- "servers": [{ "server": fixture_server_record(INSTALLABLE, true) }]- }))- } else {- // The registry lists no version of it — the adapter's- // `Error::UnknownServer` path.- Json(json!({ "servers": [] }))- }- }-- let app = Router::new()- .route("/v0/servers", get(list))- .route("/v0/servers/{name}/versions", get(versions));-- let listener = tokio::net::TcpListener::bind("127.0.0.1:0")- .await- .expect("bind fixture registry");- let addr = listener.local_addr().expect("fixture registry addr");- let join = tokio::spawn(async move { axum::serve(listener, app).await });- (addr, join)-}--// ── mcp_setup: the catalog half ─────────────────────────────────────────────--/// `mcp_setup_search` and `mcp_setup_get` against the fixture registry.-#[tokio::test]-async fn mcp_setup_search_and_get_read_the_configured_registry() {- let _lock = env_lock();- let (registry_addr, registry_join) = serve_fixture_registry().await;- let harness = setup(vec![EnvVarGuard::set(- "MCP_OFFICIAL_REGISTRY_BASE",- &format!("http://{registry_addr}"),- )])- .await;-- let found = rpc(- &harness.rpc_base,- 200,- "openhuman.mcp_setup_search",- json!({ "query": "planted", "page": 1, "page_size": 10 }),- )- .await;- let found = ok(&found, "mcp_setup_search");- let servers = found- .get("servers")- .and_then(Value::as_array)- .unwrap_or_else(|| panic!("search has no `servers` array: {found}"));-- // Exactly one row: the un-installable record must be filtered out rather- // than shown as a dead end the user can only discover by trying.- assert_eq!(- servers.len(),- 1,- "the row declaring neither a remote nor a package must be dropped: {found}"- );- let row = &servers[0];- assert_eq!(- row.get("qualified_name").and_then(Value::as_str),- Some(INSTALLABLE),- "the surviving row must be the installable one: {row}"- );- assert_eq!(- row.get("source").and_then(Value::as_str),- Some("mcp_official"),- "every row must be tagged with the registry it came from: {row}"- );- assert_eq!(- row.get("display_name").and_then(Value::as_str),- Some("Planted E2E Server"),- "the declared title must win over the derived one: {row}"- );- assert_eq!(- row.get("auth_kind").and_then(Value::as_str),- Some("api_key"),- "a package declaring an `isSecret` env var must be badged as needing a key: {row}"- );- assert_eq!(- found.get("page").and_then(Value::as_u64),- Some(1),- "the requested page must be echoed: {found}"- );- assert_eq!(- found.get("total_pages").and_then(Value::as_u64),- Some(1),- "an empty nextCursor means this is the last page: {found}"- );-- // `get` adds `required_env_keys`, which is the whole reason the setup- // dialog calls it rather than reading the search row.- let detail = rpc(- &harness.rpc_base,- 201,- "openhuman.mcp_setup_get",- json!({ "qualified_name": INSTALLABLE }),- )- .await;- let detail = ok(&detail, "mcp_setup_get");- let server = detail- .get("server")- .unwrap_or_else(|| panic!("get has no `server`: {detail}"));- assert_eq!(- server.get("qualified_name").and_then(Value::as_str),- Some(INSTALLABLE)- );- assert_eq!(- server- .get("required_env_keys")- .and_then(Value::as_array)- .map(|keys| keys.iter().filter_map(Value::as_str).collect::<Vec<_>>()),- Some(vec!["PLANTED_API_KEY"]),- "the declared secret env var must be injected as a required key: {server}"- );- // The package became a stdio connection with a worked example.- let connections = server- .get("connections")- .and_then(Value::as_array)- .unwrap_or_else(|| panic!("detail has no `connections`: {server}"));- assert_eq!(- connections.len(),- 1,- "one package, one connection: {server}"- );- assert_eq!(- connections[0].get("type").and_then(Value::as_str),- Some("stdio"),- "an npm package must become a stdio connection: {server}"- );-- // Failure path 1: a blank name is refused by the shared identifier guard,- // before any network call.- let blank = rpc(- &harness.rpc_base,- 202,- "openhuman.mcp_setup_get",- json!({ "qualified_name": " " }),- )- .await;- assert!(- error_message(&blank, "mcp_setup_get blank").contains("qualified_name must not be empty"),- "a blank qualified_name must be named in the refusal: {blank}"- );-- // Failure path 2: the param is absent entirely — a different error from a- // blank one, and it must stay different.- let absent = rpc(&harness.rpc_base, 203, "openhuman.mcp_setup_get", json!({})).await;- assert!(- error_message(&absent, "mcp_setup_get absent").contains("missing required param"),- "an absent qualified_name must be a missing-param error: {absent}"- );-- // Failure path 3: a name the registry lists no version of.- let unknown = rpc(- &harness.rpc_base,- 204,- "openhuman.mcp_setup_get",- json!({ "qualified_name": UNINSTALLABLE }),- )- .await;- assert!(- unknown.get("error").is_some(),- "a name with no published version must error, not return an empty detail: {unknown}"- );-- registry_join.abort();- harness.join.abort();-}--// ── mcp_setup: the secret half ──────────────────────────────────────────────--/// `mcp_setup_request_secret` + `mcp_setup_submit_secret`, driven as the pair-/// they actually are.-///-/// `request_secret` blocks on the vault until a UI answers, publishing the ref-/// on the event bus on the way in. This case plays both halves: one task issues-/// the request, and the ref that comes back over the bus is what the other task-/// submits. Asserting only one half would assert nothing — the request never-/// returns without the submit, and the submit has no ref without the request.-#[tokio::test]-async fn mcp_setup_secret_request_blocks_until_the_matching_submit_lands() {- let _lock = env_lock();- let harness = setup(Vec::new()).await;- openhuman_core::core::bus::init().await.expect("bus init");-- // Capture the ref the flow publishes for the UI.- struct RefCatcher {- tx: tokio::sync::mpsc::UnboundedSender<(String, String, String)>,- }-- #[async_trait::async_trait]- impl tinybus::EventHandler<DomainEvent> for RefCatcher {- fn name(&self) -> &str {- "mcp-setup-e2e::ref-catcher"- }-- async fn handle(&self, event: &DomainEvent) {- if let DomainEvent::McpSetupSecretRequested {- ref_id,- key_name,- prompt,- } = event- {- let _ = self- .tx- .send((ref_id.clone(), key_name.clone(), prompt.clone()));- }- }- }-- let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();- let _subscription = openhuman_core::core::bus::BUS- .subscribe(Arc::new(RefCatcher { tx }))- .expect("the in-process bus accepts a subscriber once init() has run");-- let base = harness.rpc_base.clone();- let request = tokio::spawn(async move {- rpc(- &base,- 210,- "openhuman.mcp_setup_request_secret",- json!({ "key_name": "PLANTED_API_KEY", "prompt": "Paste the planted key." }),- )- .await- });-- let (ref_id, key_name, prompt) = tokio::time::timeout(Duration::from_secs(30), rx.recv())- .await- .expect("the request must publish its ref promptly")- .expect("the ref-catcher channel stays open");- assert_eq!(- key_name, "PLANTED_API_KEY",- "the published event must carry the requested key name"- );- assert_eq!(- prompt, "Paste the planted key.",- "the published event must carry the prompt the UI renders"- );- assert!(- ref_id.starts_with("secret://"),- "the minted handle must be an opaque `secret://` ref, got {ref_id}"- );-- // The request is still blocked: nothing has answered it yet. Proving that- // is the point — a `request_secret` that returned early would hand the- // agent a ref with no value behind it.- assert!(- !request.is_finished(),- "request_secret must not return before a value is submitted"- );-- let submitted = rpc(- &harness.rpc_base,- 211,- "openhuman.mcp_setup_submit_secret",- json!({ "ref_id": ref_id, "value": "planted-secret-value" }),- )- .await;- let submitted = ok(&submitted, "mcp_setup_submit_secret");- assert_eq!(- submitted.get("ref").and_then(Value::as_str),- Some(ref_id.as_str()),- "submit must echo the ref it fulfilled: {submitted}"- );- assert_eq!(- submitted.get("fulfilled").and_then(Value::as_bool),- Some(true),- "a first submit must report fulfilled: {submitted}"- );-- // Now the blocked request completes, returning the ref — and never the- // value, which is the security property the whole indirection exists for.- let requested = tokio::time::timeout(Duration::from_secs(30), request)- .await- .expect("request_secret must return once the submit lands")- .expect("request task must not panic");- let requested = ok(&requested, "mcp_setup_request_secret");- assert_eq!(- requested.get("ref").and_then(Value::as_str),- Some(ref_id.as_str()),- "request_secret returns the same ref it published: {requested}"- );- assert_eq!(- requested.get("key_name").and_then(Value::as_str),- Some("PLANTED_API_KEY")- );- assert!(- !requested.to_string().contains("planted-secret-value"),- "the raw secret must NEVER cross the model-facing surface: {requested}"- );-- // A second submit against the same ref is refused — the ref is single-use.- let replay = rpc(- &harness.rpc_base,- 212,- "openhuman.mcp_setup_submit_secret",- json!({ "ref_id": ref_id, "value": "a-different-value" }),- )- .await;- let message = error_message(&replay, "mcp_setup_submit_secret replay");- assert!(- message.contains("unknown or already submitted"),- "replaying a ref must be refused, got: {message}"- );-- // A syntactically invalid ref never reaches the vault.- let malformed = rpc(- &harness.rpc_base,- 213,- "openhuman.mcp_setup_submit_secret",- json!({ "ref_id": "../../etc/passwd", "value": "nope" }),- )- .await;- assert!(- error_message(&malformed, "mcp_setup_submit_secret malformed").contains("invalid ref_id"),- "a malformed ref must be refused by the parser: {malformed}"- );-- // And the request half validates its own inputs before touching the vault.- let blank_key = rpc(- &harness.rpc_base,- 214,- "openhuman.mcp_setup_request_secret",- json!({ "key_name": " ", "prompt": "anything" }),- )- .await;- assert!(- error_message(&blank_key, "request_secret blank key")- .contains("key_name must not be empty"),- "a blank key_name must be refused without blocking for five minutes: {blank_key}"- );-- harness.join.abort();-}--// ── mcp_setup: the install half ─────────────────────────────────────────────--/// `mcp_setup_test_connection` and `mcp_setup_install_and_connect`.-///-/// Both take `{ENV_KEY: secret://…}` handles, and both parse those handles-/// before doing anything else — which is the boundary this case asserts, since-/// spawning a real candidate server would need a registry-resolvable package-/// and a subprocess.-///-/// `test_connection` is additionally documented to report a failed dial as-/// `ok: false` **with the reason**, rather than raising — that contract is what-/// lets the setup agent retry instead of aborting, and it is asserted here-/// against a name the fixture registry does not publish.-#[tokio::test]-async fn mcp_setup_install_paths_validate_handles_and_report_dial_failure_in_band() {- let _lock = env_lock();- let (registry_addr, registry_join) = serve_fixture_registry().await;- let harness = setup(vec![EnvVarGuard::set(- "MCP_OFFICIAL_REGISTRY_BASE",- &format!("http://{registry_addr}"),- )])- .await;-- // A handle that is not a `secret://<hex>` ref is rejected by the parser,- // for both methods, before any dial.- for (id, method) in [- (220, "openhuman.mcp_setup_test_connection"),- (221, "openhuman.mcp_setup_install_and_connect"),- ] {- let bad_handle = rpc(- &harness.rpc_base,- id,- method,- json!({- "qualified_name": INSTALLABLE,- "env_refs": { "PLANTED_API_KEY": "not-a-ref!!" }- }),- )- .await;- assert!(- error_message(&bad_handle, method).contains("invalid ref_id"),- "{method} must refuse a malformed handle: {bad_handle}"- );- }-- // A blank qualified_name is refused ahead of the handles.- let blank = rpc(- &harness.rpc_base,- 222,- "openhuman.mcp_setup_test_connection",- json!({ "qualified_name": "", "env_refs": {} }),- )- .await;- assert!(- error_message(&blank, "test_connection blank name")- .contains("qualified_name must not be empty"),- "a blank name must be refused: {blank}"- );-- // `env_refs` is required, not defaulted — omitting it must not silently- // dial with no credentials.- let no_refs = rpc(- &harness.rpc_base,- 223,- "openhuman.mcp_setup_install_and_connect",- json!({ "qualified_name": INSTALLABLE }),- )- .await;- assert!(- error_message(&no_refs, "install_and_connect no env_refs").contains("env_refs"),- "an absent env_refs must be named in the refusal: {no_refs}"- );-- // The in-band failure contract: a dial that cannot happen is reported as- // `ok: false` with a reason, NOT as a JSON-RPC error.- let dial = rpc(- &harness.rpc_base,- 224,- "openhuman.mcp_setup_test_connection",- json!({ "qualified_name": UNINSTALLABLE, "env_refs": {} }),- )- .await;- let dial = ok(- &dial,- "mcp_setup_test_connection must not raise on a failed dial",- );- assert_eq!(- dial.get("ok").and_then(Value::as_bool),- Some(false),- "a dial that could not succeed must report ok:false: {dial}"- );- assert!(- dial.get("error")- .and_then(Value::as_str)- .is_some_and(|e| !e.trim().is_empty()),- "ok:false must carry a non-empty reason the agent can act on: {dial}"- );- assert!(- dial.get("tools").is_none_or(Value::is_null),- "`tools` must be absent when the dial failed: {dial}"- );-- // `install_and_connect` still raises here, and after #6110 that is the- // *correct* answer rather than the drift this case originally pinned.- //- // `UNINSTALLABLE` declares neither a remote nor a package and the fixture- // registry serves no version of it, so the **install** step is what fails.- // There is no server and no `server_id`, so there is nothing to report a- // `status` for — the schema's `installed_disconnected` means "install- // succeeded, connect failed", which is a different case and not reachable- // from this input.- //- // The reconciliation the old note asked for has happened: a failed- // *connect* now returns `Ok` with `status: "installed_disconnected"` and an- // `error`, matching `test_connection`'s in-band contract. Exercising that- // arm needs a package that installs and then refuses to dial, which means a- // registry-resolvable package and a subprocess; it is covered by the unit- // tests on `classify_install_connect` in- // `crates/openhuman-core/src/mcp/registry/setup_ops_tests.rs`.- let install = rpc(- &harness.rpc_base,- 225,- "openhuman.mcp_setup_install_and_connect",- json!({ "qualified_name": UNINSTALLABLE, "env_refs": {} }),- )- .await;- assert!(- install.get("error").is_some(),- "an install that cannot resolve a package must still raise — it has no \- server_id to attach a status to: {install}"- );-- registry_join.abort();- harness.join.abort();-}--// ── mcp_clients ─────────────────────────────────────────────────────────────--/// The four uncovered `mcp_clients_*` controllers.-///-/// `registry_get` reads the fixture catalog; `detect_auth` and `oauth_begin`-/// address an *installed* server by UUID, so with nothing installed the-/// interesting assertion is that they refuse a name they cannot resolve rather-/// than dialling something arbitrary. `config_assist` needs both the catalog-/// and an inference turn, so it is asserted at its catalog boundary.-#[tokio::test]-async fn mcp_clients_registry_get_and_the_per_server_controllers() {- let _lock = env_lock();- let (registry_addr, registry_join) = serve_fixture_registry().await;- let harness = setup(vec![EnvVarGuard::set(- "MCP_OFFICIAL_REGISTRY_BASE",- &format!("http://{registry_addr}"),- )])- .await;-- // `mcp_clients_registry_get` — the install dialog's one round trip, which- // must carry the credential names alongside the detail.- let detail = rpc(- &harness.rpc_base,- 230,- "openhuman.mcp_clients_registry_get",- json!({ "qualified_name": INSTALLABLE }),- )- .await;- let detail = ok(&detail, "mcp_clients_registry_get");- let server = detail- .get("server")- .unwrap_or_else(|| panic!("no `server` in registry_get: {detail}"));- assert_eq!(- server.get("qualified_name").and_then(Value::as_str),- Some(INSTALLABLE)- );- assert_eq!(- server- .get("required_env_keys")- .and_then(Value::as_array)- .map(|k| k.iter().filter_map(Value::as_str).collect::<Vec<_>>()),- Some(vec!["PLANTED_API_KEY"]),- "registry_get must inject the credential names, not make the dialog \- fetch them separately: {server}"- );- assert_eq!(- server.get("source").and_then(Value::as_str),- Some("mcp_official"),- "the detail must name the registry it came from so an install can route \- its lookup back: {server}"- );-- let blank = rpc(- &harness.rpc_base,- 231,- "openhuman.mcp_clients_registry_get",- json!({ "qualified_name": " " }),- )- .await;- assert!(- error_message(&blank, "registry_get blank").contains("qualified_name must not be empty"),- "a blank name must be refused: {blank}"- );-- // `detect_auth` / `oauth_begin` address an installed server by id. Nothing- // is installed, so both must refuse — and refuse *by name*, so an operator- // can tell "no such server" from "the probe failed".- for (id, method) in [- (232, "openhuman.mcp_clients_detect_auth"),- (233, "openhuman.mcp_clients_oauth_begin"),- ] {- let blank_id = rpc(&harness.rpc_base, id, method, json!({ "server_id": " " })).await;- assert!(- error_message(&blank_id, method).contains("server_id must not be empty"),- "{method} must refuse a blank server_id: {blank_id}"- );-- let unknown = rpc(- &harness.rpc_base,- id + 100,- method,- json!({ "server_id": "00000000-0000-4000-8000-000000000000" }),- )- .await;- assert!(- unknown.get("error").is_some(),- "{method} against an uninstalled server id must error rather than \- probing something arbitrary: {unknown}"- );- // A UUID that resolves to nothing must not come back as a usable- // authorize URL — that would be an open redirect waiting to happen.- assert!(- unknown.get("result").is_none(),- "{method} must not return a result for an unknown server: {unknown}"- );- }-- // `config_assist` validates its identifier, then needs the catalog detail- // before it can build a prompt. A name the registry cannot resolve fails at- // that fetch, with the message saying so.- let assist_blank = rpc(- &harness.rpc_base,- 240,- "openhuman.mcp_clients_config_assist",- json!({ "qualified_name": "", "user_message": "how do I set this up?" }),- )- .await;- assert!(- error_message(&assist_blank, "config_assist blank")- .contains("qualified_name must not be empty"),- "config_assist must refuse a blank name: {assist_blank}"- );-- let assist_unknown = rpc(- &harness.rpc_base,- 241,- "openhuman.mcp_clients_config_assist",- json!({ "qualified_name": UNINSTALLABLE, "user_message": "how do I set this up?" }),- )- .await;- let message = error_message(&assist_unknown, "config_assist unknown server");- assert!(- message.contains("Failed to fetch registry detail"),- "config_assist must say the catalog lookup is what failed, not surface a \- bare transport error, got: {message}"- );-- // `user_message` is required — a caller that forgets it must be told, not- // handed an assistant turn on an empty question.- let assist_no_message = rpc(- &harness.rpc_base,- 242,- "openhuman.mcp_clients_config_assist",- json!({ "qualified_name": INSTALLABLE }),- )- .await;- assert!(- error_message(&assist_no_message, "config_assist no message").contains("user_message"),- "an absent user_message must be named: {assist_no_message}"- );-- registry_join.abort();- harness.join.abort();-}--// ── mcp_audit ───────────────────────────────────────────────────────────────--/// `mcp_audit_list` — the write-audit log's only reader, exercised over rows-/// this case records through the audit API so the content is knowable.-#[tokio::test]-async fn mcp_audit_list_filters_and_orders_the_write_log() {- let _lock = env_lock();- let harness = setup(Vec::new()).await;-- // Empty first: an audit log with no rows must read as an empty list, not- // as an error — an operator opening the panel on a fresh install sees this.- let empty = rpc(- &harness.rpc_base,- 250,- "openhuman.mcp_audit_list",- json!({}),- )- .await;- assert_eq!(- ok(&empty, "mcp_audit_list empty")- .get("records")- .and_then(Value::as_array)- .map(Vec::len),- Some(0),- "a fresh workspace must list zero records: {empty}"- );-- // Seed three rows: two clients, two tools, one failure.- let config = openhuman_core::config::Config {- workspace_dir: harness.workspace.clone(),- ..openhuman_core::config::Config::default()- };- use openhuman_core::mcp::audit::{record_write, NewMcpWriteRecord};- for (ts, client, tool, success, error) in [- (1_000_i64, "mcp:claude-desktop", "memory.store", true, None),- (- 2_000,- "mcp:claude-desktop",- "memory.delete",- false,- Some("denied by policy"),- ),- (3_000, "mcp:some-other-client", "memory.store", true, None),- ] {- record_write(- &config,- NewMcpWriteRecord {- timestamp_ms: ts,- client_info: client.to_string(),- tool_name: tool.to_string(),- args_summary: json!({ "keys": ["a", "b"] }),- resulting_chunk_id: None,- success,- error_message: error.map(str::to_string),- },- )- .expect("record an audit row");- }-- let all = rpc(- &harness.rpc_base,- 251,- "openhuman.mcp_audit_list",- json!({}),- )- .await;- let all = ok(&all, "mcp_audit_list all");- let records = all- .get("records")- .and_then(Value::as_array)- .unwrap_or_else(|| panic!("no `records` array: {all}"));- assert_eq!(records.len(), 3, "all three rows must come back: {all}");- assert_eq!(- records- .iter()- .filter_map(|r| r.get("timestamp_ms").and_then(Value::as_i64))- .collect::<Vec<_>>(),- vec![3_000, 2_000, 1_000],- "records must be ordered newest-first, as the schema documents: {all}"- );- // The failed attempt is retained, with its reason — an audit log that kept- // only successes would be useless for the thing it exists for.- let failed = records- .iter()- .find(|r| r.get("success").and_then(Value::as_bool) == Some(false))- .unwrap_or_else(|| panic!("the rejected write must be retained: {all}"));- assert_eq!(- failed.get("error_message").and_then(Value::as_str),- Some("denied by policy"),- "a failed write must keep its reason: {failed}"- );- assert_eq!(- failed.get("tool_name").and_then(Value::as_str),- Some("memory.delete")- );-- // Each filter narrows, and they are exact matches rather than substrings.- let by_client = rpc(- &harness.rpc_base,- 252,- "openhuman.mcp_audit_list",- json!({ "client_filter": "mcp:some-other-client" }),- )- .await;- let by_client = ok(&by_client, "mcp_audit_list client_filter");- let rows = by_client- .get("records")- .and_then(Value::as_array)- .expect("records");- assert_eq!(- rows.len(),- 1,- "the client filter must narrow to one: {by_client}"- );- assert_eq!(- rows[0].get("client_info").and_then(Value::as_str),- Some("mcp:some-other-client")- );-- let by_tool = rpc(- &harness.rpc_base,- 253,- "openhuman.mcp_audit_list",- json!({ "tool_filter": "memory.store" }),- )- .await;- assert_eq!(- ok(&by_tool, "mcp_audit_list tool_filter")- .get("records")- .and_then(Value::as_array)- .map(Vec::len),- Some(2),- "the tool filter must match exactly two: {by_tool}"- );-- // `memory.` is a prefix of both tool names — an exact filter must match- // neither, which is what stops a filter quietly widening.- let prefix = rpc(- &harness.rpc_base,- 254,- "openhuman.mcp_audit_list",- json!({ "tool_filter": "memory." }),- )- .await;- assert_eq!(- ok(&prefix, "mcp_audit_list prefix filter")- .get("records")- .and_then(Value::as_array)- .map(Vec::len),- Some(0),- "the tool filter is exact, not a prefix match: {prefix}"- );-- let successes = rpc(- &harness.rpc_base,- 255,- "openhuman.mcp_audit_list",- json!({ "success_only": true }),- )- .await;- let successes = ok(&successes, "mcp_audit_list success_only");- let rows = successes- .get("records")- .and_then(Value::as_array)- .expect("records");- assert_eq!(- rows.len(),- 2,- "success_only must drop the failure: {successes}"- );- assert!(- rows.iter()- .all(|r| r.get("success").and_then(Value::as_bool) == Some(true)),- "success_only must return only successes: {successes}"- );-- let since = rpc(- &harness.rpc_base,- 256,- "openhuman.mcp_audit_list",- json!({ "since_ms": 2_000 }),- )- .await;- assert_eq!(- ok(&since, "mcp_audit_list since_ms")- .get("records")- .and_then(Value::as_array)- .map(Vec::len),- Some(2),- "since_ms is inclusive of its own boundary: {since}"- );-- // Paging: limit then offset walk the newest-first set without overlap.- let page_one = rpc(- &harness.rpc_base,- 257,- "openhuman.mcp_audit_list",- json!({ "limit": 1 }),- )- .await;- let page_two = rpc(- &harness.rpc_base,- 258,- "openhuman.mcp_audit_list",- json!({ "limit": 1, "offset": 1 }),- )- .await;- let first = ok(&page_one, "audit page one")- .get("records")- .and_then(Value::as_array)- .expect("records")- .clone();- let second = ok(&page_two, "audit page two")- .get("records")- .and_then(Value::as_array)- .expect("records")- .clone();- assert_eq!(first.len(), 1, "limit 1 returns one row: {page_one}");- assert_eq!(- second.len(),- 1,- "limit 1 offset 1 returns one row: {page_two}"- );- assert_eq!(- first[0].get("timestamp_ms").and_then(Value::as_i64),- Some(3_000)- );- assert_eq!(- second[0].get("timestamp_ms").and_then(Value::as_i64),- Some(2_000),- "offset must skip from the newest end, not restart: {page_two}"- );-- harness.join.abort();-}