Skip to content

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

refactor(mcp): consolidate domain startup into a single entry point

Steven Enamakel1437ed72914f
diff --git a/src/core/jsonrpc.rs b/src/core/jsonrpc.rs
index de462eb9db..bd8c4785b1 100644
--- a/src/core/jsonrpc.rs
+++ b/src/core/jsonrpc.rs
@@ -2354,20 +2354,15 @@ fn register_domain_subscribers(
// bootstrap_core_runtime; this subscriber must be live before then so those
// connect events are observed (issue #3039 gap A1).
//
- // The `tinymcp` service is opened here for the same reason: this is where
- // the MCP domain is turned on, and every RPC handler in the domain reaches
- // for the service. Opening it later — from the boot-connect job — would
- // leave a window where a handler answers "still starting" to a caller whose
- // domain is, as far as anything else can tell, already up.
+ // What bringing the domain up means is the domain's own; this only says
+ // when. The service it opens is wanted here rather than later for the same
+ // reason as the subscriber: every RPC handler in the domain reaches for it,
+ // and opening it from the boot-connect job would leave a window where a
+ // handler answers "still starting" to a caller whose domain is, as far as
+ // anything else can tell, already up.
if plan.mcp {
if group_first_time(DomainGroup::Mcp) {
- crate::openhuman::mcp::registry::bus::init();
-
- // Logged, never fatal: MCP being unavailable must not stop the core
- // coming up, and every caller handles an absent service.
- if let Err(error) = crate::openhuman::mcp::host::init(&config) {
- log::warn!("[event_bus] the mcp service could not be opened: {error}");
- }
+ crate::openhuman::mcp::start(&config);
}
} else {
log::debug!("[event_bus] mcp_registry bus init SKIPPED — Mcp domain disabled");
diff --git a/src/core/runtime/services.rs b/src/core/runtime/services.rs
index f7dafc1a45..4dc244da64 100644
--- a/src/core/runtime/services.rs
+++ b/src/core/runtime/services.rs
@@ -353,13 +353,11 @@ pub async fn start_boot_once_jobs(services: ServiceSet, config: &Config) {
}
if services.mcp_boot {
- // Idempotent, and normally a no-op: `register_domain_subscribers` opens
- // the service when it enables the MCP domain. It is repeated here
- // because the two are gated separately — a `ServiceSet` that boots MCP
- // is entitled to a service whether or not the RPC domain was turned on.
- if let Err(error) = crate::openhuman::mcp::host::init(config) {
- log::warn!("[runtime] the mcp service could not be opened: {error}");
- }
+ // Idempotent, and normally a no-op: `register_domain_subscribers` brings
+ // the domain up when it enables it. Repeated here because the two are
+ // gated separately — a `ServiceSet` that boots MCP is entitled to a
+ // service whether or not the RPC domain was turned on.
+ crate::openhuman::mcp::start(config);
let cfg_for_mcp = config.clone();
tokio::spawn(async move {
diff --git a/src/openhuman/mcp/host.rs b/src/openhuman/mcp/host.rs
index 3485720651..4692ec230c 100644
--- a/src/openhuman/mcp/host.rs
+++ b/src/openhuman/mcp/host.rs
@@ -27,7 +27,7 @@
//! here. [`proxy_for_mcp`] consults them and hands over the answer.
use std::collections::HashMap;
-use std::path::PathBuf;
+use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, OnceLock};
use tinymcp::{
@@ -203,7 +203,17 @@ pub fn try_service() -> Option<Arc<McpHost>> {
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
- if let Some(workspace) = DEFAULT_WORKSPACE.get() {
+ resolve(DEFAULT_WORKSPACE.get().map(PathBuf::as_path), &hosts)
+}
+
+/// The rule [`try_service`] applies, as a function of its inputs.
+///
+/// Separated from the process state so it can be tested. The state it reads is
+/// two `OnceLock`s and a process-wide map that every case in this suite shares,
+/// so a test driving `try_service` directly could only assert whatever the rest
+/// of the suite happened to leave behind — which is to say, nothing.
+fn resolve(default: Option<&Path>, hosts: &HashMap<PathBuf, Arc<McpHost>>) -> Option<Arc<McpHost>> {
+ if let Some(workspace) = default {
if let Some(service) = hosts.get(workspace) {
return Some(Arc::clone(service));
}
diff --git a/src/openhuman/mcp/host_tests.rs b/src/openhuman/mcp/host_tests.rs
index 7d01dc6aae..176df06967 100644
--- a/src/openhuman/mcp/host_tests.rs
+++ b/src/openhuman/mcp/host_tests.rs
@@ -285,30 +285,74 @@ fn two_workspaces_get_two_services() {
assert!(tinymcp::Store::path_for(second_dir.path()).exists());
}
+/// A map holding one service per named workspace.
+fn hosts_for(workspaces: &[&std::path::Path]) -> HashMap<PathBuf, Arc<McpHost>> {
+ workspaces
+ .iter()
+ .map(|workspace| {
+ let mut config = config_without_docs();
+ config.workspace_dir = workspace.to_path_buf();
+ (
+ workspace.to_path_buf(),
+ Arc::new(McpHost::open(&config).expect("the service opens")),
+ )
+ })
+ .collect()
+}
+
+#[test]
+fn the_default_workspace_wins_when_one_is_set() {
+ let first = tempfile::tempdir().expect("tempdir");
+ let second = tempfile::tempdir().expect("tempdir");
+ let hosts = hosts_for(&[first.path(), second.path()]);
+ let expected = Arc::clone(&hosts[second.path()]);
+
+ let resolved = super::resolve(Some(second.path()), &hosts).expect("a service");
+
+ assert!(Arc::ptr_eq(&resolved, &expected));
+}
+
#[test]
-fn the_only_open_service_answers_a_caller_with_no_configuration() {
+fn the_only_open_service_answers_when_no_default_is_set() {
// The agent's tool registry asks which MCP tools are live, and it asks by
- // server id alone. A process that opened a service without booting — a
- // test, or a host driving the library directly — would otherwise be told
- // nothing is connected while a connection sits in the map.
- //
- // Shares the process map with the other cases here, so it asserts the
- // resolution rather than a specific workspace: with several open and no
- // default set, there is no honest answer and `None` is correct.
- let temporary = tempfile::tempdir().expect("tempdir");
- let mut config = config_without_docs();
- config.workspace_dir = temporary.path().to_path_buf();
+ // server id alone. A process that opened a service without booting — a test,
+ // or a host driving the library directly — would otherwise be told nothing
+ // is connected while a connection sits in the map.
+ let only = tempfile::tempdir().expect("tempdir");
+ let hosts = hosts_for(&[only.path()]);
+ let expected = Arc::clone(&hosts[only.path()]);
- let opened = super::for_config(&config).expect("the service opens");
+ let resolved = super::resolve(None, &hosts).expect("the sole service");
- match super::try_service() {
- Some(resolved) => assert!(
- std::sync::Arc::ptr_eq(&resolved, &opened) || super::DEFAULT_WORKSPACE.get().is_some(),
- "resolved a service that is neither the only one open nor the default"
- ),
- None => assert!(
- super::DEFAULT_WORKSPACE.get().is_none(),
- "answered None even though a default workspace is set"
- ),
- }
+ assert!(Arc::ptr_eq(&resolved, &expected));
+}
+
+#[test]
+fn several_open_services_and_no_default_has_no_honest_answer() {
+ // Picking one would be picking arbitrarily, and the caller cannot tell it
+ // apart from the one it meant.
+ let first = tempfile::tempdir().expect("tempdir");
+ let second = tempfile::tempdir().expect("tempdir");
+
+ assert!(super::resolve(None, &hosts_for(&[first.path(), second.path()])).is_none());
+}
+
+#[test]
+fn nothing_open_answers_nothing() {
+ assert!(super::resolve(None, &HashMap::new()).is_none());
+}
+
+#[test]
+fn a_default_naming_a_workspace_nothing_opened_falls_through_to_the_rule() {
+ // The default is set from a workspace that was opened, so this should not
+ // happen — but if it ever did, answering the sole open service is better
+ // than answering nothing.
+ let only = tempfile::tempdir().expect("tempdir");
+ let absent = tempfile::tempdir().expect("tempdir");
+ let hosts = hosts_for(&[only.path()]);
+ let expected = Arc::clone(&hosts[only.path()]);
+
+ let resolved = super::resolve(Some(absent.path()), &hosts).expect("the sole service");
+
+ assert!(Arc::ptr_eq(&resolved, &expected));
}
diff --git a/src/openhuman/mcp/mod.rs b/src/openhuman/mcp/mod.rs
index d2095c927a..ea3db47f17 100644
--- a/src/openhuman/mcp/mod.rs
+++ b/src/openhuman/mcp/mod.rs
@@ -45,6 +45,32 @@
//! and `audit` keep their own gate and their `stub`, so a build without the
//! feature still serves `/rpc` without those namespaces.
+/// Brings this domain up: its lifecycle subscriber and its service.
+///
+/// The one entry point core startup calls. It exists so that `src/core/` — which
+/// is transport, and carries no business logic — does not have to know that this
+/// domain has a service, that opening one can fail, or what to do when it does.
+///
+/// Never fails. MCP being unavailable must not stop the core coming up, and
+/// every caller in the domain already handles an absent service, so a failure is
+/// logged here and the process continues without it.
+///
+/// Idempotent: the subscriber registers once and the service opens once, so the
+/// two startup paths that call this — the RPC domain enable point and the
+/// boot-jobs path, which are gated separately — can both call it.
+#[cfg(feature = "mcp")]
+pub fn start(config: &crate::openhuman::config::Config) {
+ registry::bus::init();
+
+ if let Err(error) = host::init(config) {
+ log::warn!("[mcp] the service could not be opened; continuing without it: {error}");
+ }
+}
+
+/// Brings this domain up — the build without it, where there is nothing to do.
+#[cfg(not(feature = "mcp"))]
+pub fn start(_config: &crate::openhuman::config::Config) {}
+
pub mod audit;
// Ungated, like the transport below and for the same reason: `tinymcp` is an
// ordinary dependency, and the startup path calls `host::init` without a `cfg`
diff --git a/src/openhuman/mcp/registry/mod.rs b/src/openhuman/mcp/registry/mod.rs
index fcc1c4a643..8d65bf1b3e 100644
--- a/src/openhuman/mcp/registry/mod.rs
+++ b/src/openhuman/mcp/registry/mod.rs
@@ -308,7 +308,7 @@ pub mod oauth {
/// hit means are this application's, and a module dropping tools by criteria of
/// its own would be making a decision it cannot explain to anyone.
///
-/// A tool whose description or title trips a rule is dropped, and the drop is
+/// A tool whose description trips a rule is dropped, and the drop is
/// logged and published with the *rule code* only — the offending text is never
/// re-emitted, because the payload is the thing that was dangerous.
#[cfg(feature = "mcp")]
diff --git a/src/openhuman/mcp/registry/setup_ops.rs b/src/openhuman/mcp/registry/setup_ops.rs
index 76fce3231d..74814c1408 100644
--- a/src/openhuman/mcp/registry/setup_ops.rs
+++ b/src/openhuman/mcp/registry/setup_ops.rs
@@ -246,12 +246,14 @@ pub async fn mcp_setup_install_and_connect(
server_id: outcome.server_id.clone(),
qualified_name: qualified_name.clone(),
});
- if tool_count > 0 {
- BUS.publish(DomainEvent::McpServerConnected {
- server_id: outcome.server_id.clone(),
- tool_count,
- });
- }
+ // Unconditional, like the `connect` handler's. The call returning `Ok` is
+ // what says the connection succeeded; a server exposing only resources or
+ // prompts connects with zero tools, and gating on the count would leave
+ // anything tracking connection state believing it never came up.
+ BUS.publish(DomainEvent::McpServerConnected {
+ server_id: outcome.server_id.clone(),
+ tool_count,
+ });
Ok(RpcOutcome::new(
json!({