Merge pull request 'mcp: connect in background, never block startup' (#146) from mcp-async into main

This commit was merged in pull request #146.
This commit is contained in:
hermes committed 2026-10-10 22:17:41 +00:00
commit 8b5d24436f
4 files changed
+336 -132

No files matched your search

+21 -23
View File
@@ -210,16 +210,15 @@ fn command_specs(
Source::Builtin,
ArgKind::None,
));
for (n, s) in &mcp.servers {
v.extend(s.prompts.iter().map(|p| {
CmdSpec::new(
&format!("{n}:{}", p["name"].as_str().unwrap_or_default()),
p["description"].as_str().unwrap_or_default(),
Source::Mcp,
ArgKind::Free,
)
}));
}
// servers still connecting have no prompts yet; `/mcp` shows them, typed `/server:prompt` still resolves
v.extend(mcp.prompts().iter().map(|(n, p)| {
CmdSpec::new(
&format!("{n}:{}", p["name"].as_str().unwrap_or_default()),
p["description"].as_str().unwrap_or_default(),
Source::Mcp,
ArgKind::Free,
)
}));
let sk = c::skill_specs(&context::skills(&context::hx_home(), cwd), &v);
v.extend(sk);
v
@@ -580,7 +579,7 @@ async fn main() -> Result<()> {
}
// MCP servers connect while the model catalog loads
let mcp_cfg = hx_mcp::config::load(&context::hx_home(), &cwd).map_err(anyhow::Error::msg)?;
let mcp_task = tokio::spawn(hx_mcp::Hub::start(mcp_cfg));
let mcp = hx_mcp::Hub::spawn(mcp_cfg);
let kinds = logged_in();
let last_path = context::hx_home().join("last.json");
let remember = cfg.remember_model != Some(false);
@@ -670,7 +669,8 @@ async fn main() -> Result<()> {
.unwrap_or(context::DEFAULT_PROMPT)
));
trace("prompt");
let mcp = Arc::new(mcp_task.await?);
// short grace so fast servers land in the (cache-stable) startup prompt; slow ones connect in the background
mcp.wait_all(std::time::Duration::from_secs(1)).await;
trace("mcp");
mcp.register(&mut agent.tools);
let idx = mcp.system_prompt();
@@ -678,7 +678,7 @@ async fn main() -> Result<()> {
agent.append_system(&idx);
}
for (n, s) in &mcp.servers {
if let Some(e) = &s.error {
if let Some(e) = &s.st().error {
eprintln!("[mcp] {n}: {e}");
}
}
@@ -828,7 +828,7 @@ async fn main() -> Result<()> {
mcp: mcp
.servers
.iter()
.map(|(n, s)| (n.clone(), s.error.is_none()))
.map(|(n, s)| (n.clone(), s.st().error.is_none()))
.collect(),
mouse: cfg.mouse.unwrap_or(true)
&& std::env::var_os("HX_MOUSE").is_none_or(|v| v != "0"),
@@ -839,15 +839,13 @@ async fn main() -> Result<()> {
if name == "mcp" {
return Some(Box::pin(async move {
let mut v = mcp.status();
for (n, s) in &mcp.servers {
v.extend(s.prompts.iter().map(|p| {
format!(
" /{n}:{} {}",
p["name"].as_str().unwrap_or_default(),
p["description"].as_str().unwrap_or_default()
)
}));
}
v.extend(mcp.prompts().iter().map(|(n, p)| {
format!(
" /{n}:{} {}",
p["name"].as_str().unwrap_or_default(),
p["description"].as_str().unwrap_or_default()
)
}));
Ok(hx_tui::CmdOut::Show(if v.is_empty() {
"mcp: no servers configured (~/.hx/mcp.json, .hx/mcp.json)".into()
} else {
+272 -96
View File
@@ -17,8 +17,9 @@ use hx_core::tool::{Tool, ToolCtx, ToolResult};
use serde_json::{Value, json};
use std::collections::BTreeMap;
use std::sync::Arc;
use std::sync::RwLock;
use std::time::Duration;
use tokio::sync::Mutex;
use tokio::sync::{Mutex, watch};
/// Servers whose full tool schemas cost at most this many tokens are registered eagerly: below this the
/// saved prompt tokens don't pay for the extra `mcp_describe` round trip. See README "MCP" for the numbers.
@@ -28,10 +29,10 @@ pub const OUTPUT_CAP: usize = 30_000;
const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
const MAX_RESTARTS: u32 = 3;
pub struct Slot {
pub cfg: Server,
client: Mutex<Option<Arc<Client>>>,
restarts: std::sync::atomic::AtomicU32,
/// Cached server data; filled by the connect task. `pending` until that task finished.
#[derive(Default)]
pub struct State {
pub pending: bool,
pub tools: Vec<Value>,
pub prompts: Vec<Value>,
pub resources: Vec<Value>,
@@ -39,79 +40,180 @@ pub struct Slot {
pub error: Option<String>,
}
#[derive(Default)]
pub struct Slot {
pub cfg: Server,
client: Mutex<Option<Arc<Client>>>,
restarts: std::sync::atomic::AtomicU32,
state: RwLock<State>,
}
impl Slot {
fn new(cfg: Server, pending: bool) -> Self {
Slot {
cfg,
client: Mutex::new(None),
restarts: Default::default(),
state: RwLock::new(State {
pending,
..Default::default()
}),
}
}
/// Read guard; never hold across an `.await`.
pub fn st(&self) -> std::sync::RwLockReadGuard<'_, State> {
self.state.read().unwrap_or_else(|e| e.into_inner())
}
}
pub struct Hub {
pub servers: BTreeMap<String, Slot>,
/// bumped whenever a server finishes connecting
done: watch::Sender<u64>,
}
impl Default for Hub {
fn default() -> Self {
Hub {
servers: BTreeMap::new(),
done: watch::channel(0).0,
}
}
}
fn timeout_of(s: &Server) -> Duration {
Duration::from_secs(s.timeout_secs.unwrap_or(60))
}
/// Connect and list tools/prompts/resources. Returns the live client on success.
async fn load(cfg: &Server) -> (State, Option<Arc<Client>>) {
let mut st = State::default();
match Client::connect(cfg, CONNECT_TIMEOUT).await {
Ok(c) => {
// startup listing must not stall a server for the full tool-call timeout
let t = CONNECT_TIMEOUT;
let caps = c.capabilities.clone();
let (tools, prompts, resources) = tokio::join!(
c.list("tools/list", "tools", t),
async {
if caps.get("prompts").is_some() {
c.list("prompts/list", "prompts", t).await
} else {
Ok(vec![])
}
},
async {
if caps.get("resources").is_some() {
c.list("resources/list", "resources", t).await
} else {
Ok(vec![])
}
}
);
match tools {
Ok(v) => {
st.tools = v
.into_iter()
.filter(|x| {
cfg.allow.is_empty()
|| x["name"]
.as_str()
.is_some_and(|n| cfg.allow.iter().any(|a| a == n))
})
.collect()
}
Err(e) => st.error = Some(format!("tools/list: {e}")),
}
st.prompts = prompts.unwrap_or_default();
st.resources = resources.unwrap_or_default();
st.instructions = c.instructions.clone();
(st, Some(Arc::new(c)))
}
Err(e) => {
st.error = Some(e);
(st, None)
}
}
}
impl Hub {
/// Connect to all servers in parallel and cache their tool/prompt/resource lists.
/// Connect to all servers in parallel and wait for every one (CLI commands, tests).
pub async fn start(cfgs: BTreeMap<String, Server>) -> Self {
let slots = futures::future::join_all(cfgs.into_iter().map(|(name, cfg)| async move {
let mut slot = Slot {
cfg,
client: Mutex::new(None),
restarts: Default::default(),
tools: vec![],
prompts: vec![],
resources: vec![],
instructions: None,
error: None,
};
match Client::connect(&slot.cfg, CONNECT_TIMEOUT).await {
Ok(c) => {
let t = timeout_of(&slot.cfg);
let caps = c.capabilities.clone();
let (tools, prompts, resources) = tokio::join!(
c.list("tools/list", "tools", t),
async {
if caps.get("prompts").is_some() {
c.list("prompts/list", "prompts", t).await
} else {
Ok(vec![])
}
},
async {
if caps.get("resources").is_some() {
c.list("resources/list", "resources", t).await
} else {
Ok(vec![])
}
}
);
match tools {
Ok(v) => {
slot.tools = v
.into_iter()
.filter(|x| {
slot.cfg.allow.is_empty()
|| x["name"]
.as_str()
.is_some_and(|n| slot.cfg.allow.iter().any(|a| a == n))
})
.collect()
}
Err(e) => slot.error = Some(format!("tools/list: {e}")),
}
slot.prompts = prompts.unwrap_or_default();
slot.resources = resources.unwrap_or_default();
slot.instructions = c.instructions.clone();
*slot.client.get_mut() = Some(Arc::new(c));
}
Err(e) => slot.error = Some(e),
}
let (st, c) = load(&cfg).await;
let slot = Slot::new(cfg, false);
*slot.state.write().unwrap_or_else(|e| e.into_inner()) = st;
*slot.client.lock().await = c;
(name, slot)
}))
.await;
Self {
servers: slots.into_iter().collect(),
..Default::default()
}
}
/// Return at once; each server connects in its own task. Slots stay `pending` until done.
pub fn spawn(cfgs: BTreeMap<String, Server>) -> Arc<Self> {
let hub = Arc::new(Self {
servers: cfgs
.into_iter()
.map(|(n, c)| (n, Slot::new(c, true)))
.collect(),
..Default::default()
});
let names: Vec<String> = hub.servers.keys().cloned().collect();
for name in names {
let hub = hub.clone();
tokio::spawn(async move {
let slot = &hub.servers[&name];
let (mut st, c) = load(&slot.cfg).await;
st.pending = false;
*slot.client.lock().await = c;
*slot.state.write().unwrap_or_else(|e| e.into_inner()) = st;
hub.done.send_modify(|v| *v += 1);
});
}
hub
}
pub fn pending(&self) -> Vec<String> {
self.servers
.iter()
.filter(|(_, s)| s.st().pending)
.map(|(n, _)| n.clone())
.collect()
}
/// Wait until no server is pending, or `d` passed.
pub async fn wait_all(&self, d: Duration) {
let mut rx = self.done.subscribe();
let _ = tokio::time::timeout(d, async {
while !self.pending().is_empty() {
if rx.changed().await.is_err() {
break;
}
}
})
.await;
}
/// Wait until `server` finished connecting (bounded by connect + list timeouts).
async fn settled(&self, server: &str) {
let Some(s) = self.servers.get(server) else {
return;
};
let mut rx = self.done.subscribe();
let d = CONNECT_TIMEOUT + timeout_of(&s.cfg) + Duration::from_secs(1);
let _ = tokio::time::timeout(d, async {
while s.st().pending {
if rx.changed().await.is_err() {
break;
}
}
})
.await;
}
/// Live client for `server`, reconnecting (bounded) if the process died.
async fn client(&self, server: &str) -> Result<(Arc<Client>, &Slot), String> {
let slot = self
@@ -135,26 +237,35 @@ impl Hub {
Ok((c, slot))
}
pub fn tool(&self, server: &str, tool: &str) -> Option<&Value> {
pub fn tool(&self, server: &str, tool: &str) -> Option<Value> {
self.servers
.get(server)?
.st()
.tools
.iter()
.find(|t| t["name"] == tool)
.cloned()
}
pub fn is_eager(&self, server: &str) -> bool {
self.servers.get(server).is_some_and(|s| {
let st = s.st();
s.cfg
.eager
.unwrap_or(spec_tokens(&s.tools) <= EAGER_MAX_TOKENS)
&& !s.tools.is_empty()
.unwrap_or(spec_tokens(&st.tools) <= EAGER_MAX_TOKENS)
&& !st.tools.is_empty()
})
}
/// Validate against the cached schema, call, and flatten the result for the model.
pub async fn call(&self, server: &str, tool: &str, args: Value) -> ToolResult {
self.settled(server).await;
let Some(spec) = self.tool(server, tool) else {
if self.servers.get(server).is_some_and(|s| s.st().pending) {
return ToolResult::err(format!(
"MCP server `{server}` is still connecting; retry shortly"
));
}
return ToolResult::err(format!(
"unknown tool `{server}.{tool}` (not listed or not allowed); see the MCP index"
));
@@ -188,6 +299,7 @@ impl Hub {
}
pub async fn read(&self, server: &str, uri: &str) -> ToolResult {
self.settled(server).await;
let (c, slot) = match self.client(server).await {
Ok(x) => x,
Err(e) => return ToolResult::err(e),
@@ -217,11 +329,14 @@ impl Hub {
/// Expand prompt `server:name` with `args` (`key=value` pairs or one free-text value for the first
/// argument) into user text.
pub async fn prompt(&self, server: &str, name: &str, args: &str) -> Result<String, String> {
self.settled(server).await;
let (c, slot) = self.client(server).await?;
let p = slot
.st()
.prompts
.iter()
.find(|p| p["name"] == name)
.cloned()
.ok_or_else(|| format!("unknown prompt {server}:{name}"))?;
let names: Vec<&str> = p["arguments"]
.as_array()
@@ -255,24 +370,27 @@ impl Hub {
.join("\n\n"))
}
/// Index block for one ready lazy-or-eager server.
fn index_of(n: &str, st: &State) -> String {
let mut out = String::new();
for t in &st.tools {
let d = t["description"].as_str().unwrap_or_default();
let d = d.lines().next().unwrap_or_default();
let d: String = d.chars().take(100).collect();
out.push_str(&format!(
"- {n}.{}: {d}\n",
t["name"].as_str().unwrap_or_default()
));
}
out
}
/// Per-server index blocks for the system prompt: (server, text). Eager servers are omitted.
pub fn index(&self) -> Vec<(String, String)> {
self.servers
.iter()
.filter(|(n, s)| !s.tools.is_empty() && !self.is_eager(n))
.map(|(n, s)| {
let mut out = String::new();
for t in &s.tools {
let d = t["description"].as_str().unwrap_or_default();
let d = d.lines().next().unwrap_or_default();
let d: String = d.chars().take(100).collect();
out.push_str(&format!(
"- {n}.{}: {d}\n",
t["name"].as_str().unwrap_or_default()
));
}
(n.clone(), out)
})
.filter(|(n, s)| !s.st().tools.is_empty() && !self.is_eager(n))
.map(|(n, s)| (n.clone(), Self::index_of(n, &s.st())))
.collect()
}
@@ -285,17 +403,29 @@ impl Hub {
s.push_str(&b);
}
}
let pend = self.pending();
if !pend.is_empty() {
s.push_str(&format!(
"\n# MCP servers still connecting: {}\nCall `mcp_describe` with just `server` to list a server's tools once ready; `mcp_call` works as soon as it is.\n",
pend.join(", ")
));
}
let res: Vec<String> = self
.servers
.iter()
.flat_map(|(n, s)| {
s.resources.iter().take(20).map(move |r| {
format!(
"- {n}: {} ({})",
r["uri"].as_str().unwrap_or_default(),
r["name"].as_str().unwrap_or_default()
)
})
s.st()
.resources
.iter()
.take(20)
.map(|r| {
format!(
"- {n}: {} ({})",
r["uri"].as_str().unwrap_or_default(),
r["name"].as_str().unwrap_or_default()
)
})
.collect::<Vec<_>>()
})
.collect();
if !res.is_empty() {
@@ -304,7 +434,12 @@ impl Hub {
s.push('\n');
}
for (n, sl) in &self.servers {
if let Some(i) = sl.instructions.as_deref().filter(|i| !i.trim().is_empty()) {
if let Some(i) = sl
.st()
.instructions
.as_deref()
.filter(|i| !i.trim().is_empty())
{
let i: String = i.chars().take(1500).collect();
s.push_str(&format!(
"\n# MCP server `{n}` instructions\n{}\n",
@@ -321,7 +456,11 @@ impl Hub {
self.servers
.iter()
.map(|(n, s)| {
if let Some(e) = &s.error {
let st = s.st();
if st.pending {
return format!("{n}: connecting…");
}
if let Some(e) = &st.error {
let auth = if s.cfg.url.is_some() && e.contains("HTTP 401") && !oauth::logged_in(&s.cfg) {
format!(" (run `hx mcp login {n}`)")
} else {
@@ -329,25 +468,42 @@ impl Hub {
};
return format!("{n}: error: {e}{auth}");
}
let eager_tok = spec_tokens(&s.tools);
let eager_tok = spec_tokens(&st.tools);
let idx_tok = idx.get(n).map_or(0, |b| b.len() / 4);
format!(
"{n}: {} tools, {} prompts, {} resources; {} (index ~{idx_tok} tok, eager schemas ~{eager_tok} tok)",
s.tools.len(),
s.prompts.len(),
s.resources.len(),
st.tools.len(),
st.prompts.len(),
st.resources.len(),
if self.is_eager(n) { "eager" } else { "lazy" }
)
})
.collect()
}
/// Prompts of ready servers: (server, prompt json).
pub fn prompts(&self) -> Vec<(String, Value)> {
self.servers
.iter()
.flat_map(|(n, s)| {
s.st()
.prompts
.iter()
.map(|p| (n.clone(), p.clone()))
.collect::<Vec<_>>()
})
.collect()
}
/// Register agent tools: eager native tools, plus mcp_describe/mcp_call/mcp_read when needed.
pub fn register(self: &Arc<Self>, reg: &mut hx_core::tool::Registry) {
let mut lazy = false;
for (n, s) in &self.servers {
if self.is_eager(n) {
for t in &s.tools {
let st = s.st();
if st.pending {
lazy = true; // late servers are reached through mcp_describe/mcp_call
} else if self.is_eager(n) {
for t in &st.tools {
reg.add(Native {
hub: self.clone(),
server: n.clone(),
@@ -359,7 +515,7 @@ impl Hub {
},
});
}
} else if !s.tools.is_empty() {
} else if !st.tools.is_empty() {
lazy = true;
}
}
@@ -367,7 +523,11 @@ impl Hub {
reg.add(Describe { hub: self.clone() });
reg.add(Call { hub: self.clone() });
}
if self.servers.values().any(|s| !s.resources.is_empty()) {
// resources may appear late too
if self.servers.values().any(|s| {
let st = s.st();
st.pending || !st.resources.is_empty()
}) {
reg.add(Read { hub: self.clone() });
}
}
@@ -468,9 +628,8 @@ impl Tool for Describe {
fn spec(&self) -> ToolSpec {
ToolSpec {
name: "mcp_describe".into(),
description: "Full description and argument schema of an MCP tool from the MCP index."
.into(),
input_schema: json!({"type":"object","properties":{"server":{"type":"string"},"tool":{"type":"string"}},"required":["server","tool"]}),
description: "Full description and argument schema of an MCP tool from the MCP index. Without `tool`: list that server's tools (use for servers still connecting).".into(),
input_schema: json!({"type":"object","properties":{"server":{"type":"string"},"tool":{"type":"string"}},"required":["server"]}),
}
}
async fn call(&self, a: Value, _: &ToolCtx) -> ToolResult {
@@ -478,10 +637,27 @@ impl Tool for Describe {
a["server"].as_str().unwrap_or_default(),
a["tool"].as_str().unwrap_or_default(),
);
self.hub.settled(s).await;
let Some(slot) = self.hub.servers.get(s) else {
return ToolResult::err(format!("unknown MCP server `{s}`"));
};
if t.is_empty() {
let st = slot.st();
return match (&st.error, st.pending) {
(_, true) => ToolResult::err(format!(
"MCP server `{s}` is still connecting; retry shortly"
)),
(Some(e), _) => ToolResult::err(format!("MCP server `{s}` failed: {e}")),
_ => ToolResult::ok(Hub::index_of(s, &st)),
};
}
match self.hub.tool(s, t) {
Some(x) => ToolResult::ok(
json!({"description": x["description"], "arguments": x["inputSchema"]}).to_string(),
),
None if slot.st().pending => ToolResult::err(format!(
"MCP server `{s}` is still connecting; retry shortly"
)),
None => ToolResult::err(format!("unknown tool `{s}.{t}`")),
}
}
+41 -12
View File
@@ -30,8 +30,8 @@ fn cx() -> ToolCtx {
async fn stdio_lazy_index_describe_call() {
let h = hub(r#","eager":false"#).await;
let s = &h.servers["f"];
assert_eq!(s.error, None);
assert_eq!(s.tools.len(), 5, "pagination followed");
assert_eq!(s.st().error, None);
assert_eq!(s.st().tools.len(), 5, "pagination followed");
assert!(!h.is_eager("f"));
let sp = h.system_prompt();
assert!(sp.contains("- f.echo: Echo a message back\n"), "{sp}");
@@ -92,7 +92,7 @@ async fn stdio_lazy_index_describe_call() {
#[tokio::test]
async fn eager_and_allowlist() {
// small schemas -> native tools, no mcp_call
assert!(spec_tokens(&hub("").await.servers["f"].tools) <= EAGER_MAX_TOKENS);
assert!(spec_tokens(&hub("").await.servers["f"].st().tools) <= EAGER_MAX_TOKENS);
let h = hub(r#","allow":["echo","add"]"#).await;
assert!(h.is_eager("f"));
let mut reg = hx_core::tool::Registry::default();
@@ -157,13 +157,13 @@ async fn http_transport() {
let mut h = Hub::default();
for _ in 0..50 {
h = Hub::start(BTreeMap::from([("w".to_string(), cfg.clone())])).await;
if h.servers["w"].error.is_none() {
if h.servers["w"].st().error.is_none() {
break;
}
tokio::time::sleep(Duration::from_millis(100)).await;
}
assert_eq!(h.servers["w"].error, None);
assert_eq!(h.servers["w"].tools.len(), 5);
assert_eq!(h.servers["w"].st().error, None);
assert_eq!(h.servers["w"].st().tools.len(), 5);
assert_eq!(
h.call("w", "echo", json!({"message":"sse"})).await,
ToolResult::ok("echo: sse")
@@ -175,12 +175,13 @@ async fn http_transport() {
let h = Hub::start(BTreeMap::from([("w".to_string(), bad)])).await;
assert!(
h.servers["w"]
.st()
.error
.as_deref()
.unwrap_or("")
.contains("401"),
"{:?}",
h.servers["w"].error
h.servers["w"].st().error
);
let _ = srv.kill().await;
}
@@ -207,7 +208,7 @@ async fn reference_server_everything() {
}))
.unwrap();
let h = Hub::start(BTreeMap::from([("e".to_string(), cfg)])).await;
assert_eq!(h.servers["e"].error, None);
assert_eq!(h.servers["e"].st().error, None);
assert!(h.tool("e", "echo").is_some() && h.tool("e", "get-sum").is_some());
assert_eq!(
h.call("e", "echo", json!({"message":"ref"})).await,
@@ -219,14 +220,14 @@ async fn reference_server_everything() {
.content
.contains('5')
);
assert!(!h.servers["e"].prompts.is_empty() && !h.servers["e"].resources.is_empty());
assert!(!h.servers["e"].st().prompts.is_empty() && !h.servers["e"].st().resources.is_empty());
assert!(
h.prompt("e", "simple-prompt", "")
.await
.unwrap()
.contains("simple prompt")
);
let uri = h.servers["e"].resources[0]["uri"]
let uri = h.servers["e"].st().resources[0]["uri"]
.as_str()
.unwrap()
.to_string();
@@ -254,6 +255,7 @@ async fn http_oauth_login_and_refresh() {
h = start().await;
// server up once the error is the 401 (not a connection error)
if h.servers["o"]
.st()
.error
.as_deref()
.is_some_and(|e| e.contains("401"))
@@ -293,8 +295,8 @@ async fn http_oauth_login_and_refresh() {
}
// a1 is rejected by the server -> 401 -> forced refresh -> a2
let h = start().await;
assert_eq!(h.servers["o"].error, None);
assert_eq!(h.servers["o"].tools.len(), 5);
assert_eq!(h.servers["o"].st().error, None);
assert_eq!(h.servers["o"].st().tools.len(), 5);
assert_eq!(
h.call("o", "echo", json!({"message":"auth"})).await,
ToolResult::ok("echo: auth")
@@ -303,3 +305,30 @@ async fn http_oauth_login_and_refresh() {
assert!(!oauth::logged_in(&cfg));
let _ = srv.kill().await;
}
#[tokio::test]
async fn spawn_does_not_block_on_slow_server() {
let slow = stdio(r#","env":{"FAKE_INIT_DELAY":"2"}"#);
let t0 = std::time::Instant::now();
let h = Hub::spawn(BTreeMap::from([
("fast".to_string(), stdio("")),
("slow".to_string(), slow),
]));
assert!(t0.elapsed() < Duration::from_millis(200), "spawn blocked");
assert_eq!(h.pending().len(), 2);
// pending: status says connecting, describe/call wait for the slot instead of failing
assert!(h.status().iter().all(|l| l.contains("connecting")));
let r = h.call("fast", "echo", json!({"message":"hi"})).await;
assert_eq!(r, ToolResult::ok("echo: hi"));
assert_eq!(
h.pending(),
vec!["slow".to_string()],
"fast ready, slow still pending"
);
assert!(h.system_prompt().contains("still connecting: slow"));
h.wait_all(Duration::from_secs(10)).await;
assert!(h.pending().is_empty());
assert_eq!(h.servers["slow"].st().tools.len(), 5);
let r = h.call("slow", "echo", json!({"message":"late"})).await;
assert_eq!(r, ToolResult::ok("echo: late"));
}
+2 -1
View File
@@ -1,7 +1,7 @@
"""Tiny MCP server for tests. stdio (default) or streamable HTTP: `fake_mcp.py http PORT`.
Tools: echo(message), add(a,b), crash() (exits the process), big() (large output), slow(). One prompt, one resource.
"""
import json, sys, time
import json, os, sys, time
TOOLS = [
{"name": "echo", "description": "Echo a message back\nsecond line ignored in index",
@@ -20,6 +20,7 @@ def handle(m):
return None
r = None
if meth == "initialize":
time.sleep(float(os.environ.get("FAKE_INIT_DELAY", "0")))
r = {"protocolVersion": p.get("protocolVersion"), "serverInfo": {"name": "fake", "version": "1"},
"capabilities": {"tools": {}, "prompts": {}, "resources": {}}, "instructions": "Use echo for tests."}
elif meth == "tools/list":