M5: rmcp stdio client and tool adapters
Adds an rmcp-based stdio MCP client in harness-mcp plus adapters exposing a configured server's tools as namespaced harness-tools, with an echo-server fixture and integration test, and wiring through harness-app.
This commit is contained in:
Generated
+170
-2
@@ -35,6 +35,15 @@ version = "0.2.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
|
||||
|
||||
[[package]]
|
||||
name = "android_system_properties"
|
||||
version = "0.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anyhow"
|
||||
version = "1.0.103"
|
||||
@@ -92,6 +101,18 @@ version = "1.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
|
||||
|
||||
[[package]]
|
||||
name = "autocfg"
|
||||
version = "1.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
||||
|
||||
[[package]]
|
||||
name = "base64"
|
||||
version = "0.21.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567"
|
||||
|
||||
[[package]]
|
||||
name = "base64"
|
||||
version = "0.22.1"
|
||||
@@ -175,6 +196,20 @@ dependencies = [
|
||||
"rand_core 0.10.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "chrono"
|
||||
version = "0.4.45"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"
|
||||
dependencies = [
|
||||
"iana-time-zone",
|
||||
"js-sys",
|
||||
"num-traits",
|
||||
"serde",
|
||||
"wasm-bindgen",
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "compact_str"
|
||||
version = "0.8.2"
|
||||
@@ -217,6 +252,12 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "core-foundation-sys"
|
||||
version = "0.8.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.3.0"
|
||||
@@ -723,7 +764,16 @@ dependencies = [
|
||||
name = "harness-mcp"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"harness-core",
|
||||
"rmcp",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tokio-util",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -914,7 +964,7 @@ version = "0.1.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"base64 0.22.1",
|
||||
"bytes",
|
||||
"futures-channel",
|
||||
"futures-util",
|
||||
@@ -931,6 +981,30 @@ dependencies = [
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "iana-time-zone"
|
||||
version = "0.1.65"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"
|
||||
dependencies = [
|
||||
"android_system_properties",
|
||||
"core-foundation-sys",
|
||||
"iana-time-zone-haiku",
|
||||
"js-sys",
|
||||
"log",
|
||||
"wasm-bindgen",
|
||||
"windows-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "iana-time-zone-haiku"
|
||||
version = "0.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
|
||||
dependencies = [
|
||||
"cc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_collections"
|
||||
version = "2.2.0"
|
||||
@@ -1298,6 +1372,15 @@ version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
|
||||
|
||||
[[package]]
|
||||
name = "num-traits"
|
||||
version = "0.2.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
|
||||
dependencies = [
|
||||
"autocfg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.21.4"
|
||||
@@ -1605,7 +1688,7 @@ version = "0.12.28"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"base64 0.22.1",
|
||||
"bytes",
|
||||
"futures-core",
|
||||
"futures-util",
|
||||
@@ -1654,6 +1737,38 @@ dependencies = [
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rmcp"
|
||||
version = "0.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "33a0110d28bd076f39e14bfd5b0340216dd18effeb5d02b43215944cc3e5c751"
|
||||
dependencies = [
|
||||
"base64 0.21.7",
|
||||
"chrono",
|
||||
"futures",
|
||||
"paste",
|
||||
"pin-project-lite",
|
||||
"rmcp-macros",
|
||||
"schemars",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tokio-util",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rmcp-macros"
|
||||
version = "0.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a6e2b2fd7497540489fa2db285edd43b7ed14c49157157438664278da6e42a7a"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rusqlite"
|
||||
version = "0.32.1"
|
||||
@@ -2605,12 +2720,65 @@ version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
|
||||
|
||||
[[package]]
|
||||
name = "windows-core"
|
||||
version = "0.62.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
|
||||
dependencies = [
|
||||
"windows-implement",
|
||||
"windows-interface",
|
||||
"windows-link",
|
||||
"windows-result",
|
||||
"windows-strings",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-implement"
|
||||
version = "0.60.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-interface"
|
||||
version = "0.59.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-link"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
||||
|
||||
[[package]]
|
||||
name = "windows-result"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-strings"
|
||||
version = "0.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.48.0"
|
||||
|
||||
@@ -20,7 +20,7 @@ use harness_core::lsp::DiagnosticsSource;
|
||||
use harness_core::permission::{PermissionReply, PermissionService, Rule, Ruleset};
|
||||
use harness_core::store::{Store, StoreError};
|
||||
use harness_core::tool::{
|
||||
ContextReporter, SpawnError, SpawnOutcome, SpawnRequest, SubagentSpawner, ToolRegistry,
|
||||
ContextReporter, SpawnError, SpawnOutcome, SpawnRequest, SubagentSpawner, Tool, ToolRegistry,
|
||||
};
|
||||
use harness_core::types::{
|
||||
Message, MessageId, ModelRef, Part, PartBody, PartId, Session, SessionId,
|
||||
@@ -76,6 +76,71 @@ fn db_path(cwd: &Path) -> PathBuf {
|
||||
base.join(format!("{}.sqlite", slug))
|
||||
}
|
||||
|
||||
/// Builds the provider registry from config: every provider with an API key is registered.
|
||||
fn providers_from_config(config: &Config) -> ProviderRegistry {
|
||||
let mut providers = ProviderRegistry::new();
|
||||
if let Some(key) = config
|
||||
.providers
|
||||
.get("anthropic")
|
||||
.and_then(|p| p.api_key.clone())
|
||||
{
|
||||
providers.register(Arc::new(AnthropicProvider::new(key)));
|
||||
}
|
||||
if let Some(key) = config
|
||||
.providers
|
||||
.get("openai")
|
||||
.and_then(|p| p.api_key.clone())
|
||||
{
|
||||
let provider = match config
|
||||
.providers
|
||||
.get("openai")
|
||||
.and_then(|p| p.base_url.clone())
|
||||
{
|
||||
Some(base_url) => OpenAiProvider::with_base_url(key, base_url),
|
||||
None => OpenAiProvider::new(key),
|
||||
};
|
||||
providers.register(Arc::new(provider));
|
||||
}
|
||||
// OpenCode Zen: OpenAI-compatible chat gateway under its own `opencode` provider id, so it
|
||||
// coexists with a real `openai` provider. `base_url` defaults to Zen's endpoint.
|
||||
if let Some(key) = config
|
||||
.providers
|
||||
.get("opencode")
|
||||
.and_then(|p| p.api_key.clone())
|
||||
{
|
||||
let base_url = config
|
||||
.providers
|
||||
.get("opencode")
|
||||
.and_then(|p| p.base_url.clone());
|
||||
providers.register(Arc::new(OpenAiProvider::opencode(key, base_url)));
|
||||
}
|
||||
providers
|
||||
}
|
||||
|
||||
/// Connects every enabled MCP server declared in config and returns their tool adapters. A
|
||||
/// server that fails to start is logged and skipped inside `harness_mcp` — never fatal.
|
||||
async fn connect_mcp_tools(config: &Config) -> Vec<Arc<dyn Tool>> {
|
||||
let servers: HashMap<String, harness_mcp::ServerConfig> = config
|
||||
.mcp
|
||||
.iter()
|
||||
.filter(|(_, c)| c.enabled.unwrap_or(true) && !c.command.is_empty())
|
||||
.map(|(name, c)| {
|
||||
(
|
||||
name.clone(),
|
||||
harness_mcp::ServerConfig {
|
||||
command: c.command.clone(),
|
||||
args: c.args.clone(),
|
||||
env: c.env.clone(),
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
if servers.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
harness_mcp::connect_all(servers).await
|
||||
}
|
||||
|
||||
/// Non-blocking, multi-turn engine API used by the TUI.
|
||||
#[derive(Clone)]
|
||||
pub struct EngineHandle {
|
||||
@@ -111,69 +176,36 @@ struct RunHandle {
|
||||
|
||||
impl EngineHandle {
|
||||
/// Persistent SQLite-backed store. Used by the TUI and the default headless `App`.
|
||||
pub fn init(cwd: PathBuf) -> Result<Self, AppError> {
|
||||
/// Async because it connects any configured MCP servers (spawn + initialize + list tools)
|
||||
/// before the first turn so their tools are advertised to the model.
|
||||
pub async fn init(cwd: PathBuf) -> Result<Self, AppError> {
|
||||
let path = db_path(&cwd);
|
||||
let store = Store::open(&path)?;
|
||||
let handle = Self::new(cwd, store)?;
|
||||
let config = config::load(&cwd)?;
|
||||
let providers = providers_from_config(&config);
|
||||
let mcp_tools = connect_mcp_tools(&config).await;
|
||||
let handle = Self::build(cwd, store, config, providers, mcp_tools)?;
|
||||
handle.spawn_catalog_refresh();
|
||||
Ok(handle)
|
||||
}
|
||||
|
||||
/// In-memory store — useful for tests and ephemeral sessions.
|
||||
/// In-memory store — useful for tests and ephemeral sessions. Skips MCP (no external
|
||||
/// servers in tests) and stays synchronous.
|
||||
pub fn init_in_memory(cwd: PathBuf) -> Result<Self, AppError> {
|
||||
let store = Store::open_in_memory()?;
|
||||
Self::new(cwd, store)
|
||||
}
|
||||
|
||||
fn new(cwd: PathBuf, store: Store) -> Result<Self, AppError> {
|
||||
let config = config::load(&cwd)?;
|
||||
|
||||
let mut providers = ProviderRegistry::new();
|
||||
if let Some(key) = config
|
||||
.providers
|
||||
.get("anthropic")
|
||||
.and_then(|p| p.api_key.clone())
|
||||
{
|
||||
providers.register(Arc::new(AnthropicProvider::new(key)));
|
||||
}
|
||||
if let Some(key) = config
|
||||
.providers
|
||||
.get("openai")
|
||||
.and_then(|p| p.api_key.clone())
|
||||
{
|
||||
let provider = match config
|
||||
.providers
|
||||
.get("openai")
|
||||
.and_then(|p| p.base_url.clone())
|
||||
{
|
||||
Some(base_url) => OpenAiProvider::with_base_url(key, base_url),
|
||||
None => OpenAiProvider::new(key),
|
||||
};
|
||||
providers.register(Arc::new(provider));
|
||||
}
|
||||
// OpenCode Zen: OpenAI-compatible chat gateway under its own `opencode` provider id,
|
||||
// so it coexists with a real `openai` provider. `base_url` defaults to Zen's endpoint.
|
||||
if let Some(key) = config
|
||||
.providers
|
||||
.get("opencode")
|
||||
.and_then(|p| p.api_key.clone())
|
||||
{
|
||||
let base_url = config
|
||||
.providers
|
||||
.get("opencode")
|
||||
.and_then(|p| p.base_url.clone());
|
||||
providers.register(Arc::new(OpenAiProvider::opencode(key, base_url)));
|
||||
}
|
||||
|
||||
Self::build(cwd, store, config, providers)
|
||||
let providers = providers_from_config(&config);
|
||||
Self::build(cwd, store, config, providers, Vec::new())
|
||||
}
|
||||
|
||||
/// Shared construction over an explicit provider set — the seam tests use to inject a mock.
|
||||
/// Shared construction over an explicit provider set and pre-connected extra tools (MCP) —
|
||||
/// the seam the tests use to inject a mock provider.
|
||||
fn build(
|
||||
cwd: PathBuf,
|
||||
store: Store,
|
||||
config: Config,
|
||||
providers: ProviderRegistry,
|
||||
extra_tools: Vec<Arc<dyn Tool>>,
|
||||
) -> Result<Self, AppError> {
|
||||
let bus = EventBus::new();
|
||||
let permissions = Arc::new(PermissionService::new(bus.clone()));
|
||||
@@ -181,6 +213,9 @@ impl EngineHandle {
|
||||
let mut tools = ToolRegistry::new();
|
||||
harness_tools::register_builtins(&mut tools);
|
||||
harness_tools::register_task_tool(&mut tools);
|
||||
for tool in extra_tools {
|
||||
tools.register(tool);
|
||||
}
|
||||
|
||||
// Layered agent registry: bundled markdown → global dir → project dir → config patches.
|
||||
let global_agent_dir = dirs::config_dir().map(|d| d.join("ai-harness").join("agent"));
|
||||
@@ -888,8 +923,8 @@ pub struct App {
|
||||
impl App {
|
||||
/// Persistent SQLite-backed store with an auto-approve permission frontend — the default
|
||||
/// headless configuration used by `harness run -p`.
|
||||
pub fn init(cwd: PathBuf) -> Result<Self, AppError> {
|
||||
let engine = EngineHandle::init(cwd)?;
|
||||
pub async fn init(cwd: PathBuf) -> Result<Self, AppError> {
|
||||
let engine = EngineHandle::init(cwd).await?;
|
||||
let _auto_approve_handle = Some(spawn_auto_approve_task(&engine));
|
||||
Ok(Self {
|
||||
engine,
|
||||
@@ -1018,6 +1053,7 @@ mod tests {
|
||||
Store::open_in_memory().unwrap(),
|
||||
Config::default(),
|
||||
providers,
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
@@ -1107,6 +1143,7 @@ mod tests {
|
||||
Store::open_in_memory().unwrap(),
|
||||
Config::default(),
|
||||
providers,
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap();
|
||||
// Auto-approve permission asks (the child's read tool gates on `read`).
|
||||
|
||||
@@ -6,6 +6,17 @@ license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
harness-core = { workspace = true }
|
||||
rmcp = { workspace = true, features = ["client", "transport-child-process"] }
|
||||
tokio = { workspace = true }
|
||||
async-trait = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
tokio-util = { workspace = true }
|
||||
tempfile = { workspace = true }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
@@ -1 +1,261 @@
|
||||
// MCP stdio client → Tool adapters land here in M5.
|
||||
//! MCP stdio client → `Tool` adapters (M5). For each configured server we spawn the child
|
||||
//! over rmcp's `TokioChildProcess` transport, `initialize`, `list_tools`, and wrap every
|
||||
//! remote tool as an [`McpTool`] named `{server}_{tool}`. Servers are gated behind the `mcp`
|
||||
//! permission key. See `docs/09-integrations.md`.
|
||||
//!
|
||||
//! Out of scope for v1 (matching the doc): resources, prompts, sampling, and non-stdio
|
||||
//! transports.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use harness_core::tool::{Tool, ToolCtx, ToolError, ToolOutput};
|
||||
use rmcp::model::{CallToolRequestParam, RawContent};
|
||||
use rmcp::service::RunningService;
|
||||
use rmcp::transport::TokioChildProcess;
|
||||
use rmcp::{RoleClient, ServiceExt};
|
||||
use tokio::process::Command;
|
||||
|
||||
/// Sanitized-name cap so a `{server}_{tool}` name stays a legal tool identifier.
|
||||
const MAX_NAME_LEN: usize = 64;
|
||||
|
||||
/// One configured MCP server: the child command plus its environment.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ServerConfig {
|
||||
pub command: String,
|
||||
pub args: Vec<String>,
|
||||
pub env: HashMap<String, String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
enum ConnectError {
|
||||
#[error("spawn/transport failed: {0}")]
|
||||
Transport(#[from] std::io::Error),
|
||||
#[error("MCP service error: {0}")]
|
||||
Service(#[from] rmcp::service::ServiceError),
|
||||
}
|
||||
|
||||
/// Connects every configured server and returns ready tool adapters. A server that fails to
|
||||
/// start (or list its tools) is logged and skipped — the rest are unaffected, and the session
|
||||
/// still runs with whatever connected. `named_servers` is `{server_name: config}`.
|
||||
pub async fn connect_all(named_servers: HashMap<String, ServerConfig>) -> Vec<Arc<dyn Tool>> {
|
||||
let mut tools: Vec<Arc<dyn Tool>> = Vec::new();
|
||||
for (name, config) in named_servers {
|
||||
match connect(&name, &config).await {
|
||||
Ok(mut server_tools) => {
|
||||
tracing::info!(server = %name, count = server_tools.len(), "MCP server connected");
|
||||
tools.append(&mut server_tools);
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(server = %name, error = %e, "MCP server failed to start; skipping");
|
||||
}
|
||||
}
|
||||
}
|
||||
tools
|
||||
}
|
||||
|
||||
async fn connect(name: &str, config: &ServerConfig) -> Result<Vec<Arc<dyn Tool>>, ConnectError> {
|
||||
let mut command = Command::new(&config.command);
|
||||
command.args(&config.args);
|
||||
for (key, value) in &config.env {
|
||||
command.env(key, value);
|
||||
}
|
||||
// rmcp sets stdin/stdout to piped and kill-on-drop; the child dies with the `RunningService`.
|
||||
let transport = TokioChildProcess::new(&mut command)?;
|
||||
let service = Arc::new(().serve(transport).await?);
|
||||
|
||||
let remote_tools = service.peer().list_all_tools().await?;
|
||||
let adapters = remote_tools
|
||||
.into_iter()
|
||||
.map(|tool| {
|
||||
let full_name = qualified_name(name, &tool.name);
|
||||
let parameters = serde_json::Value::Object((*tool.input_schema).clone());
|
||||
Arc::new(McpTool {
|
||||
full_name,
|
||||
remote_name: tool.name.to_string(),
|
||||
description: tool.description.to_string(),
|
||||
parameters,
|
||||
service: service.clone(),
|
||||
}) as Arc<dyn Tool>
|
||||
})
|
||||
.collect();
|
||||
Ok(adapters)
|
||||
}
|
||||
|
||||
/// `{server}_{tool}` sanitized to `[a-zA-Z0-9_-]` and capped at [`MAX_NAME_LEN`] chars.
|
||||
fn qualified_name(server: &str, tool: &str) -> String {
|
||||
let mut name: String = format!("{server}_{tool}")
|
||||
.chars()
|
||||
.map(|c| {
|
||||
if c.is_ascii_alphanumeric() || c == '_' || c == '-' {
|
||||
c
|
||||
} else {
|
||||
'_'
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
name.truncate(MAX_NAME_LEN);
|
||||
name
|
||||
}
|
||||
|
||||
/// A single remote MCP tool exposed to the engine as a `Tool`. Holds a shared handle to the
|
||||
/// server's `RunningService` (kept alive for the whole session so the child stays up).
|
||||
struct McpTool {
|
||||
/// Engine-facing name: sanitized `{server}_{tool}`; also the permission pattern.
|
||||
full_name: String,
|
||||
/// The server's own tool name, sent back verbatim in `call_tool`.
|
||||
remote_name: String,
|
||||
description: String,
|
||||
parameters: serde_json::Value,
|
||||
service: Arc<RunningService<RoleClient, ()>>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Tool for McpTool {
|
||||
fn name(&self) -> &str {
|
||||
&self.full_name
|
||||
}
|
||||
|
||||
fn description(&self) -> &str {
|
||||
&self.description
|
||||
}
|
||||
|
||||
fn parameters(&self) -> serde_json::Value {
|
||||
self.parameters.clone()
|
||||
}
|
||||
|
||||
async fn execute(
|
||||
&self,
|
||||
input: serde_json::Value,
|
||||
ctx: ToolCtx,
|
||||
) -> Result<ToolOutput, ToolError> {
|
||||
ctx.ask
|
||||
.ask(
|
||||
"mcp",
|
||||
self.full_name.clone(),
|
||||
self.full_name.clone(),
|
||||
input.clone(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
let arguments = match input {
|
||||
serde_json::Value::Object(map) => Some(map),
|
||||
serde_json::Value::Null => None,
|
||||
other => {
|
||||
return Err(ToolError::Invalid(format!(
|
||||
"MCP tool arguments must be a JSON object, got {other}"
|
||||
)))
|
||||
}
|
||||
};
|
||||
|
||||
let result = self
|
||||
.service
|
||||
.peer()
|
||||
.call_tool(CallToolRequestParam {
|
||||
name: self.remote_name.clone().into(),
|
||||
arguments,
|
||||
})
|
||||
.await
|
||||
.map_err(|e| ToolError::Other(e.to_string()))?;
|
||||
|
||||
let mut text = String::new();
|
||||
let mut image_index = 0;
|
||||
for content in &result.content {
|
||||
match &content.raw {
|
||||
RawContent::Text(t) => {
|
||||
if !text.is_empty() {
|
||||
text.push('\n');
|
||||
}
|
||||
text.push_str(&t.text);
|
||||
}
|
||||
RawContent::Image(image) => {
|
||||
let note = save_image(&ctx.data_dir, &self.full_name, image_index, image).await;
|
||||
if !text.is_empty() {
|
||||
text.push('\n');
|
||||
}
|
||||
text.push_str(¬e);
|
||||
image_index += 1;
|
||||
}
|
||||
RawContent::Resource(resource) => {
|
||||
let embedded = resource_text(resource);
|
||||
if !embedded.is_empty() {
|
||||
if !text.is_empty() {
|
||||
text.push('\n');
|
||||
}
|
||||
text.push_str(&embedded);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MCP surfaces tool-level failures as `is_error` with the message in `content`; map
|
||||
// that to a tool error so the model sees it as a failed call rather than a result.
|
||||
if result.is_error.unwrap_or(false) {
|
||||
return Err(ToolError::Other(if text.is_empty() {
|
||||
"MCP tool reported an error".to_string()
|
||||
} else {
|
||||
text
|
||||
}));
|
||||
}
|
||||
|
||||
Ok(ToolOutput::new(self.full_name.clone(), text))
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes an image payload to the session data dir and returns a one-line note for the tool
|
||||
/// output. Best-effort: a write failure still yields a note (without a path).
|
||||
async fn save_image(
|
||||
data_dir: &PathBuf,
|
||||
tool_name: &str,
|
||||
index: usize,
|
||||
image: &rmcp::model::RawImageContent,
|
||||
) -> String {
|
||||
let ext = image.mime_type.rsplit('/').next().unwrap_or("bin");
|
||||
let file_name = format!("{tool_name}-image-{index}.{ext}.b64");
|
||||
let path = data_dir.join(&file_name);
|
||||
let saved = tokio::fs::create_dir_all(data_dir).await.is_ok()
|
||||
&& tokio::fs::write(&path, &image.data).await.is_ok();
|
||||
if saved {
|
||||
format!(
|
||||
"[image: {} ({} base64 bytes) saved to {}]",
|
||||
image.mime_type,
|
||||
image.data.len(),
|
||||
path.display()
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
"[image: {} ({} base64 bytes, not saved)]",
|
||||
image.mime_type,
|
||||
image.data.len()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Best-effort text extraction from an embedded resource (text resources only in v1).
|
||||
fn resource_text(resource: &rmcp::model::RawEmbeddedResource) -> String {
|
||||
match &resource.resource {
|
||||
rmcp::model::ResourceContents::TextResourceContents { text, .. } => text.clone(),
|
||||
_ => String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn qualified_name_prefixes_and_sanitizes() {
|
||||
assert_eq!(qualified_name("fs", "read_file"), "fs_read_file");
|
||||
assert_eq!(qualified_name("my.server", "do/thing"), "my_server_do_thing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qualified_name_caps_length() {
|
||||
let long_tool = "t".repeat(100);
|
||||
let name = qualified_name("srv", &long_tool);
|
||||
assert_eq!(name.len(), MAX_NAME_LEN);
|
||||
assert!(name.starts_with("srv_t"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
//! End-to-end MCP integration test: spawn a real stdio MCP server (a small Python fixture),
|
||||
//! connect through the real rmcp client, and verify a discovered tool is callable and gated
|
||||
//! behind the `mcp` permission key. This is the M5 milestone's ✅ for MCP.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use harness_core::event::{AppEvent, EventBus};
|
||||
use harness_core::permission::{PermissionReply, PermissionService};
|
||||
use harness_core::tool::{MetadataSink, PermissionHandle, ToolCtx, ToolError};
|
||||
use harness_core::types::{MessageId, SessionId};
|
||||
use harness_mcp::{connect_all, ServerConfig};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
/// A permission frontend that replies `Once` to every ask and records the `permission`/`pattern`
|
||||
/// of each, so a test can assert the call was actually gated.
|
||||
fn recording_auto_approve(
|
||||
bus: EventBus,
|
||||
service: Arc<PermissionService>,
|
||||
) -> Arc<Mutex<Vec<(String, String)>>> {
|
||||
let asks = Arc::new(Mutex::new(Vec::new()));
|
||||
let asks_task = asks.clone();
|
||||
// Subscribe before spawning: a subscription created inside the task could miss the ask
|
||||
// (tokio broadcast only delivers to receivers that exist at publish time).
|
||||
let mut rx = bus.subscribe();
|
||||
tokio::spawn(async move {
|
||||
while let Ok(event) = rx.recv().await {
|
||||
if let AppEvent::PermissionAsked { request } = event {
|
||||
asks_task
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push((request.permission.clone(), request.pattern.clone()));
|
||||
service.reply(&request.id, PermissionReply::Once);
|
||||
}
|
||||
}
|
||||
});
|
||||
asks
|
||||
}
|
||||
|
||||
struct Harness {
|
||||
ctx_data_dir: std::path::PathBuf,
|
||||
service: Arc<PermissionService>,
|
||||
}
|
||||
|
||||
impl Harness {
|
||||
fn ctx(&self) -> ToolCtx {
|
||||
let (metadata, _rx) = MetadataSink::channel();
|
||||
ToolCtx {
|
||||
session_id: SessionId::new(),
|
||||
message_id: MessageId::new(),
|
||||
call_id: "call_1".into(),
|
||||
data_dir: self.ctx_data_dir.clone(),
|
||||
cwd: std::env::temp_dir(),
|
||||
cancel: CancellationToken::new(),
|
||||
ask: PermissionHandle::new(
|
||||
self.service.clone(),
|
||||
SessionId::new(),
|
||||
Vec::new(),
|
||||
Arc::new(Mutex::new(Vec::new())),
|
||||
CancellationToken::new(),
|
||||
),
|
||||
metadata,
|
||||
spawner: None,
|
||||
context_reporter: None,
|
||||
diagnostics: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn fixture_server() -> HashMap<String, ServerConfig> {
|
||||
let script = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/echo_server.py");
|
||||
HashMap::from([(
|
||||
"fix".to_string(),
|
||||
ServerConfig {
|
||||
command: "python3".to_string(),
|
||||
args: vec![script.to_string()],
|
||||
env: HashMap::new(),
|
||||
},
|
||||
)])
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn discovers_and_calls_a_real_mcp_tool_with_permission() {
|
||||
let tools = connect_all(fixture_server()).await;
|
||||
let names: Vec<_> = tools.iter().map(|t| t.name().to_string()).collect();
|
||||
assert!(
|
||||
names.contains(&"fix_echo".to_string()),
|
||||
"expected fix_echo among {names:?}"
|
||||
);
|
||||
assert!(names.contains(&"fix_boom".to_string()));
|
||||
|
||||
let echo = tools.iter().find(|t| t.name() == "fix_echo").unwrap();
|
||||
// Schema passes through untouched from the server.
|
||||
assert_eq!(echo.parameters()["properties"]["text"]["type"], "string");
|
||||
|
||||
let bus = EventBus::new();
|
||||
let service = Arc::new(PermissionService::new(bus.clone()));
|
||||
let asks = recording_auto_approve(bus, service.clone());
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let harness = Harness {
|
||||
ctx_data_dir: dir.path().to_path_buf(),
|
||||
service,
|
||||
};
|
||||
|
||||
let out = echo
|
||||
.execute(serde_json::json!({"text": "hi there"}), harness.ctx())
|
||||
.await
|
||||
.expect("echo call succeeds");
|
||||
assert_eq!(out.output, "hi there");
|
||||
|
||||
// The call was gated on the `mcp` key with the qualified tool name as the pattern.
|
||||
let recorded = asks.lock().unwrap().clone();
|
||||
assert_eq!(recorded, vec![("mcp".to_string(), "fix_echo".to_string())]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn tool_error_result_maps_to_tool_error() {
|
||||
let tools = connect_all(fixture_server()).await;
|
||||
let boom = tools.iter().find(|t| t.name() == "fix_boom").unwrap();
|
||||
|
||||
let bus = EventBus::new();
|
||||
let service = Arc::new(PermissionService::new(bus.clone()));
|
||||
let _asks = recording_auto_approve(bus, service.clone());
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let harness = Harness {
|
||||
ctx_data_dir: dir.path().to_path_buf(),
|
||||
service,
|
||||
};
|
||||
|
||||
let err = boom
|
||||
.execute(serde_json::json!({}), harness.ctx())
|
||||
.await
|
||||
.expect_err("boom reports an error result");
|
||||
match err {
|
||||
ToolError::Other(msg) => assert_eq!(msg, "kaboom"),
|
||||
other => panic!("expected ToolError::Other, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_failed_server_is_skipped_not_fatal() {
|
||||
let servers = HashMap::from([(
|
||||
"broken".to_string(),
|
||||
ServerConfig {
|
||||
command: "definitely-not-a-real-binary-xyz".to_string(),
|
||||
args: vec![],
|
||||
env: HashMap::new(),
|
||||
},
|
||||
)]);
|
||||
// No panic, no tools — the missing server is logged and skipped.
|
||||
let tools = connect_all(servers).await;
|
||||
assert!(tools.is_empty());
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Minimal MCP stdio server fixture for harness-mcp integration tests.
|
||||
|
||||
Speaks newline-delimited JSON-RPC (the framing rmcp's child-process transport uses) and
|
||||
implements just enough of the protocol to be discovered and called: `initialize`,
|
||||
`notifications/initialized`, `tools/list`, and `tools/call`. Exposes one tool, `echo`,
|
||||
which returns its `text` argument, plus `boom`, which returns an error result.
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
|
||||
PROTOCOL_VERSION = "2024-11-05"
|
||||
|
||||
TOOLS = [
|
||||
{
|
||||
"name": "echo",
|
||||
"description": "Returns the text it is given.",
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {"text": {"type": "string"}},
|
||||
"required": ["text"],
|
||||
},
|
||||
},
|
||||
{
|
||||
"name": "boom",
|
||||
"description": "Always fails.",
|
||||
"inputSchema": {"type": "object", "properties": {}},
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def reply(msg_id, result):
|
||||
sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": msg_id, "result": result}) + "\n")
|
||||
sys.stdout.flush()
|
||||
|
||||
|
||||
def main():
|
||||
# readline() rather than `for line in sys.stdin`: the latter's read-ahead buffer blocks
|
||||
# until it fills, which would stall the JSON-RPC handshake line-by-line.
|
||||
while True:
|
||||
line = sys.stdin.readline()
|
||||
if line == "": # EOF: parent closed stdin
|
||||
break
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
msg = json.loads(line)
|
||||
method = msg.get("method")
|
||||
msg_id = msg.get("id")
|
||||
|
||||
if method == "initialize":
|
||||
reply(msg_id, {
|
||||
"protocolVersion": PROTOCOL_VERSION,
|
||||
"capabilities": {"tools": {}},
|
||||
"serverInfo": {"name": "echo-fixture", "version": "0.1.0"},
|
||||
})
|
||||
elif method == "notifications/initialized":
|
||||
pass # notification: no response
|
||||
elif method == "tools/list":
|
||||
reply(msg_id, {"tools": TOOLS})
|
||||
elif method == "tools/call":
|
||||
params = msg.get("params") or {}
|
||||
name = params.get("name")
|
||||
args = params.get("arguments") or {}
|
||||
if name == "echo":
|
||||
reply(msg_id, {
|
||||
"content": [{"type": "text", "text": args.get("text", "")}],
|
||||
"isError": False,
|
||||
})
|
||||
elif name == "boom":
|
||||
reply(msg_id, {
|
||||
"content": [{"type": "text", "text": "kaboom"}],
|
||||
"isError": True,
|
||||
})
|
||||
else:
|
||||
reply(msg_id, {
|
||||
"content": [{"type": "text", "text": f"unknown tool {name}"}],
|
||||
"isError": True,
|
||||
})
|
||||
elif msg_id is not None:
|
||||
# Unknown request: empty result keeps the client happy.
|
||||
reply(msg_id, {})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -31,7 +31,7 @@ pub struct App {
|
||||
|
||||
impl App {
|
||||
pub async fn new(cwd: PathBuf) -> anyhow::Result<Self> {
|
||||
let engine = EngineHandle::init(cwd)?;
|
||||
let engine = EngineHandle::init(cwd).await?;
|
||||
let bus_rx = engine.bus().subscribe();
|
||||
|
||||
let config = engine.config();
|
||||
|
||||
@@ -50,7 +50,7 @@ async fn run_headless(args: &[String]) -> i32 {
|
||||
}
|
||||
};
|
||||
|
||||
let app = match harness_app::App::init(cwd) {
|
||||
let app = match harness_app::App::init(cwd).await {
|
||||
Ok(app) => app,
|
||||
Err(e) => {
|
||||
eprintln!("error: {e}");
|
||||
|
||||
Reference in New Issue
Block a user