Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(mcp): bind MCP tool calls to the server connection that listed them
thinhlpg9f52af75a9d9
diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rsindex 204bb9162..d989962bf 100644--- a/src-tauri/src/core/agent/loop.rs+++ b/src-tauri/src/core/agent/loop.rs@@ -734,7 +734,7 @@ impl ModelInvoker for HttpModelInvoker {}struct McpToolInvoker {- tool_to_server: HashMap<String, String>,+ tool_to_server: crate::core::mcp::identity::ToolRoutes,mcp_servers: SharedMcpServers,mcp_settings: Arc<Mutex<McpSettings>>,}@@ -3312,7 +3312,7 @@ fn tool_names(tools: &[serde_json::Value]) -> Vec<String> {fn apply_tool_allowlist(openai_tools: &mut Vec<serde_json::Value>,- tool_to_server: &mut HashMap<String, String>,+ tool_to_server: &mut crate::core::mcp::identity::ToolRoutes,allowed: &[String],) {let allow: std::collections::HashSet<&str> = allowed.iter().map(String::as_str).collect();@@ -3332,7 +3332,7 @@ fn apply_tool_allowlist(/// advertisement; only an explicit deny (or `default = "deny"`) does.fn retain_advertisable_mcp_tools(openai_tools: &mut Vec<serde_json::Value>,- tool_to_server: &mut HashMap<String, String>,+ tool_to_server: &mut crate::core::mcp::identity::ToolRoutes,permissions: &tauri_plugin_agent_tools::permissions::ToolPermissions,) {openai_tools.retain(|t| {@@ -10246,6 +10246,13 @@ mod tests {assert_eq!(stop_reason_of(&json!({})), "stop");}+ fn route(server: &str) -> crate::core::mcp::identity::ToolRoute {+ crate::core::mcp::identity::ToolRoute {+ server: server.to_string(),+ generation: 1,+ }+ }+#[test]fn tool_allowlist_keeps_only_named_tools() {let mut tools = vec![@@ -10253,8 +10260,8 @@ mod tests {json!({ "type": "function", "function": { "name": "write" } }),];let mut map = HashMap::from([- ("search".to_string(), "srv".to_string()),- ("write".to_string(), "srv".to_string()),+ ("search".to_string(), route("srv")),+ ("write".to_string(), route("srv")),]);apply_tool_allowlist(&mut tools, &mut map, &["search".to_string()]);@@ -13425,7 +13432,7 @@ mod tests {#[test]fn tool_allowlist_empty_removes_all() {let mut tools = vec![json!({ "type": "function", "function": { "name": "search" } })];- let mut map = HashMap::from([("search".to_string(), "srv".to_string())]);+ let mut map = HashMap::from([("search".to_string(), route("srv"))]);apply_tool_allowlist(&mut tools, &mut map, &[]);@@ -13438,7 +13445,7 @@ mod tests {use tauri_plugin_agent_tools::permissions::{PermissionDefault, ToolPermissions};let mut tools =vec![json!({ "type": "function", "function": { "name": "web_search_exa" } })];- let mut map = HashMap::from([("web_search_exa".to_string(), "exa".to_string())]);+ let mut map = HashMap::from([("web_search_exa".to_string(), route("exa"))]);// The scaffolded CLI project default: read-only, no allow-list.let perms = ToolPermissions::new(PermissionDefault::ReadOnly, &[], &[], &[]);@@ -13460,8 +13467,8 @@ mod tests {json!({ "type": "function", "function": { "name": "dangerous_write" } }),];let mut map = HashMap::from([- ("web_search_exa".to_string(), "exa".to_string()),- ("dangerous_write".to_string(), "exa".to_string()),+ ("web_search_exa".to_string(), route("exa")),+ ("dangerous_write".to_string(), route("exa")),]);let perms = ToolPermissions::new(PermissionDefault::ReadOnly,@@ -13485,7 +13492,7 @@ mod tests {use tauri_plugin_agent_tools::permissions::{PermissionDefault, ToolPermissions};let mut tools =vec![json!({ "type": "function", "function": { "name": "web_search_exa" } })];- let mut map = HashMap::from([("web_search_exa".to_string(), "exa".to_string())]);+ let mut map = HashMap::from([("web_search_exa".to_string(), route("exa"))]);let perms = ToolPermissions::new(PermissionDefault::Deny, &[], &[], &[]);retain_advertisable_mcp_tools(&mut tools, &mut map, &perms);diff --git a/src-tauri/src/core/agent/prefix_stability.rs b/src-tauri/src/core/agent/prefix_stability.rsindex 1dbee377e..f94a3b8f2 100644--- a/src-tauri/src/core/agent/prefix_stability.rs+++ b/src-tauri/src/core/agent/prefix_stability.rs@@ -551,20 +551,20 @@ fn a_restart_advertises_the_same_tool_bytes() {let fs = || vec![tool("read_file")];let walks = [- vec![("git".to_string(), git()), ("fs".to_string(), fs())],- vec![("fs".to_string(), fs()), ("git".to_string(), git())],+ vec![("git".to_string(), 1, git()), ("fs".to_string(), 2, fs())],+ vec![("fs".to_string(), 2, fs()), ("git".to_string(), 1, git())],vec![- ("git".to_string(), vec![tool("status"), tool("commit")]),- ("fs".to_string(), fs()),+ ("git".to_string(), 1, vec![tool("status"), tool("commit")]),+ ("fs".to_string(), 2, fs()),],vec![- ("fs".to_string(), fs()),- ("git".to_string(), vec![tool("status"), tool("commit")]),+ ("fs".to_string(), 2, fs()),+ ("git".to_string(), 1, vec![tool("status"), tool("commit")]),],];let mut bodies: Vec<String> = Vec::new();- let mut mappings: Vec<HashMap<String, String>> = Vec::new();+ let mut mappings: Vec<crate::core::mcp::identity::ToolRoutes> = Vec::new();for walk in walks {let (tools, mapping) = assemble_tool_array(walk);bodies.push(turn(project.root(), &[], "", &tools).body);@@ -595,12 +595,12 @@ fn a_failed_listing_keeps_the_advertised_tools() {let project = Project::new("listing-failure");let mut cache = HashMap::new();- let listed = vec![("git".to_string(), Some(vec![tool("commit")]))];+ let listed = vec![("git".to_string(), 1, Some(vec![tool("commit")]))];let warm = reuse_last_good_listings(&mut cache, listed);let (warm_tools, _) = assemble_tool_array(warm);let before = turn(project.root(), &[], "", &warm_tools);- let timed_out = reuse_last_good_listings(&mut cache, vec![("git".to_string(), None)]);+ let timed_out = reuse_last_good_listings(&mut cache, vec![("git".to_string(), 1, None)]);let (reused_tools, _) = assemble_tool_array(timed_out);let after = turn(project.root(), &[], "", &reused_tools);@@ -612,7 +612,7 @@ fn a_failed_listing_keeps_the_advertised_tools() {// A server that has never listed successfully has nothing to reuse, so a// first-run failure still omits it rather than advertising a guess.- let never_listed = reuse_last_good_listings(&mut cache, vec![("new".to_string(), None)]);+ let never_listed = reuse_last_good_listings(&mut cache, vec![("new".to_string(), 3, None)]);assert!(never_listed.is_empty());}diff --git a/src-tauri/src/core/agent/upstream.rs b/src-tauri/src/core/agent/upstream.rsindex 5cc6c731f..a03ef5ba7 100644--- a/src-tauri/src/core/agent/upstream.rs+++ b/src-tauri/src/core/agent/upstream.rs@@ -26,6 +26,7 @@ use crate::core::server::proxy::engine_upstream;#[cfg(not(feature = "cli"))]use crate::core::server::MlxBackendSession;use crate::core::{+ mcp::identity::{self, ToolRoute, ToolRoutes},mcp::models::McpSettings,mcp::truncate::truncate_tool_result,state::{ProviderConfig, SharedMcpServers},@@ -891,9 +892,16 @@ pub(crate) fn copy_optional_chat_params(}/// One MCP tool already rendered into the OpenAI `function` shape, paired with-/// the tool name used for ordering and for `tool_to_server` lookup.+/// the tool name used for ordering and for routing lookup.pub(crate) type RenderedTool = (String, serde_json::Value);+/// One server's listing attempt: its name, the connection generation it was+/// made against (see `mcp::identity`), and the tools, `None` when it failed.+pub(crate) type ListingAttempt = (String, u64, Option<Vec<RenderedTool>>);++/// A server's resolved listing: name, the generation the tools came from, tools.+pub(crate) type ServerListing = (String, u64, Vec<RenderedTool>);+/// Ordering key for the advertised tool array: `(server name, tool name)`.////// The tool array is part of the request *prefix*, and providers cache prefixes@@ -907,11 +915,14 @@ fn tool_sort_key<'a>(server_name: &'a str, tool_name: &'a str) -> (&'a str, &'a(server_name, tool_name)}-/// Last successful listing per MCP server, for the lifetime of the process.-fn last_good_listings() -> &'static std::sync::Mutex<HashMap<String, Vec<RenderedTool>>> {- static CACHE: std::sync::OnceLock<std::sync::Mutex<HashMap<String, Vec<RenderedTool>>>> =- std::sync::OnceLock::new();- CACHE.get_or_init(Default::default)+/// Last successful listing per MCP server, with the generation it came from.+pub(crate) type ListingCache = HashMap<String, (u64, Vec<RenderedTool>)>;++/// The [`ListingCache`] for the lifetime of the process.+fn last_good_listings() -> &'static std::sync::Mutex<ListingCache> {+ static CACHE: std::sync::LazyLock<std::sync::Mutex<ListingCache>> =+ std::sync::LazyLock::new(Default::default);+ &CACHE}/// Resolve each server's listing attempt against the last-known-good one.@@ -922,35 +933,39 @@ fn last_good_listings() -> &'static std::sync::Mutex<HashMap<String, Vec<Rendere/// again on the turn the server comes back. A server that has never listed/// successfully is still omitted - there is nothing to reuse.///+/// A reused listing keeps the generation it was listed from, so if the server+/// was replaced in between, calls to those tools are refused instead of being+/// run on a process that never offered them.+////// `listings` is assumed to cover every configured server (every caller probes/// the whole `SharedMcpServers` map and filters afterwards), so a server absent/// from it has been removed and its cached listing is dropped. That keeps the/// cache from growing across a long session, and means removing a server changes/// the array exactly once, at the point of the change.pub(crate) fn reuse_last_good_listings(- cache: &mut HashMap<String, Vec<RenderedTool>>,- listings: Vec<(String, Option<Vec<RenderedTool>>)>,-) -> Vec<(String, Vec<RenderedTool>)> {+ cache: &mut ListingCache,+ listings: Vec<ListingAttempt>,+) -> Vec<ServerListing> {let probed: std::collections::HashSet<String> =- listings.iter().map(|(name, _)| name.clone()).collect();+ listings.iter().map(|(name, _, _)| name.clone()).collect();cache.retain(|name, _| probed.contains(name));let mut resolved = Vec::with_capacity(listings.len());- for (server_name, tools) in listings {+ for (server_name, generation, tools) in listings {match tools {Some(tools) => {- cache.insert(server_name.clone(), tools.clone());- resolved.push((server_name, tools));+ cache.insert(server_name.clone(), (generation, tools.clone()));+ resolved.push((server_name, generation, tools));}None => match cache.get(&server_name) {- Some(tools) => {+ Some((cached_generation, tools)) => {log::warn!("Reusing last known tool listing for MCP server {} ({} tools)",server_name,tools.len());- resolved.push((server_name, tools.clone()));+ resolved.push((server_name, *cached_generation, tools.clone()));}None => {log::warn!(@@ -966,37 +981,49 @@ pub(crate) fn reuse_last_good_listings(}/// Flatten the per-server listings into the advertised array, ordered by-/// [`tool_sort_key`], with `tool_to_server` kept consistent with that order.+/// [`tool_sort_key`], with the routes kept consistent with that order.+///+/// A name no single server can be held to (offered by two servers, or empty)+/// is left out of the array and the routes alike: the model calls tools by+/// bare name, so any route for it would be a guess.pub(crate) fn assemble_tool_array(- listings: Vec<(String, Vec<RenderedTool>)>,-) -> (Vec<serde_json::Value>, HashMap<String, String>) {- let mut flattened: Vec<(String, String, serde_json::Value)> = listings+ listings: Vec<ServerListing>,+) -> (Vec<serde_json::Value>, ToolRoutes) {+ let unroutable =+ identity::unroutable_tool_names(listings.iter().flat_map(|(server_name, _, tools)| {+ tools+ .iter()+ .map(move |(tool_name, _)| (server_name.as_str(), tool_name.as_str()))+ }));++ let mut flattened: Vec<(String, u64, String, serde_json::Value)> = listings.into_iter()- .flat_map(|(server_name, tools)| {+ .flat_map(|(server_name, generation, tools)| {tools.into_iter()- .map(move |(tool_name, tool)| (server_name.clone(), tool_name, tool))+ .map(move |(tool_name, tool)| (server_name.clone(), generation, tool_name, tool))})+ .filter(|(_, _, tool_name, _)| !unroutable.contains(tool_name)).collect();- flattened.sort_by(|(a_server, a_tool, _), (b_server, b_tool, _)| {+ flattened.sort_by(|(a_server, _, a_tool, _), (b_server, _, b_tool, _)| {tool_sort_key(a_server, a_tool).cmp(&tool_sort_key(b_server, b_tool))});let mut openai_tools = Vec::with_capacity(flattened.len());- let mut tool_to_server: HashMap<String, String> = HashMap::new();- for (server_name, tool_name, tool) in flattened {- tool_to_server.insert(tool_name, server_name);+ let mut routes = ToolRoutes::new();+ for (server, generation, tool_name, tool) in flattened {+ routes.insert(tool_name, ToolRoute { server, generation });openai_tools.push(tool);}- (openai_tools, tool_to_server)+ (openai_tools, routes)}pub(crate) async fn collect_mcp_openai_tools(mcp_servers: &SharedMcpServers,mcp_settings: &Arc<Mutex<McpSettings>>,-) -> Result<(Vec<serde_json::Value>, HashMap<String, String>), String> {+) -> Result<(Vec<serde_json::Value>, ToolRoutes), String> {let timeout_duration = mcp_settings.lock().await.tool_call_timeout_duration();let servers = mcp_servers.lock().await;@@ -1005,6 +1032,8 @@ pub(crate) async fn collect_mcp_openai_tools(// the full timeout before the next was contacted).let listings =futures_util::future::join_all(servers.iter().map(|(server_name, service)| async move {+ // Read under the servers lock, which every replacement also holds.+ let generation = identity::current_generation(server_name);let result =match tokio::time::timeout(timeout_duration, service.list_all_tools()).await {Ok(Ok(tools)) => Some(@@ -1051,7 +1080,7 @@ pub(crate) async fn collect_mcp_openai_tools(None}};- (server_name.clone(), result)+ (server_name.clone(), generation, result)})).await;@@ -1067,7 +1096,7 @@ pub(crate) async fn collect_mcp_openai_tools(pub(crate) async fn execute_mcp_tool_calls(tool_calls: &[serde_json::Value],- tool_to_server: &HashMap<String, String>,+ routes: &ToolRoutes,mcp_servers: &SharedMcpServers,mcp_settings: &Arc<Mutex<McpSettings>>,) -> Vec<(String, String)> {@@ -1111,7 +1140,7 @@ pub(crate) async fn execute_mcp_tool_calls(serde_json::Map::new()};- let Some(server_name) = tool_to_server.get(&tool_name) else {+ let Some(route) = routes.get(&tool_name) else {results.push((tool_call_id,format!("ERROR: No MCP server registered for tool '{tool_name}'"),@@ -1119,13 +1148,19 @@ pub(crate) async fn execute_mcp_tool_calls(continue;};- let Some(service) = servers.get(server_name) else {+ // The servers lock is held across this check and the call, and every+ // replacement takes it, so the connection checked is the one called.+ let Some(service) = servers.get(&route.server) else {results.push((tool_call_id,- format!("ERROR: MCP server '{server_name}' is not running"),+ format!("ERROR: MCP server '{}' is not running", route.server),));continue;};+ if let Err(e) = identity::check_generation(&route.server, route.generation) {+ results.push((tool_call_id, format!("ERROR: {e}")));+ continue;+ }let tool_call = service.call_tool(CallToolRequestParams::new(tool_name.clone()).with_arguments(args_map),@@ -2248,12 +2283,20 @@ mod tests {#[test]fn tool_array_is_byte_identical_whatever_order_the_servers_are_walked_in() {let one = vec![- ("fs".to_string(), vec![rendered("write"), rendered("read")]),- ("git".to_string(), vec![rendered("commit")]),+ (+ "fs".to_string(),+ 1,+ vec![rendered("write"), rendered("read")],+ ),+ ("git".to_string(), 2, vec![rendered("commit")]),];let two = vec![- ("git".to_string(), vec![rendered("commit")]),- ("fs".to_string(), vec![rendered("read"), rendered("write")]),+ ("git".to_string(), 2, vec![rendered("commit")]),+ (+ "fs".to_string(),+ 1,+ vec![rendered("read"), rendered("write")],+ ),];let (first, _) = assemble_tool_array(one);@@ -2267,45 +2310,48 @@ mod tests {assert_eq!(advertised_names(&first), ["read", "write", "commit"]);}- /// Two servers exposing the same tool name is a pre-existing collision the- /// array does not dedupe - but which server wins `tool_to_server` used to- /// depend on iteration order, so the same call could route to either one- /// across restarts. Sorting makes it the last server by name, always.+ /// The model calls tools by bare name, so a name two servers offer cannot be+ /// attributed to either: it is left out rather than routed to one of them,+ /// while the servers' other tools stay.#[test]- fn a_tool_name_exposed_by_two_servers_routes_the_same_way_every_run() {- let listings = |flipped: bool| {- let fs = ("fs".to_string(), vec![rendered("search")]);- let zed = ("zed".to_string(), vec![rendered("search")]);- if flipped {- vec![zed, fs]- } else {- vec![fs, zed]- }- };-- let (first, first_map) = assemble_tool_array(listings(false));- let (second, second_map) = assemble_tool_array(listings(true));+ fn a_tool_name_exposed_by_two_servers_is_not_offered_or_routed() {+ let (tools, routes) = assemble_tool_array(vec![+ (+ "fs".to_string(),+ 1,+ vec![rendered("search"), rendered("read")],+ ),+ ("zed".to_string(), 2, vec![rendered("search")]),+ ]);- assert_eq!(- serde_json::to_string(&first).unwrap(),- serde_json::to_string(&second).unwrap()- );- assert_eq!(advertised_names(&first), ["search", "search"]);- assert_eq!(first_map.get("search").unwrap(), "zed");- assert_eq!(first_map, second_map);+ assert_eq!(advertised_names(&tools), ["read"]);+ assert!(!routes.contains_key("search"));+ assert_eq!(routes["read"].server, "fs");}#[test]- fn tool_to_server_stays_consistent_with_the_reordered_array() {- let (tools, tool_to_server) = assemble_tool_array(vec![- ("git".to_string(), vec![rendered("commit")]),- ("fs".to_string(), vec![rendered("read")]),+ fn routes_stay_consistent_with_the_reordered_array() {+ let (tools, routes) = assemble_tool_array(vec![+ ("git".to_string(), 2, vec![rendered("commit")]),+ ("fs".to_string(), 1, vec![rendered("read")]),]);assert_eq!(advertised_names(&tools), ["read", "commit"]);- assert_eq!(tool_to_server.get("read").unwrap(), "fs");- assert_eq!(tool_to_server.get("commit").unwrap(), "git");- assert_eq!(tool_to_server.len(), tools.len());+ assert_eq!(+ routes["read"],+ ToolRoute {+ server: "fs".to_string(),+ generation: 1+ }+ );+ assert_eq!(+ routes["commit"],+ ToolRoute {+ server: "git".to_string(),+ generation: 2+ }+ );+ assert_eq!(routes.len(), tools.len());}/// A listing timeout must not shrink the advertised array mid-session - the@@ -2313,27 +2359,45 @@ mod tests {#[test]fn a_failed_listing_reuses_the_last_known_tools() {let mut cache = HashMap::new();- let good = vec![("fs".to_string(), Some(vec![rendered("read")]))];+ let good = vec![("fs".to_string(), 1, Some(vec![rendered("read")]))];let (before, _) = assemble_tool_array(reuse_last_good_listings(&mut cache, good));- let timed_out = vec![("fs".to_string(), None)];- let (after, mapping) = assemble_tool_array(reuse_last_good_listings(&mut cache, timed_out));+ let timed_out = vec![("fs".to_string(), 1, None)];+ let (after, routes) = assemble_tool_array(reuse_last_good_listings(&mut cache, timed_out));assert_eq!(serde_json::to_string(&before).unwrap(),serde_json::to_string(&after).unwrap());- assert_eq!(mapping.get("read").unwrap(), "fs");+ assert_eq!(routes["read"].server, "fs");+ }++ /// A server replaced while its listing fails keeps the old tools advertised+ /// (the prefix stays warm) but routed to the old connection, so a call is+ /// refused rather than run on a process that never offered the tool.+ #[test]+ fn a_reused_listing_keeps_the_generation_it_was_listed_from() {+ let mut cache = HashMap::new();+ reuse_last_good_listings(+ &mut cache,+ vec![("fs".to_string(), 1, Some(vec![rendered("read")]))],+ );++ let replaced_and_failing = vec![("fs".to_string(), 2, None)];+ let (_, routes) =+ assemble_tool_array(reuse_last_good_listings(&mut cache, replaced_and_failing));++ assert_eq!(routes["read"].generation, 1);}#[test]fn a_server_that_never_listed_successfully_is_omitted() {let mut cache = HashMap::new();- let resolved = reuse_last_good_listings(&mut cache, vec![("fs".to_string(), None)]);- let (tools, mapping) = assemble_tool_array(resolved);+ let resolved = reuse_last_good_listings(&mut cache, vec![("fs".to_string(), 1, None)]);+ let (tools, routes) = assemble_tool_array(resolved);assert!(tools.is_empty());- assert!(mapping.is_empty());+ assert!(routes.is_empty());}/// Removing a server changes the array exactly once: its cached listing goes@@ -2344,12 +2408,12 @@ mod tests {reuse_last_good_listings(&mut cache,vec![- ("fs".to_string(), Some(vec![rendered("read")])),- ("git".to_string(), Some(vec![rendered("commit")])),+ ("fs".to_string(), 1, Some(vec![rendered("read")])),+ ("git".to_string(), 2, Some(vec![rendered("commit")])),],);- let resolved = reuse_last_good_listings(&mut cache, vec![("fs".to_string(), None)]);+ let resolved = reuse_last_good_listings(&mut cache, vec![("fs".to_string(), 1, None)]);let (tools, _) = assemble_tool_array(resolved);assert_eq!(advertised_names(&tools), ["read"]);@@ -2367,6 +2431,7 @@ mod tests {&mut cache,vec![("fs".to_string(),+ 1,Some(vec![rendered("read"), rendered("write")]),)],);@@ -2374,16 +2439,16 @@ mod tests {// `write` is no longer exposed by the server.let relisted = reuse_last_good_listings(&mut cache,- vec![("fs".to_string(), Some(vec![rendered("read")]))],+ vec![("fs".to_string(), 1, Some(vec![rendered("read")]))],);- let (tools, mapping) = assemble_tool_array(relisted);+ let (tools, routes) = assemble_tool_array(relisted);assert_eq!(advertised_names(&tools), ["read"]);- assert!(!mapping.contains_key("write"));+ assert!(!routes.contains_key("write"));// A later hiccup reuses that listing, not the pre-removal one.let (after_hiccup, _) = assemble_tool_array(reuse_last_good_listings(&mut cache,- vec![("fs".to_string(), None)],+ vec![("fs".to_string(), 1, None)],));assert_eq!(advertised_names(&after_hiccup), ["read"]);}diff --git a/src-tauri/src/core/cli/mcp.rs b/src-tauri/src/core/cli/mcp.rsindex 098ad6086..32001ed07 100644--- a/src-tauri/src/core/cli/mcp.rs+++ b/src-tauri/src/core/cli/mcp.rs@@ -27,6 +27,7 @@ use tokio::process::Command;use crate::core::app::commands::resolve_jan_data_folder;use crate::core::mcp::models::McpSettings;use crate::core::mcp::models::{extract_active_status, extract_command_args, McpServerConfig};+use crate::core::mcp::identity;use crate::core::mcp::oauth;use crate::core::state::{RunningServiceEnum, SharedMcpServers};@@ -512,7 +513,7 @@ async fn connect_in(}};- servers.lock().await.insert(name.to_string(), service);+ identity::insert_server(&mut *servers.lock().await, name, service);Ok(())}diff --git a/src-tauri/src/core/mcp/commands.rs b/src-tauri/src/core/mcp/commands.rsindex 5a81c4874..2611d3918 100644--- a/src-tauri/src/core/mcp/commands.rs+++ b/src-tauri/src/core/mcp/commands.rs@@ -17,6 +17,7 @@ use crate::core::{state::AppState,};use crate::core::{+ mcp::identity,mcp::models::ToolWithServer,state::{RunningMcpService, SharedMcpServers},};@@ -76,13 +77,17 @@ async fn collect_mcp_tools<R: Runtime>(let maybe_list_result = {let servers = state.mcp_servers.lock().await;match servers.get(&server_name) {- Some(service) => Some(timeout(timeout_duration, service.list_all_tools()).await),+ // Read under the servers lock, which every replacement holds.+ Some(service) => Some((+ identity::current_generation(&server_name),+ timeout(timeout_duration, service.list_all_tools()).await,+ )),None => None,}};let fresh_tools = match maybe_list_result {- Some(Ok(Ok(tools))) => {+ Some((generation, Ok(Ok(tools)))) => {let mapped: Vec<ToolWithServer> = tools.into_iter().map(|tool| ToolWithServer {@@ -90,13 +95,14 @@ async fn collect_mcp_tools<R: Runtime>(description: tool.description.as_ref().map(|d| d.to_string()),input_schema: serde_json::Value::Object((*tool.input_schema).clone()),server: server_name.clone(),+ generation,}).collect();let mut last_known = state.mcp_last_known_tools.lock().await;last_known.insert(server_name.clone(), mapped.clone());Some(mapped)}- Some(Ok(Err(e))) => {+ Some((_, Ok(Err(e)))) => {let err_str = e.to_string();log::warn!("MCP server {server_name} failed to list tools: {err_str}");if is_transport_error(&err_str) {@@ -107,7 +113,7 @@ async fn collect_mcp_tools<R: Runtime>(}None}- Some(Err(_)) => {+ Some((_, Err(_))) => {log::warn!("MCP server {server_name}: listing tools timed out after {} seconds",timeout_duration.as_secs()@@ -138,6 +144,15 @@ async fn collect_mcp_tools<R: Runtime>(}}+ // A name two servers offer, or an empty one, cannot be held to one server+ // when the model calls it, so it is not offered at all.+ let unroutable = identity::unroutable_tool_names(+ all_tools+ .iter()+ .map(|tool| (tool.server.as_str(), tool.name.as_str())),+ );+ all_tools.retain(|tool| !unroutable.contains(&tool.name));+Ok(all_tools)}@@ -387,28 +402,27 @@ pub async fn get_server_summaries(/// # Arguments/// * `state` - Application state containing MCP server connections/// * `tool_name` - Name of the tool to call-/// * `server_name` - Optional name of the server to call the tool from (for disambiguation)+/// * `server_name` - The server that offered the tool. Without it the tool is+/// looked up across servers, and a name more than one server offers is refused+/// * `server_generation` - The connection generation the tool was listed from+/// (`ToolWithServer::generation`). A call to a server that has since been+/// replaced is refused instead of running on the new process/// * `arguments` - Optional map of argument names to values/// * `cancellation_token` - Optional token to allow cancellation from JS side/// * `max_output_chars` - Optional caller-derived per-result character budget/// (the desktop chat derives one from the active model's context window);/// combined with the `maxToolOutputChars` setting, tighter wins///-/// # Returns-/// * `Result<CallToolResult, String>` - Result of the tool call if successful, or error message if failed-///-/// This function:-/// 1. Locks the MCP servers mutex to access server connections-/// 2. If server_name is provided, looks for the tool in that specific server-/// 3. Otherwise, searches through all servers for one containing the named tool-/// 4. When found, calls the tool on that server with the provided arguments-/// 5. Supports cancellation via cancellation_token-/// 6. Returns error if no server has the requested tool or if specified server not found+/// The servers lock is held from the generation check through the call, and+/// every replacement of a server takes that lock, so the connection checked is+/// the one that runs the call.#[tauri::command]+#[allow(clippy::too_many_arguments)]pub async fn call_tool(state: State<'_, AppState>,tool_name: String,server_name: Option<String>,+ server_generation: Option<u64>,arguments: Option<Map<String, Value>>,cancellation_token: Option<String>,max_output_chars: Option<u64>,@@ -430,115 +444,176 @@ pub async fn call_tool(let servers = state.mcp_servers.lock().await;- // If server_name is provided, only check that specific server- let servers_to_check: Vec<(&String, &RunningMcpService)> =- if let Some(ref server) = server_name {- servers.iter().filter(|(name, _)| *name == server).collect()- } else {- servers.iter().collect()- };-- if servers_to_check.is_empty() {- cleanup_cancellation_token(&state, &cancellation_token).await;- if let Some(server) = server_name {- return Err(format!("Server '{server}' not found"));+ let target = resolve_call_target(+ &servers,+ &tool_name,+ server_name.as_deref(),+ server_generation,+ )+ .await;+ let (srv_name, service) = match target {+ Ok(target) => target,+ Err(CallTargetError::Refused(e)) => {+ cleanup_cancellation_token(&state, &cancellation_token).await;+ return Err(e);}- return Err(format!(- "Tool {tool_name} not found — no MCP servers connected"- ));- }-- let mut transport_error_servers: Vec<String> = Vec::new();+ Err(CallTargetError::Disconnected(names)) => {+ state.mcp_reconnect_notify.notify_waiters();+ cleanup_cancellation_token(&state, &cancellation_token).await;+ return Err(format!(+ "MCP server(s) [{}] disconnected while looking for tool '{}'. Reconnecting - please retry.",+ names.join(", "),+ tool_name+ ));+ }+ };- // Iterate through servers and find the one that contains the tool- for (srv_name, service) in servers_to_check.iter() {- let tools = match service.list_all_tools().await {- Ok(tools) => tools,- Err(e) => {- let err_str = e.to_string();- log::warn!(- "MCP server {} failed to list tools during call_tool: {}",- srv_name,- err_str- );- if is_transport_error(&err_str) {- transport_error_servers.push(srv_name.to_string());+ log::info!("Found tool {tool_name} in server {srv_name}");++ // Call the tool with timeout and cancellation support+ let mut params = CallToolRequestParams::new(tool_name.clone());+ if let Some(args) = arguments {+ params = params.with_arguments(args);+ }+ let tool_call = service.call_tool(params);++ // Race between timeout, tool call, and cancellation+ let result = if cancellation_token.is_some() {+ tokio::select! {+ result = timeout(timeout_duration, tool_call) => {+ match result {+ Ok(call_result) => call_result.map_err(|e| e.to_string()),+ Err(_) => Err(format!(+ "Tool call '{tool_name}' timed out after {} seconds",+ timeout_duration.as_secs()+ )),}- continue;}- };+ _ = cancel_rx => {+ Err(format!("Tool call '{tool_name}' was cancelled"))+ }+ }+ } else {+ match timeout(timeout_duration, tool_call).await {+ Ok(call_result) => call_result.map_err(|e| e.to_string()),+ Err(_) => Err(format!(+ "Tool call '{tool_name}' timed out after {} seconds",+ timeout_duration.as_secs()+ )),+ }+ };- if !tools.iter().any(|t| t.name == tool_name) {- continue; // Tool not found in this server, try next+ // Signal reconnect if the tool call itself hit a transport error+ if let Err(e) = &result {+ if is_transport_error(e) {+ log::warn!("MCP server {srv_name} transport error during tool call: {e}");+ state.mcp_reconnect_notify.notify_waiters();}+ }- log::info!("Found tool {tool_name} in server {srv_name}");+ cleanup_cancellation_token(&state, &cancellation_token).await;+ // Cap here rather than at each caller: this is the single point every+ // desktop MCP tool result passes through on its way into conversation+ // history, so an unbounded result can never reach the model.+ result.map(|res| truncate_tool_result(&res, tool_output_cap))+}++pub(crate) enum CallTargetError {+ /// The call must not run; the message says why.+ Refused(String),+ /// No server was found to offer the tool, but these could not be asked.+ Disconnected(Vec<String>),+}- // Call the tool with timeout and cancellation support- let mut params = CallToolRequestParams::new(tool_name.clone());- if let Some(args) = arguments.clone() {- params = params.with_arguments(args);+/// The one connection a call may run on. A named server must still be the+/// connection the tool was listed from and must offer the tool; an unnamed+/// call needs exactly one server offering it. Never falls back to another+/// server: a call meant for one server that reaches another acts with the+/// wrong server's handler and grants.+pub(crate) async fn resolve_call_target<'a, S: McpToolSource>(+ servers: &'a std::collections::HashMap<String, S>,+ tool_name: &str,+ server_name: Option<&str>,+ server_generation: Option<u64>,+) -> Result<(&'a str, &'a S), CallTargetError> {+ if let Some(server) = server_name {+ let Some((name, service)) = servers.get_key_value(server) else {+ return Err(CallTargetError::Refused(format!(+ "MCP server '{server}' is not connected; the call was not run"+ )));+ };+ if let Some(generation) = server_generation {+ identity::check_generation(server, generation).map_err(CallTargetError::Refused)?;}- let tool_call = service.call_tool(params);-- // Race between timeout, tool call, and cancellation- let result = if cancellation_token.is_some() {- tokio::select! {- result = timeout(timeout_duration, tool_call) => {- match result {- Ok(call_result) => call_result.map_err(|e| e.to_string()),- Err(_) => Err(format!(- "Tool call '{tool_name}' timed out after {} seconds",- timeout_duration.as_secs()- )),- }- }- _ = cancel_rx => {- Err(format!("Tool call '{tool_name}' was cancelled"))- }- }- } else {- match timeout(timeout_duration, tool_call).await {- Ok(call_result) => call_result.map_err(|e| e.to_string()),- Err(_) => Err(format!(- "Tool call '{tool_name}' timed out after {} seconds",- timeout_duration.as_secs()- )),+ return match service.tool_names().await {+ Ok(names) if names.iter().any(|n| n == tool_name) => Ok((name.as_str(), service)),+ Ok(_) => Err(CallTargetError::Refused(format!(+ "MCP server '{server}' no longer offers tool '{tool_name}'"+ ))),+ Err(e) if is_transport_error(&e) => {+ Err(CallTargetError::Disconnected(vec![name.clone()]))}+ Err(e) => Err(CallTargetError::Refused(format!(+ "MCP server '{server}' could not list its tools: {e}"+ ))),};+ }- // Signal reconnect if the tool call itself hit a transport error- if let Err(ref e) = result {- if is_transport_error(e) {- log::warn!(- "MCP server {} transport error during tool call: {}",- srv_name,- e- );- state.mcp_reconnect_notify.notify_waiters();+ if servers.is_empty() {+ return Err(CallTargetError::Refused(format!(+ "Tool {tool_name} not found - no MCP servers connected"+ )));+ }++ let mut offering: Vec<(&'a str, &'a S)> = Vec::new();+ let mut disconnected: Vec<String> = Vec::new();+ for (name, service) in servers {+ match service.tool_names().await {+ Ok(names) if names.iter().any(|n| n == tool_name) => {+ offering.push((name.as_str(), service))+ }+ Ok(_) => {}+ Err(e) => {+ log::warn!("MCP server {name} failed to list tools during call_tool: {e}");+ if is_transport_error(&e) {+ disconnected.push(name.clone());+ }}}-- cleanup_cancellation_token(&state, &cancellation_token).await;- // Cap here rather than at each caller: this is the single point every- // desktop MCP tool result passes through on its way into conversation- // history, so an unbounded result can never reach the model.- return result.map(|res| truncate_tool_result(&res, tool_output_cap));}- // No server had the tool — check if it's because of transport errors- if !transport_error_servers.is_empty() {- state.mcp_reconnect_notify.notify_waiters();- cleanup_cancellation_token(&state, &cancellation_token).await;- return Err(format!(- "MCP server(s) [{}] disconnected while looking for tool '{}'. Reconnecting — please retry.",- transport_error_servers.join(", "),- tool_name- ));+ match offering.as_slice() {+ [only] => Ok(*only),+ [] if !disconnected.is_empty() => Err(CallTargetError::Disconnected(disconnected)),+ [] => Err(CallTargetError::Refused(format!(+ "Tool {tool_name} not found"+ ))),+ many => {+ let mut names: Vec<&str> = many.iter().map(|(name, _)| *name).collect();+ names.sort_unstable();+ Err(CallTargetError::Refused(format!(+ "Tool '{tool_name}' is offered by more than one MCP server ({}); the call was not run",+ names.join(", ")+ )))+ }}+}- cleanup_cancellation_token(&state, &cancellation_token).await;- Err(format!("Tool {tool_name} not found"))+/// The part of a running MCP service call routing needs, so routing can be+/// tested without a live server.+#[async_trait::async_trait]+pub(crate) trait McpToolSource: Sync {+ async fn tool_names(&self) -> Result<Vec<String>, String>;+}++#[async_trait::async_trait]+impl McpToolSource for RunningMcpService {+ async fn tool_names(&self) -> Result<Vec<String>, String> {+ self.list_all_tools()+ .await+ .map(|tools| tools.into_iter().map(|t| t.name.to_string()).collect())+ .map_err(|e| e.to_string())+ }}/// Cancels a running tool call by its cancellation tokendiff --git a/src-tauri/src/core/mcp/helpers.rs b/src-tauri/src/core/mcp/helpers.rsindex 9ad59bfab..f1a170f48 100644--- a/src-tauri/src/core/mcp/helpers.rs+++ b/src-tauri/src/core/mcp/helpers.rs@@ -20,6 +20,7 @@ use tokio::{use crate::core::{app::commands::get_jan_data_folder_path,mcp::models::{extract_active_status, extract_command_args, McpSettings},+ mcp::identity,mcp::oauth,mcp::progress::JanClientHandler,state::{AppState, RunningMcpService, SharedMcpServers},@@ -454,7 +455,7 @@ async fn schedule_mcp_start_task<R: Runtime>(match client {Ok(client) => {log::info!("Connected to server: {:?}", client.peer_info());- servers.lock().await.insert(name.clone(), client);+ identity::insert_server(&mut *servers.lock().await, &name, client);emit_mcp_update_event(&app, &name);}@@ -637,10 +638,7 @@ async fn schedule_mcp_start_task<R: Runtime>(});}log::trace!("Connected to server: {:#?}", server.peer_info());- servers- .lock()- .await- .insert(name.clone(), server);+ identity::insert_server(&mut *servers.lock().await, &name, server);log::info!("Server {name} started successfully.");// Wait a short time to verify the server is stable before marking as connecteddiff --git a/src-tauri/src/core/mcp/identity.rs b/src-tauri/src/core/mcp/identity.rsnew file mode 100644index 000000000..8d57daa63--- /dev/null+++ b/src-tauri/src/core/mcp/identity.rs@@ -0,0 +1,149 @@+//! Which connection an MCP server name refers to, so a tool call reaches the+//! server that advertised the tool and nothing else.+//!+//! A server name is not an identity: a server that disconnects and reconnects,+//! or is edited and restarted, comes back under the same name with a new+//! process, possibly a different tool set. Each connection therefore gets a+//! generation when it is put in the servers map, and a tool is advertised+//! together with the generation it was listed from. A call whose generation is+//! no longer the server's current one is refused rather than run on whatever+//! now answers to that name.+//!+//! A tool name offered by two servers is ambiguous: the model calls tools by+//! bare name, so no call to it can be attributed to one of them. Such names,+//! and empty ones, are left out of every listing rather than routed to a+//! guess.+//!+//! Generations come from one process-wide counter and are never reused, so a+//! server removed and added back cannot match a call made to its predecessor.++use std::collections::{HashMap, HashSet};+use std::sync::atomic::{AtomicU64, Ordering};+use std::sync::{LazyLock, Mutex};++/// The generation of a server name no connection was registered for. Never+/// handed out by [`insert_server`].+pub const UNREGISTERED: u64 = 0;++/// Where a call to an advertised tool must go.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct ToolRoute {+ pub server: String,+ pub generation: u64,+}++/// Advertised tool name -> the connection that offered it.+pub type ToolRoutes = HashMap<String, ToolRoute>;++static NEXT_GENERATION: AtomicU64 = AtomicU64::new(UNREGISTERED + 1);+static GENERATIONS: LazyLock<Mutex<HashMap<String, u64>>> = LazyLock::new(Default::default);++fn generations() -> &'static Mutex<HashMap<String, u64>> {+ &GENERATIONS+}++/// Puts a freshly connected service in the servers map under a new+/// generation. Every insertion into a servers map goes through here, with the+/// map's lock held by the caller, so a call that validates its generation under+/// the same lock cannot interleave with a replacement.+pub fn insert_server<V>(servers: &mut HashMap<String, V>, name: &str, service: V) -> u64 {+ let generation = NEXT_GENERATION.fetch_add(1, Ordering::Relaxed);+ generations()+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+ .insert(name.to_string(), generation);+ servers.insert(name.to_string(), service);+ generation+}++/// The generation of the connection currently registered under `name`.+pub fn current_generation(name: &str) -> u64 {+ generations()+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+ .get(name)+ .copied()+ .unwrap_or(UNREGISTERED)+}++/// Refuses a call made to a connection that has since been replaced.+pub fn check_generation(server: &str, generation: u64) -> Result<(), String> {+ if current_generation(server) == generation {+ Ok(())+ } else {+ Err(format!(+ "MCP server '{server}' restarted since this tool was offered; the call was not run. Retry to use the server's current tools."+ ))+ }+}++/// Tool names that cannot be routed: empty, or offered by more than one+/// server. `tools` yields `(server, tool name)` pairs.+pub fn unroutable_tool_names<'a>(+ tools: impl IntoIterator<Item = (&'a str, &'a str)>,+) -> HashSet<String> {+ let mut owner: HashMap<&str, &str> = HashMap::new();+ let mut unroutable = HashSet::new();+ for (server, tool) in tools {+ if tool.is_empty() {+ unroutable.insert(String::new());+ continue;+ }+ match owner.insert(tool, server) {+ Some(previous) if previous != server => {+ unroutable.insert(tool.to_string());+ }+ _ => {}+ }+ }+ for name in &unroutable {+ if !name.is_empty() {+ log::warn!(+ "MCP tool '{name}' is offered by more than one server; it is not offered to the model until only one server provides it"+ );+ }+ }+ unroutable+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_reconnect_invalidates_the_generation_a_tool_was_listed_from() {+ let mut servers: HashMap<String, ()> = HashMap::new();+ let first = insert_server(&mut servers, "identity-test-reconnect", ());+ assert!(check_generation("identity-test-reconnect", first).is_ok());++ let second = insert_server(&mut servers, "identity-test-reconnect", ());+ assert_ne!(first, second);+ assert!(check_generation("identity-test-reconnect", first).is_err());+ assert!(check_generation("identity-test-reconnect", second).is_ok());+ }++ #[test]+ fn generations_are_never_reused_across_names() {+ let mut servers: HashMap<String, ()> = HashMap::new();+ let a = insert_server(&mut servers, "identity-test-a", ());+ let b = insert_server(&mut servers, "identity-test-b", ());+ assert_ne!(a, b);+ assert_ne!(a, UNREGISTERED);+ assert!(check_generation("identity-test-b", a).is_err());+ }++ #[test]+ fn a_name_offered_by_two_servers_or_left_empty_is_unroutable() {+ let names = unroutable_tool_names([+ ("fs", "search"),+ ("web", "search"),+ ("fs", "read"),+ ("fs", "read"),+ ("git", ""),+ ]);+ assert!(names.contains("search"));+ assert!(names.contains(""));+ // One server listing a name twice is not a collision between servers.+ assert!(!names.contains("read"));+ }+}diff --git a/src-tauri/src/core/mcp/mod.rs b/src-tauri/src/core/mcp/mod.rsindex d4adec61b..dd1c0961f 100644--- a/src-tauri/src/core/mcp/mod.rs+++ b/src-tauri/src/core/mcp/mod.rs@@ -5,6 +5,9 @@ pub mod commands;pub mod constants;#[cfg(not(feature = "cli"))]pub mod helpers;+// Server connection generations and tool-name routing: shared by the desktop+// commands, the CLI and the agent loop.+pub mod identity;#[cfg(not(feature = "cli"))]pub mod lockfile;pub mod models;diff --git a/src-tauri/src/core/mcp/models.rs b/src-tauri/src/core/mcp/models.rsindex 3aa642fd6..9534bfe67 100644--- a/src-tauri/src/core/mcp/models.rs+++ b/src-tauri/src/core/mcp/models.rs@@ -169,6 +169,10 @@ pub struct ToolWithServer {#[serde(rename = "inputSchema")]pub input_schema: serde_json::Value,pub server: String,+ /// The connection generation the tool was listed from; passed back with a+ /// call so a replaced server cannot run it (see `mcp::identity`).+ #[serde(default)]+ pub generation: u64,}/// Lightweight server metadata used by the frontend orchestrator for tool routingdiff --git a/src-tauri/src/core/mcp/tests.rs b/src-tauri/src/core/mcp/tests.rsindex 4571fa059..0dab80c75 100644--- a/src-tauri/src/core/mcp/tests.rs+++ b/src-tauri/src/core/mcp/tests.rs@@ -367,6 +367,7 @@ async fn test_get_tools_falls_back_to_last_known_when_server_enabled_but_disconndescription: Some("search the web".to_string()),input_schema: serde_json::json!({}),server: "exa".to_string(),+ generation: 0,}],);}@@ -404,6 +405,7 @@ async fn test_get_tools_omits_disabled_server_even_with_stale_last_known_entry()description: None,input_schema: serde_json::json!({}),server: "old_server".to_string(),+ generation: 0,}],);}@@ -779,6 +781,7 @@ fn test_tool_with_server_serialization_uses_input_schema_camel_case() {description: Some("d".into()),input_schema: serde_json::json!({"type": "object"}),server: "srv".into(),+ generation: 0,};let json = serde_json::to_string(&t).unwrap();assert!(json.contains("\"inputSchema\":"));@@ -1073,3 +1076,102 @@ async fn initialize_identifies_the_client_as_jan() {assert_eq!(seen.name, "Jan");assert_eq!(seen.version, env!("CARGO_PKG_VERSION"));}++/// A stand-in for a connected server: the tools it lists, or a listing error.+struct FakeServer(Result<Vec<&'static str>, &'static str>);++#[async_trait::async_trait]+impl super::commands::McpToolSource for FakeServer {+ async fn tool_names(&self) -> Result<Vec<String>, String> {+ self.0+ .clone()+ .map(|names| names.into_iter().map(String::from).collect())+ .map_err(String::from)+ }+}++fn listing(names: &[&'static str]) -> FakeServer {+ FakeServer(Ok(names.to_vec()))+}++async fn route_call(+ servers: &HashMap<String, FakeServer>,+ tool: &str,+ server: Option<&str>,+ generation: Option<u64>,+) -> Result<String, String> {+ use super::commands::{resolve_call_target, CallTargetError};+ match resolve_call_target(servers, tool, server, generation).await {+ Ok((name, _)) => Ok(name.to_string()),+ Err(CallTargetError::Refused(e)) => Err(e),+ Err(CallTargetError::Disconnected(names)) => Err(format!("disconnected: {names:?}")),+ }+}++/// A server restarted under the same name gets a new generation, so a call+/// listed from the old connection is refused instead of reaching the new one.+#[tokio::test]+async fn a_call_listed_before_a_reconnect_is_refused() {+ use super::identity::insert_server;+ let mut servers = HashMap::new();+ let old = insert_server(&mut servers, "route-reconnect", listing(&["search"]));+ let new = insert_server(&mut servers, "route-reconnect", listing(&["search"]));++ let stale = route_call(&servers, "search", Some("route-reconnect"), Some(old)).await;+ assert!(stale.unwrap_err().contains("restarted"));++ let current = route_call(&servers, "search", Some("route-reconnect"), Some(new)).await;+ assert_eq!(current.unwrap(), "route-reconnect");+}++/// While the named server is gone (a reload window), the call is refused even+/// though another server offers a tool of the same name.+#[tokio::test]+async fn a_call_to_a_missing_server_is_not_rerouted() {+ use super::identity::insert_server;+ let mut servers = HashMap::new();+ insert_server(&mut servers, "route-other", listing(&["search"]));++ let result = route_call(&servers, "search", Some("route-reloading"), None).await;+ assert!(result.unwrap_err().contains("not connected"));+}++/// A named server that dropped the tool since it was offered does not run it.+#[tokio::test]+async fn a_named_server_must_still_offer_the_tool() {+ use super::identity::insert_server;+ let mut servers = HashMap::new();+ let generation = insert_server(&mut servers, "route-dropped", listing(&["read"]));++ let result = route_call(&servers, "search", Some("route-dropped"), Some(generation)).await;+ assert!(result.unwrap_err().contains("no longer offers"));+}++/// Without a server name, a tool two servers offer is ambiguous and refused;+/// one only a single server offers still resolves to it.+#[tokio::test]+async fn an_unnamed_call_to_a_duplicate_tool_name_is_refused() {+ use super::identity::insert_server;+ let mut servers = HashMap::new();+ insert_server(&mut servers, "route-a", listing(&["search", "read"]));+ insert_server(&mut servers, "route-b", listing(&["search"]));++ let ambiguous = route_call(&servers, "search", None, None).await;+ assert!(ambiguous.unwrap_err().contains("more than one MCP server"));++ let unique = route_call(&servers, "read", None, None).await;+ assert_eq!(unique.unwrap(), "route-a");+}++/// A server that cannot be asked is reported as disconnected rather than the+/// tool as missing, so the caller retries after the reconnect.+#[tokio::test]+async fn an_unreachable_server_reports_a_disconnect() {+ use super::identity::insert_server;+ let mut servers = HashMap::new();+ let down = FakeServer(Err("transport closed"));+ insert_server(&mut servers, "route-down", down);++ let result = route_call(&servers, "search", None, None).await;+ assert!(result.unwrap_err().starts_with("disconnected"));+}