Skip to content

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

refactor(mcp): delegate host lifecycle to tinymcp

Steven Enamakele151f3bec5a4
diff --git a/crates/openhuman-core/src/mcp/host.rs b/crates/openhuman-core/src/mcp/host.rs
index 5df314c3c3..5d17d75a31 100644
--- a/crates/openhuman-core/src/mcp/host.rs
+++ b/crates/openhuman-core/src/mcp/host.rs
@@ -1,301 +1,27 @@
-//! The `tinymcp` service this process holds, and the conversion into it.
+//! OpenHuman-specific configuration for the TinyMCP module.
//!
-//! The MCP client lives in `tinymcp` now. What is left here is the host half:
-//! this holder, the RPC surface over it, the agent-facing tools, and the
-//! prompt-injection scan over remote tool definitions.
-//!
-//! # Why a holder exists at all
-//!
-//! Before the extraction the connection map, the pending-authorization map and
-//! the secret vault were process globals, so every caller reached them by
-//! calling a free function. `tinymcp` owns them instead — a library that
-//! installed globals would make two hosts in one process share connections, and
-//! would make its own tests order-dependent. So one instance lives here, and
-//! the free functions callers used become methods on it.
-//!
-//! # It is initialised once, at boot
-//!
-//! [`init`] is called from the core startup path, before anything that might
-//! reach for a server. A caller that arrives before then gets `None` rather
-//! than a lazily-built service on a configuration nobody chose.
-//!
-//! # The proxy decision is made here
-//!
-//! `tinymcp` takes an already-resolved proxy rather than a policy: whether a
-//! proxy applies to a given service is decided by this application's scope
-//! setting, its per-service list and its no-proxy list, and all three live
-//! here. [`proxy_for_mcp`] consults them and hands over the answer.
+//! This module keeps only host policy: converting product configuration to the
+//! module contract, resolving the product proxy, and constructing the OAuth
+//! redirect URL from the core's actual bound port. TinyMCP owns its service,
+//! stores, transports, registries, and supervisor.
-use std::collections::HashMap;
-use std::path::{Path, PathBuf};
-use std::sync::{Arc, Mutex, OnceLock};
-
-use tinymcp::{
- AuditStore, McpClientConfig, McpClientIdentityConfig, McpProxyConfig, McpRegistry,
- McpServerRegistry, Store,
-};
+use std::path::PathBuf;
+use std::sync::OnceLock;
use crate::config::Config;
-/// The service key MCP traffic is scoped under for proxy decisions.
const PROXY_SERVICE_KEY: &str = "tool.mcp_client";
-
-/// The port the core serves on when nothing says otherwise.
const DEFAULT_CORE_PORT: u16 = 7788;
-
-/// One service per workspace, opened on first use.
-///
-/// Not a single `OnceLock`. Every entry point into this domain is addressed by
-/// configuration — an RPC handler loads a `Config` and acts on *that* workspace
-/// — and one process serves more than one over its life: the workspace can be
-/// switched in place, and the test suite runs each case against its own. A
-/// single service bound to whichever configuration booted first would answer
-/// every one of those from the wrong store, silently.
-///
-/// The map is what keeps that cheap. Opening a service runs the store's
-/// migrations and builds an HTTP client, which no request path should pay for.
-/// Each entry carries the identity and proxy its host was built with, so the
-/// reconnect supervisor can dial with the same identity the host's connections
-/// use — `McpRegistry` keeps those private.
-static HOSTS: OnceLock<Mutex<HashMap<PathBuf, HostEntry>>> = OnceLock::new();
-
-/// One open host, with the identity and proxy it was built with.
-///
-/// The reconnect supervisor needs those to dial a reconnecting server with the
-/// same identity the host's connections use, and `McpRegistry` keeps them
-/// private. Storing them here — from the same `client_config` the host was
-/// opened from — is what lets one supervisor task cover every workspace: it
-/// rebuilds each host's `tinymcp::Supervisor` from the stored values rather
-/// than recomputing them from a configuration it does not have.
-#[derive(Debug)]
-struct HostEntry {
- host: Arc<McpHost>,
- identity: McpClientIdentityConfig,
- proxy: Option<McpProxyConfig>,
-}
-
-/// The workspace [`init`] opened, for the callers that have no `Config`.
-///
-/// A handful of paths — dropping a connection, listing a connected server's
-/// tools — are addressed by server id alone, because the connection map they
-/// read used to be a process global. They resolve through here.
-static DEFAULT_WORKSPACE: OnceLock<PathBuf> = OnceLock::new();
static DEFAULT_CONFIG: OnceLock<Config> = OnceLock::new();
-/// The three pieces of `tinymcp` this application drives.
-///
-/// Held together rather than separately because they are initialised from one
-/// configuration and share a lifetime. This is the same shape `tinymcp`'s own
-/// bus adapter assembles; that adapter is not used here, because a host calling
-/// the library directly has no use for a bus inside it.
-#[derive(Debug)]
-pub struct McpHost {
- dynamic: McpRegistry,
- static_servers: McpServerRegistry,
- audit: AuditStore,
-}
-
-/// Lets `tinymcp::Supervisor::run_many` reach the registry inside a host.
-impl AsRef<McpRegistry> for McpHost {
- fn as_ref(&self) -> &McpRegistry {
- &self.dynamic
- }
-}
-
-impl McpHost {
- /// Builds a host from `config`, without installing it as the process one.
- ///
- /// Public so a test can drive a host over its own workspace: the
- /// process-wide one is a `OnceLock`, and a suite that needs a fresh store
- /// per case cannot share it. The startup path and [`for_config`] build
- /// through [`from_client_config`] instead, so a host and the entry stored
- /// beside it share one conversion.
- ///
- /// # Errors
- ///
- /// Returns an error when either store cannot be opened, or when an HTTP
- /// client cannot be built.
- pub fn open(config: &Config) -> anyhow::Result<Self> {
- let client = client_config(config);
- Self::from_client_config(&host_key(config), &client)
- }
-
- /// Builds a host over `workspace` from an already-converted client
- /// configuration.
- ///
- /// [`open`] and [`for_config`] share this so both derive from the one
- /// conversion: a host and the entry stored beside it can never disagree
- /// about which identity and proxy they were built with.
- fn from_client_config(workspace: &Path, client: &McpClientConfig) -> anyhow::Result<Self> {
- std::fs::create_dir_all(workspace).map_err(|error| {
- anyhow::anyhow!("failed to create the mcp store directory: {error}")
- })?;
- Ok(Self {
- dynamic: McpRegistry::new(
- Store::open(workspace)
- .map_err(|error| anyhow::anyhow!("failed to open the mcp store: {error}"))?,
- client.registry_auth.clone(),
- client.client_identity.clone(),
- client.proxy.clone(),
- )
- .map_err(|error| anyhow::anyhow!("failed to start the mcp registry: {error}"))?,
- static_servers: McpServerRegistry::from_config(client).map_err(|error| {
- anyhow::anyhow!("failed to build the static server set: {error}")
- })?,
- audit: AuditStore::open(workspace)
- .map_err(|error| anyhow::anyhow!("failed to open the mcp audit log: {error}"))?,
- })
- }
-
- /// The user-installed servers, their connections, and the catalogs.
- #[must_use]
- pub fn dynamic(&self) -> &McpRegistry {
- &self.dynamic
- }
-
- /// The servers declared in this application's own configuration.
- #[must_use]
- pub fn static_servers(&self) -> &McpServerRegistry {
- &self.static_servers
- }
-
- /// The write-audit log.
- #[must_use]
- pub fn audit(&self) -> &AuditStore {
- &self.audit
- }
-}
-
-/// The service for `config`'s workspace, opening it on first use.
-///
-/// This is the entry point for every caller that has a `Config`, which is
-/// almost all of them. Two calls with the same workspace get the same service,
-/// so a connection opened through one is visible through the other.
-///
-/// # Errors
-///
-/// Returns an error when the stores cannot be opened or an HTTP client cannot
-/// be built.
-///
-/// Opening is not done under the process-wide lock: building a host runs the
-/// store's migrations and constructs an HTTP client, which no request path
-/// should pay for and no lock should be held across. The host is built first,
-/// and only then is the map locked to see whether another initializer won the
-/// race; if one did, its service is returned and the freshly-built one is
-/// dropped.
-pub fn for_config(config: &Config) -> anyhow::Result<Arc<McpHost>> {
- let workspace = host_key(config);
-
- // A host already under this workspace needs no re-opening: it would be
- // wasteful (and, on the common path, a plain Mutex of the shared map held
- // only for a lookup) to build a second one before noticing the first.
- let hosts = HOSTS.get_or_init(|| Mutex::new(HashMap::new()));
- if let Some(existing) = hosts
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner())
- .get(&workspace)
- {
- return Ok(Arc::clone(&existing.host));
- }
-
- // Build outside the lock: opening runs the store's migrations and builds
- // an HTTP client, neither of which should serialize or block a Tokio
- // worker behind the process-wide map. The client configuration is
- // converted once, so the host and the entry stored beside it share it.
- let client = client_config(config);
- let service = Arc::new(McpHost::from_client_config(&workspace, &client)?);
-
- // Recheck before inserting — a concurrent initializer may have won the
- // race while the service was being built. Its Arc wins; ours is dropped.
- let mut hosts = hosts
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner());
-
- if let Some(existing) = hosts.get(&workspace) {
- return Ok(Arc::clone(&existing.host));
- }
-
- tracing::debug!(key = ?workspace, "[mcp] opened host");
- hosts.insert(
- workspace,
- HostEntry {
- host: Arc::clone(&service),
- identity: client.client_identity,
- proxy: client.proxy,
- },
- );
-
- Ok(service)
-}
-
-/// The service for `config` when one exists, without creating an agent's.
-///
-/// Outside an agent context this is [`for_config`]. Under one, an agent that
-/// never installed a server has no store on disk, and a read (listing
-/// connections or tools) must not create one: it answers with an error the
-/// read paths already treat as "nothing connected".
-///
-/// # Errors
-///
-/// When the agent has no host yet, or [`for_config`] fails.
-pub fn lookup(config: &Config) -> anyhow::Result<Arc<McpHost>> {
- let key = host_key(config);
- // A SaaS profile's default agent keeps its host at its own workspace root
- // (no agent id), and a read must not create one there either.
- let tenant_owned = key != config.workspace_dir
- || crate::core::runtime::current_tenant().map_or(true, |t| t.profile.is_some());
- if tenant_owned {
- let open = HOSTS.get().and_then(|hosts| {
- hosts
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner())
- .get(&key)
- .map(|entry| Arc::clone(&entry.host))
- });
- if let Some(host) = open {
- return Ok(host);
- }
- if !Store::path_for(&key).exists() {
- anyhow::bail!("the agent has no mcp host yet");
- }
- }
- for_config(config)
-}
-
-/// Opens the service for `config` and marks its workspace the default.
-///
-/// Called once, from the core startup path. A second call opens nothing new and
-/// leaves the default alone, so a service already holding live connections is
-/// never displaced.
-///
-/// # Errors
-///
-/// Returns an error when the stores cannot be opened or an HTTP client cannot
-/// be built. A caller should log and continue: MCP being unavailable must not
-/// stop the core coming up.
-pub fn init(config: &Config) -> anyhow::Result<()> {
- for_config(config)?;
-
- set_default_config(config);
-
- if DEFAULT_WORKSPACE.set(config.workspace_dir.clone()).is_err() {
- tracing::debug!("[mcp] a default workspace was already set; leaving it alone");
- return Ok(());
- }
-
- tracing::info!(workspace = ?config.workspace_dir, "[mcp] service initialised");
- Ok(())
-}
-
-/// Remembers the process config for ambient MCP calls without opening a
-/// TinyMCP implementation in the host.
+/// Remembers the process config for ambient MCP calls without opening a module
+/// service in the host.
pub fn set_default_config(config: &Config) {
let _ = DEFAULT_CONFIG.set(config.clone());
}
/// The config named by the current scoped dispatch, or the process default
-/// outside a tenant scope. Ambient MCP helpers use this rather than resolving
-/// an implementation-owned process registry.
+/// outside a tenant scope.
pub fn ambient_config() -> Option<Config> {
match crate::core::runtime::current_tenant() {
Ok(tenant) if tenant.is_scoped() => {
@@ -305,156 +31,9 @@ pub fn ambient_config() -> Option<Config> {
}
}
-/// The service for the paths that have no `Config` to resolve by.
-///
-/// Anything holding one should call [`for_config`] instead, which cannot answer
-/// `None` and cannot answer from the wrong workspace.
-///
-/// Resolves in two steps. The workspace [`init`] opened wins, because that is
-/// the one this process booted against. Failing that — nothing has booted, but
-/// something opened a service anyway — a *single* open workspace is
-/// unambiguously the one meant, so it answers that. With several open and no
-/// default, there is no honest answer and it says so.
-///
-/// The second step is what makes the connection map readable from a caller that
-/// never booted: the agent's tool registry asks which MCP tools are live, and it
-/// asks by server id alone. Without it, a process that opened a service through
-/// [`for_config`] would still report nothing connected.
-#[must_use]
-pub fn try_service() -> Option<Arc<McpHost>> {
- if let Some(agent_host) = current_agent_host() {
- return agent_host;
- }
- let hosts = HOSTS
- .get()?
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner());
-
- resolve(DEFAULT_WORKSPACE.get().map(PathBuf::as_path), &hosts)
-}
-
-/// Removes the host of agent `agent_id` on `workspace_dir` from the open set
-/// and hands it back, so the caller can close its connections. `None` when
-/// the agent never opened one.
-pub fn take_agent_host(workspace_dir: &Path, agent_id: &str) -> Option<Arc<McpHost>> {
- let key = workspace_dir.join("agents").join(agent_id);
- let entry = HOSTS
- .get()?
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner())
- .remove(&key)?;
- tracing::debug!(agent = %agent_id, "[mcp] agent host evicted");
- Some(entry.host)
-}
-
-/// Where the host for `config` keeps its stores: the workspace, or the
-/// agent's own directory beneath it when an agent context is current. A SaaS
-/// profile's workspace is its own, so its default agent's host sits at the
-/// workspace root and never meets another profile's.
-fn host_key(config: &Config) -> PathBuf {
- crate::core::runtime::agent_scope_dir(config)
-}
-
-/// The current tenant's host, when a turn runs under an embedded agent's or
-/// a SaaS profile's context.
-///
-/// `None` outside both (the desktop's own sessions); `Some(None)` when the
-/// tenant's host cannot be opened, or a SaaS task has no tenant scope, which
-/// must not fall back to another tenant's or the default one.
-fn current_agent_host() -> Option<Option<Arc<McpHost>>> {
- let tenant = match crate::core::runtime::current_tenant() {
- Ok(tenant) if !tenant.is_scoped() => return None,
- Ok(tenant) => tenant,
- Err(no_tenant) => {
- tracing::debug!("[mcp] {no_tenant}; no host");
- return Some(None);
- }
- };
- let Some(opened) = crate::core::runtime::CoreContext::with_current_embedder_config(lookup)
- else {
- // A scoped tenant always carries its own config; without one there is
- // no host it may use.
- return tenant.profile.is_some().then_some(None);
- };
- Some(match opened {
- Ok(host) => Some(host),
- Err(error) => {
- tracing::debug!(
- agent = tenant.agent.as_deref().unwrap_or(""),
- profile_scoped = tenant.profile.is_some(),
- ?error,
- "[mcp] tenant host unavailable"
- );
- None
- }
- })
-}
-
-/// 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, HostEntry>) -> Option<Arc<McpHost>> {
- if let Some(workspace) = default {
- if let Some(entry) = hosts.get(workspace) {
- return Some(Arc::clone(&entry.host));
- }
- }
-
- match hosts.len() {
- 1 => hosts.values().next().map(|entry| Arc::clone(&entry.host)),
- _ => None,
- }
-}
-
-/// The default workspace's service, erroring when it is not up yet.
-///
-/// # Errors
-///
-/// Returns a message naming the state, so an RPC caller learns the core is
-/// still starting rather than that their server does not exist.
-pub fn service() -> Result<Arc<McpHost>, String> {
- try_service().ok_or_else(|| "the mcp service is not initialised yet".to_string())
-}
-
-/// Every host currently open, with the identity and proxy each was built with.
-///
-/// The reconnect supervisor walks this each tick: one task supervises every
-/// workspace's installed servers, including a host opened after boot (a
-/// workspace switch), not just the one booted against. The identity and proxy
-/// ride along because a reconnect must dial with the same identity the host's
-/// connections use, and `McpRegistry` keeps those private.
-#[must_use]
-pub fn all_hosts() -> Vec<(
- PathBuf,
- Arc<McpHost>,
- McpClientIdentityConfig,
- Option<McpProxyConfig>,
-)> {
- let Some(hosts) = HOSTS.get() else {
- return Vec::new();
- };
-
- hosts
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner())
- .iter()
- .map(|(workspace, entry)| {
- (
- workspace.clone(),
- Arc::clone(&entry.host),
- entry.identity.clone(),
- entry.proxy.clone(),
- )
- })
- .collect()
-}
-
-/// Converts the MCP section of this application's configuration.
-pub fn client_config(config: &Config) -> McpClientConfig {
- let mut client = McpClientConfig {
+/// Converts the MCP section of product configuration to the module contract.
+pub fn client_config(config: &Config) -> tinymcp_bus::McpClientConfig {
+ let mut client = tinymcp_bus::McpClientConfig {
enabled: config.mcp_client.enabled,
servers: config
.mcp_client
@@ -464,35 +43,21 @@ pub fn client_config(config: &Config) -> McpClientConfig {
.map(|server| server.server.clone())
.collect(),
proxy: proxy_for_mcp(),
- ..McpClientConfig::default()
+ ..tinymcp_bus::McpClientConfig::default()
};
client.client_identity.name = config.mcp_client.client_identity.name.clone();
client.client_identity.title = config.mcp_client.client_identity.title.clone();
client.client_identity.version = config.mcp_client.client_identity.version.clone();
-
client.registry_auth = config.mcp_client.registry_auth.clone();
- // The documentation server is deliberately not seeded as an MCP server:
- // `gitbooks_search` / `gitbooks_get_page` are hard-coded deferred tools
- // (`tools::implementations::network::gitbooks`). Seeding it here made every
- // first turn dial the endpoint for `tools/list` and register the generic
- // MCP bridge tools for nothing.
-
+ // GitBooks uses dedicated deferred tools and is not part of the configured
+ // server set, so first-turn tool assembly never dials it for a catalog.
client
}
-/// Whether a declared server's transport may be dialed with its configured
-/// credentials attached.
-///
-/// Attaching a credential to an outbound request only makes sense when the
-/// request cannot be read by a third party in transit — i.e. when the endpoint
-/// is HTTPS, or is on the loopback interface where the bytes never leave the
-/// machine. A credentialed plaintext-HTTP endpoint on any other host would put
-/// the credential on the wire in the clear, so it is refused: the server is
-/// dropped from the configured set with a warning rather than silently sent.
-///
-/// stdio servers (no `endpoint`) and credential-less servers are always fine.
+/// Whether a configured credential may be sent to its endpoint. Credentials
+/// are allowed over HTTPS, stdio, or loopback HTTP only.
fn credentialed_endpoint_transport_allowed(server: &crate::config::McpServerConfig) -> bool {
use crate::config::McpAuthConfig;
@@ -501,65 +66,33 @@ fn credentialed_endpoint_transport_allowed(server: &crate::config::McpServerConf
}
let endpoint = server.endpoint.trim();
if endpoint.is_empty() {
- // stdio subprocess — credentials are passed via env, not the wire.
return true;
}
let Ok(url) = reqwest::Url::parse(endpoint) else {
- // Unparsable endpoints fail later with a clearer "could not build the
- // static server set" message; nothing is attached on this path.
return true;
};
- if url.scheme() == "https" {
- return true;
- }
- if url.scheme() != "http" {
- // Unknown scheme — let the transport decide rather than guessing.
+ if url.scheme() == "https" || !matches!(url.scheme(), "http") {
return true;
}
let loopback = url
.host_str()
- .map(|host| host == "localhost" || host == "127.0.0.1" || host == "::1")
- .unwrap_or(false);
+ .is_some_and(|host| matches!(host, "localhost" | "127.0.0.1" | "::1"));
if loopback {
return true;
}
tracing::warn!(
- "[mcp] refusing credentialed server `{}`: plaintext HTTP endpoint {endpoint} is not loopback; use https:// instead",
- server.name
+ server = %server.name,
+ "[mcp] refusing credentialed plaintext HTTP endpoint; use https:// instead"
);
false
}
-/// The statically declared server set, built from this application's
-/// configuration.
-///
-/// A set that cannot be built — a malformed proxy, an unusable TLS setting — is
-/// logged and reported as empty. Those conditions affect every server equally,
-/// and taking the whole tool surface down over one of them helps nobody: the
-/// agent loses its MCP tools either way, and an empty set says so without also
-/// failing whatever else was being assembled.
-#[must_use]
-pub fn static_registry(config: &Config) -> McpServerRegistry {
- match McpServerRegistry::from_config(&client_config(config)) {
- Ok(registry) => registry,
- Err(error) => {
- tracing::warn!("[mcp] could not build the static server set: {error}");
- McpServerRegistry::default()
- }
- }
-}
-
-/// The loopback address a browser sign-in redirects back to.
-///
-/// `tinymcp` takes this rather than deriving it, and correctly: only this
-/// application knows which port it actually bound, which may not be the one it
-/// asked for. A wrong guess sends the browser to a dead listener, where sign-in
-/// simply hangs with nothing to explain it.
-///
-/// In order: the address the core advertised after binding, then the requested
-/// port, then the default.
+/// The loopback address a browser sign-in redirects back to: the bound core
+/// port, then the requested port, then the default.
pub fn oauth_redirect_uri() -> String {
- let port = advertised_port()
+ let port = std::env::var("OPENHUMAN_CORE_RPC_URL")
+ .ok()
+ .and_then(|url| explicit_port(&url))
.or_else(|| {
std::env::var("OPENHUMAN_CORE_PORT")
.ok()
@@ -570,36 +103,18 @@ pub fn oauth_redirect_uri() -> String {
format!("http://127.0.0.1:{port}/oauth/mcp/callback")
}
-/// The port the core actually bound, read from what it advertised.
-///
-/// Authoritative when present: it reflects any fallback the core took when its
-/// preferred port was busy.
-fn advertised_port() -> Option<u16> {
- let advertised = std::env::var("OPENHUMAN_CORE_RPC_URL").ok()?;
- explicit_port(&advertised)
-}
-
-/// The explicit port in a URL, or `None` when it names none.
-///
-/// Kept separate so it is testable without touching the process environment.
fn explicit_port(url: &str) -> Option<u16> {
reqwest::Url::parse(url).ok().and_then(|url| url.port())
}
-/// The proxy MCP traffic should use, or `None` to connect directly.
-///
-/// Resolved here because the *policy* lives here: the scope setting, the
-/// per-service list and the no-proxy list are this application's, and sending
-/// the decision rather than the policy keeps them in the one place that owns
-/// them.
-pub fn proxy_for_mcp() -> Option<McpProxyConfig> {
+/// The proxy MCP traffic should use, or `None` to connect directly. The scope,
+/// per-service list, and no-proxy list are OpenHuman policy.
+pub fn proxy_for_mcp() -> Option<tinymcp_bus::McpProxyConfig> {
let proxy = crate::config::runtime_proxy_config();
-
if !proxy.should_apply_to_service(PROXY_SERVICE_KEY) {
return None;
}
-
- Some(McpProxyConfig {
+ Some(tinymcp_bus::McpProxyConfig {
http_proxy: proxy.http_proxy.clone(),
https_proxy: proxy.https_proxy.clone(),
all_proxy: proxy.all_proxy.clone(),
@@ -610,7 +125,3 @@ pub fn proxy_for_mcp() -> Option<McpProxyConfig> {
#[cfg(test)]
#[path = "host_tests.rs"]
mod tests;
-
-#[cfg(test)]
-#[path = "host_agent_tests.rs"]
-mod agent_tests;
diff --git a/crates/openhuman-core/src/mcp/host_agent_tests.rs b/crates/openhuman-core/src/mcp/host_agent_tests.rs
deleted file mode 100644
index 86e53cccba..0000000000
--- a/crates/openhuman-core/src/mcp/host_agent_tests.rs
+++ /dev/null
@@ -1,142 +0,0 @@
-use super::*;
-use crate::core::runtime::{context::CoreContext, ContextOverlay, DomainSet};
-use crate::tools::toolpacks::ToolGroups;
-
-fn workspace_config(workspace: &Path) -> Config {
- let mut config = Config::default();
- config.gitbooks.enabled = false;
- config.workspace_dir = workspace.to_path_buf();
- config
-}
-
-fn agent_context(config: &Config, agent: &str) -> Arc<CoreContext> {
- CoreContext::for_test_with_config(DomainSet::full(), config.clone()).derive_with(
- ContextOverlay::new(config.clone(), DomainSet::full(), ToolGroups::none())
- .session_agent(agent),
- )
-}
-
-#[tokio::test]
-async fn each_agent_gets_its_own_host_under_its_scope_dir() {
- let temporary = tempfile::tempdir().expect("tempdir");
- let config = workspace_config(temporary.path());
-
- let alpha = CoreContext::scope(agent_context(&config, "alpha"), async {
- for_config(&config).expect("alpha's host opens")
- })
- .await;
- let beta = CoreContext::scope(agent_context(&config, "beta"), async {
- for_config(&config).expect("beta's host opens")
- })
- .await;
- let workspace = for_config(&config).expect("the workspace host opens");
-
- assert!(!Arc::ptr_eq(&alpha, &beta));
- assert!(!Arc::ptr_eq(&alpha, &workspace));
- let alpha_dir = temporary.path().join("agents").join("alpha");
- assert!(tinymcp::Store::path_for(&alpha_dir).exists());
- assert!(tinymcp::AuditStore::path_for(&alpha_dir).exists());
- assert!(tinymcp::Store::path_for(temporary.path()).exists());
-}
-
-#[tokio::test]
-async fn the_ambient_service_under_an_agent_is_that_agents_host() {
- let temporary = tempfile::tempdir().expect("tempdir");
- let config = workspace_config(temporary.path());
-
- let (addressed, ambient) = CoreContext::scope(agent_context(&config, "gamma"), async {
- let addressed = for_config(&config).expect("the agent's host opens");
- (
- addressed,
- try_service().expect("an opened agent host is ambient"),
- )
- })
- .await;
-
- assert!(Arc::ptr_eq(&ambient, &addressed));
- let outside = for_config(&config).expect("the workspace host opens");
- assert!(!Arc::ptr_eq(&ambient, &outside));
-}
-
-#[tokio::test]
-async fn an_evicted_agent_host_is_reopened_fresh() {
- let temporary = tempfile::tempdir().expect("tempdir");
- let config = workspace_config(temporary.path());
-
- let first = CoreContext::scope(agent_context(&config, "delta"), async {
- for_config(&config).expect("delta's host opens")
- })
- .await;
- let taken = take_agent_host(temporary.path(), "delta").expect("delta had a host");
- assert!(Arc::ptr_eq(&first, &taken));
- assert!(take_agent_host(temporary.path(), "delta").is_none());
-
- let reopened = CoreContext::scope(agent_context(&config, "delta"), async {
- for_config(&config).expect("delta's host reopens")
- })
- .await;
- assert!(!Arc::ptr_eq(&first, &reopened));
-}
-
-#[tokio::test]
-async fn reading_an_agents_connections_does_not_create_its_host() {
- let temporary = tempfile::tempdir().expect("tempdir");
- let config = workspace_config(temporary.path());
-
- let (looked_up, ambient) = CoreContext::scope(agent_context(&config, "epsilon"), async {
- (lookup(&config).is_err(), try_service().is_none())
- })
- .await;
-
- assert!(looked_up, "no host exists for a fresh agent");
- assert!(ambient, "the ambient lookup answers nothing connected");
- assert!(!temporary.path().join("agents").join("epsilon").exists());
-}
-
-/// A profile's context as the SaaS profile host derives it: the profile's
-/// own workspace, a profile id, and no agent id.
-fn profile_context(config: &Config, profile: &str) -> Arc<CoreContext> {
- CoreContext::for_test_with_config(DomainSet::full(), config.clone()).derive_with(
- ContextOverlay::new(config.clone(), DomainSet::full(), ToolGroups::none()).profile(profile),
- )
-}
-
-#[tokio::test]
-async fn two_profiles_default_agents_get_their_own_hosts_and_never_the_default() {
- let (one, two) = (
- tempfile::tempdir().expect("tempdir"),
- tempfile::tempdir().expect("tempdir"),
- );
- let (alice, bob) = (workspace_config(one.path()), workspace_config(two.path()));
-
- // Before either installed anything, neither sees a host — not each
- // other's, not the process default — and a read creates none.
- for (config, name) in [(&alice, "alice"), (&bob, "bob")] {
- let seen = CoreContext::scope(profile_context(config, name), async { try_service() }).await;
- assert!(seen.is_none(), "{name} saw a host it never opened");
- assert!(!tinymcp::Store::path_for(&config.workspace_dir).exists());
- }
-
- let alice_host = CoreContext::scope(profile_context(&alice, "alice"), async {
- for_config(&alice).expect("alice's host opens")
- })
- .await;
- let bob_host = CoreContext::scope(profile_context(&bob, "bob"), async {
- for_config(&bob).expect("bob's host opens")
- })
- .await;
- assert!(!Arc::ptr_eq(&alice_host, &bob_host));
- // The default agent's host sits at the profile's workspace root.
- assert!(tinymcp::Store::path_for(one.path()).exists());
- assert!(!one.path().join("agents").exists());
-
- let ambient_alice =
- CoreContext::scope(profile_context(&alice, "alice"), async { try_service() }).await;
- let ambient_bob =
- CoreContext::scope(profile_context(&bob, "bob"), async { try_service() }).await;
- assert!(Arc::ptr_eq(
- &ambient_alice.expect("alice's host"),
- &alice_host
- ));
- assert!(Arc::ptr_eq(&ambient_bob.expect("bob's host"), &bob_host));
-}