дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-05 17:47:08 +02:00
1059 рядки
50 KiB
Rust
1059 рядки
50 KiB
Rust
//! The server over real HTTP, and the stdio bridge in front of it, with a
|
||
//! registry standing in for the IDE host.
|
||
|
||
use ide_mcp::{Discovery, McpServer, ServerOptions, Tool, ToolCallError, ToolRegistry, discovery_path, stdio};
|
||
use serde_json::{Value, json};
|
||
use std::path::{Path, PathBuf};
|
||
use std::sync::Arc;
|
||
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt};
|
||
|
||
struct Registry {
|
||
project: PathBuf,
|
||
}
|
||
|
||
impl ToolRegistry for Registry {
|
||
fn projects(&self) -> Vec<PathBuf> {
|
||
vec![self.project.clone()]
|
||
}
|
||
|
||
fn tools(&self, project: &Path) -> Result<Vec<Tool>, String> {
|
||
assert_eq!(project, self.project);
|
||
Ok(vec![Tool {
|
||
name: "echo".into(),
|
||
description: "Says it back".into(),
|
||
input_schema: json!({ "type": "object", "properties": { "text": { "type": "string" } } }),
|
||
read_only: true,
|
||
destructive: false,
|
||
output_schema: None,
|
||
}])
|
||
}
|
||
|
||
fn tools_without_project(&self) -> Vec<Tool> {
|
||
vec![named("everything")]
|
||
}
|
||
|
||
fn call(
|
||
&self,
|
||
project: &Path,
|
||
name: &str,
|
||
arguments: &str,
|
||
_cancel: ide_mcp::CancellationToken,
|
||
) -> Result<String, ToolCallError> {
|
||
let args: Value = serde_json::from_str(arguments).unwrap();
|
||
match name {
|
||
"echo" if args["text"] == "fail" => Err(ToolCallError::Failed("it failed".into())),
|
||
"echo" => Ok(format!("{} in {}", args["text"].as_str().unwrap_or(""), project.display())),
|
||
"sleep" => {
|
||
std::thread::sleep(std::time::Duration::from_millis(args["ms"].as_u64().unwrap()));
|
||
Ok("slept".into())
|
||
}
|
||
_ => Err(ToolCallError::UnknownTool(format!("no tool {name:?}"))),
|
||
}
|
||
}
|
||
}
|
||
|
||
/// A read-only tool with no arguments.
|
||
fn named(name: &str) -> Tool {
|
||
Tool {
|
||
name: name.into(),
|
||
description: format!("The tool {name}"),
|
||
input_schema: json!({ "type": "object" }),
|
||
read_only: true,
|
||
destructive: false,
|
||
output_schema: None,
|
||
}
|
||
}
|
||
|
||
struct Setup {
|
||
_tmp: tempfile::TempDir,
|
||
project: PathBuf,
|
||
discovery: PathBuf,
|
||
server: Option<McpServer>,
|
||
}
|
||
|
||
fn setup() -> Setup {
|
||
let tmp = tempfile::tempdir().unwrap();
|
||
let project = dunce::canonicalize(tmp.path()).unwrap().join("project");
|
||
std::fs::create_dir_all(project.join("src")).unwrap();
|
||
let discovery = discovery_path(&tmp.path().join("app-data"));
|
||
let registry = Arc::new(Registry { project: project.clone() });
|
||
let server = McpServer::start_with(
|
||
registry,
|
||
Some(discovery.clone()),
|
||
&tokio::runtime::Handle::current(),
|
||
ServerOptions::default(),
|
||
)
|
||
.unwrap();
|
||
Setup { _tmp: tmp, project, discovery, server: Some(server) }
|
||
}
|
||
|
||
impl Setup {
|
||
fn server(&self) -> &McpServer {
|
||
self.server.as_ref().unwrap()
|
||
}
|
||
}
|
||
|
||
/// A raw HTTP/1.1 exchange: (status, body).
|
||
async fn http(port: u16, request: &str) -> (u16, String) {
|
||
let mut stream = tokio::net::TcpStream::connect(("127.0.0.1", port)).await.unwrap();
|
||
stream.write_all(request.as_bytes()).await.unwrap();
|
||
let mut out = String::new();
|
||
stream.read_to_string(&mut out).await.unwrap();
|
||
let status = out.split(' ').nth(1).unwrap().parse().unwrap();
|
||
let body = out.split_once("\r\n\r\n").map(|(_, b)| b.to_owned()).unwrap_or_default();
|
||
(status, body)
|
||
}
|
||
|
||
/// POSTs `body` to `path` with extra header lines; closes the connection after.
|
||
async fn post(s: &Setup, path: &str, headers: &[&str], body: &Value) -> (u16, String) {
|
||
let body = body.to_string();
|
||
let port = s.server().port();
|
||
let mut head = format!(
|
||
"POST {path} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nContent-Type: application/json\r\nAccept: application/json, text/event-stream\r\nContent-Length: {}\r\nConnection: close\r\n",
|
||
body.len()
|
||
);
|
||
for h in headers {
|
||
head.push_str(h);
|
||
head.push_str("\r\n");
|
||
}
|
||
http(port, &format!("{head}\r\n{body}")).await
|
||
}
|
||
|
||
fn bearer(s: &Setup) -> String {
|
||
format!("Authorization: Bearer {}", s.server().token())
|
||
}
|
||
|
||
async fn rpc(s: &Setup, method: &str, params: Value) -> Value {
|
||
let project = format!("X-OpenIDEA-Project: {}", s.project.display());
|
||
let (status, body) = post(
|
||
s,
|
||
"/mcp",
|
||
&[&bearer(s), &project],
|
||
&json!({ "jsonrpc": "2.0", "id": 7, "method": method, "params": params }),
|
||
)
|
||
.await;
|
||
assert_eq!(status, 200, "{body}");
|
||
let reply: Value = serde_json::from_str(&body).unwrap();
|
||
assert_eq!(reply["id"], 7);
|
||
reply
|
||
}
|
||
|
||
#[tokio::test(flavor = "multi_thread")]
|
||
async fn initialize_list_and_call_tools() {
|
||
let s = setup();
|
||
let init = rpc(
|
||
&s,
|
||
"initialize",
|
||
json!({ "protocolVersion": "2025-03-26", "capabilities": {}, "clientInfo": { "name": "t", "version": "1" } }),
|
||
)
|
||
.await;
|
||
assert_eq!(init["result"]["protocolVersion"], "2025-03-26");
|
||
assert_eq!(init["result"]["serverInfo"]["name"], "OpenIDEA");
|
||
assert!(init["result"]["capabilities"]["tools"].is_object());
|
||
let newer = rpc(&s, "initialize", json!({ "protocolVersion": "2099-01-01" })).await;
|
||
assert_eq!(newer["result"]["protocolVersion"], "2025-06-18");
|
||
|
||
// Notifications are accepted without a body.
|
||
let (status, body) =
|
||
post(&s, "/mcp", &[&bearer(&s)], &json!({ "jsonrpc": "2.0", "method": "notifications/initialized" })).await;
|
||
assert_eq!((status, body.as_str()), (202, ""));
|
||
|
||
let list = rpc(&s, "tools/list", json!({})).await;
|
||
let tool = &list["result"]["tools"][0];
|
||
assert_eq!(tool["name"], "echo");
|
||
assert_eq!(tool["inputSchema"]["type"], "object");
|
||
assert_eq!(tool["annotations"], json!({ "readOnlyHint": true, "destructiveHint": false }));
|
||
|
||
let call = rpc(&s, "tools/call", json!({ "name": "echo", "arguments": { "text": "hi" } })).await;
|
||
let expected = format!("hi in {}", s.project.display());
|
||
assert_eq!(call["result"], json!({ "content": [{ "type": "text", "text": expected }], "isError": false }));
|
||
let failed = rpc(&s, "tools/call", json!({ "name": "echo", "arguments": { "text": "fail" } })).await;
|
||
assert_eq!(failed["result"]["isError"], true);
|
||
assert_eq!(failed["result"]["content"][0]["text"], "it failed");
|
||
let unknown = rpc(&s, "tools/call", json!({ "name": "nope" })).await;
|
||
assert_eq!(unknown["error"]["code"], -32602);
|
||
assert_eq!(rpc(&s, "ping", json!({})).await["result"], json!({}));
|
||
assert_eq!(rpc(&s, "resources/list", json!({})).await["error"]["code"], -32601);
|
||
|
||
// The project by query, from a folder inside it; a batch.
|
||
let query = format!(
|
||
"/mcp?project={}",
|
||
ide_mcp::endpoint_url_at(std::net::Ipv4Addr::LOCALHOST.into(), 1, &s.project.join("src"))
|
||
.split_once('=')
|
||
.unwrap()
|
||
.1
|
||
);
|
||
let batch = json!([
|
||
{ "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "echo", "arguments": { "text": "a" } } },
|
||
{ "jsonrpc": "2.0", "method": "notifications/cancelled", "params": { "requestId": 9 } },
|
||
{ "jsonrpc": "2.0", "id": 2, "method": "ping" }
|
||
]);
|
||
let (status, body) = post(&s, &query, &[&bearer(&s)], &batch).await;
|
||
assert_eq!(status, 200, "{body}");
|
||
let replies: Value = serde_json::from_str(&body).unwrap();
|
||
assert_eq!(replies.as_array().unwrap().len(), 2);
|
||
assert_eq!(replies[0]["result"]["content"][0]["text"], expected.replacen("hi", "a", 1));
|
||
}
|
||
|
||
#[tokio::test(flavor = "multi_thread")]
|
||
async fn requests_without_the_token_or_from_web_pages_are_refused() {
|
||
let s = setup();
|
||
let ping = json!({ "jsonrpc": "2.0", "id": 1, "method": "ping" });
|
||
assert_eq!(post(&s, "/mcp", &[], &ping).await.0, 401);
|
||
assert_eq!(post(&s, "/mcp", &["Authorization: Bearer wrong"], &ping).await.0, 401);
|
||
assert_eq!(post(&s, "/mcp", &[&bearer(&s), "Origin: https://evil.example"], &ping).await.0, 403);
|
||
let port = s.server().port();
|
||
let (status, _) = http(
|
||
port,
|
||
&format!(
|
||
"POST /mcp HTTP/1.1\r\nHost: evil.example:{port}\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{{}}"
|
||
),
|
||
)
|
||
.await;
|
||
assert_eq!(status, 403, "a rebound host name");
|
||
// No SSE stream to open; other paths don't exist.
|
||
let get = format!("GET /mcp HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n{}\r\nConnection: close\r\n\r\n", bearer(&s));
|
||
assert_eq!(http(port, &get).await.0, 405);
|
||
assert_eq!(post(&s, "/other", &[&bearer(&s)], &ping).await.0, 404);
|
||
assert_eq!(post(&s, "/mcp", &[&bearer(&s), "MCP-Protocol-Version: 1999-01-01"], &ping).await.0, 400);
|
||
let (status, body) = post(&s, "/mcp", &[&bearer(&s)], &json!("{")).await;
|
||
assert_eq!(status, 200, "a JSON string is a message, just not a request: {body}");
|
||
let garbage = format!(
|
||
"POST /mcp HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n{}\r\nContent-Length: 1\r\nConnection: close\r\n\r\n{{",
|
||
bearer(&s)
|
||
);
|
||
let (status, body) = http(port, &garbage).await;
|
||
assert_eq!(status, 400);
|
||
assert_eq!(serde_json::from_str::<Value>(&body).unwrap()["error"]["code"], -32700);
|
||
}
|
||
|
||
#[tokio::test(flavor = "multi_thread")]
|
||
async fn folders_that_are_not_open_are_named_in_the_error() {
|
||
let s = setup();
|
||
let elsewhere = s.project.parent().unwrap().join("elsewhere");
|
||
// The connection's folder isn't open: the list is the one without a project, and a call
|
||
// that names no project of its own is refused with the folder named.
|
||
let list = rpc_for(&s, &elsewhere, "tools/list", json!({})).await;
|
||
assert_eq!(list["result"]["tools"][0]["name"], "everything", "{list}");
|
||
let call = rpc_for(&s, &elsewhere, "tools/call", json!({ "name": "echo" })).await;
|
||
assert_eq!(call["error"]["code"], -32001, "{call}");
|
||
let message = call["error"]["message"].as_str().unwrap();
|
||
assert!(message.contains("isn't open in OpenIDEA") && message.contains(elsewhere.to_str().unwrap()), "{message}");
|
||
// No folder named and one window: that window's project lists its tools.
|
||
let (_, body) = post(&s, "/mcp", &[&bearer(&s)], &json!({"jsonrpc":"2.0","id":3,"method":"tools/list"})).await;
|
||
assert_eq!(serde_json::from_str::<Value>(&body).unwrap()["result"]["tools"][0]["name"], "echo");
|
||
}
|
||
|
||
/// One project open in a window, the folders served without a window and, optionally, the
|
||
/// root of a window on a remote host (which has no tools here).
|
||
struct WithBackground {
|
||
open: PathBuf,
|
||
background: Vec<PathBuf>,
|
||
remote: Option<PathBuf>,
|
||
}
|
||
|
||
impl ToolRegistry for WithBackground {
|
||
fn projects(&self) -> Vec<PathBuf> {
|
||
std::iter::once(self.open.clone()).chain(self.remote.clone()).collect()
|
||
}
|
||
/// The innermost served folder containing `path`, strictly inside `within`, as the
|
||
/// background policy answers.
|
||
fn resolve(&self, path: &Path, within: Option<&Path>) -> Option<PathBuf> {
|
||
let inside = |root: &&PathBuf| within.is_none_or(|open| root.starts_with(open) && *root != open);
|
||
let served = self.background.iter().filter(|root| path.starts_with(root)).filter(inside);
|
||
served.max_by_key(|root| root.components().count()).cloned()
|
||
}
|
||
fn tools_without_project(&self) -> Vec<Tool> {
|
||
vec![named("anything")]
|
||
}
|
||
fn tools(&self, project: &Path) -> Result<Vec<Tool>, String> {
|
||
if self.remote.as_deref() == Some(project) {
|
||
return Err("project is on a remote host".into());
|
||
}
|
||
Ok(vec![Tool {
|
||
name: "where".into(),
|
||
description: format!("Names {}", project.display()),
|
||
input_schema: json!({ "type": "object" }),
|
||
read_only: true,
|
||
destructive: false,
|
||
output_schema: None,
|
||
}])
|
||
}
|
||
fn call(&self, project: &Path, _: &str, _: &str, _: ide_mcp::CancellationToken) -> Result<String, ToolCallError> {
|
||
Ok(json!({"project":project}).to_string())
|
||
}
|
||
}
|
||
|
||
/// Stops the server of `s` and serves `registry` in its place.
|
||
fn restart(s: &mut Setup, registry: impl ToolRegistry) {
|
||
s.server.take().unwrap().stop();
|
||
let runtime = tokio::runtime::Handle::current();
|
||
s.server = Some(McpServer::start_with(Arc::new(registry), None, &runtime, ServerOptions::default()).unwrap());
|
||
}
|
||
|
||
/// The server over [`WithBackground`] serving the `served` folders, relative to the folder
|
||
/// that holds the open project; the folder `inventory` next to the open project.
|
||
fn setup_with_background(served: &[&str]) -> (Setup, PathBuf) {
|
||
let mut s = setup();
|
||
let base = s.project.parent().unwrap().to_path_buf();
|
||
let inventory = base.join("inventory");
|
||
std::fs::create_dir_all(inventory.join("src")).unwrap();
|
||
let background = served.iter().map(|folder| base.join(folder).components().collect()).collect();
|
||
let registry = WithBackground { open: s.project.clone(), background, remote: None };
|
||
restart(&mut s, registry);
|
||
(s, inventory)
|
||
}
|
||
|
||
async fn rpc_for(s: &Setup, folder: &Path, method: &str, params: Value) -> Value {
|
||
let project = format!("X-OpenIDEA-Project: {}", folder.display());
|
||
let body = json!({ "jsonrpc": "2.0", "id": 7, "method": method, "params": params });
|
||
let (status, body) = post(s, "/mcp", &[&bearer(s), &project], &body).await;
|
||
assert_eq!(status, 200, "{body}");
|
||
serde_json::from_str(&body).unwrap()
|
||
}
|
||
|
||
#[tokio::test(flavor = "multi_thread")]
|
||
async fn a_folder_served_in_the_background_answers_initialize_list_and_call() {
|
||
let (s, inventory) = setup_with_background(&["inventory"]);
|
||
let inside = inventory.join("src");
|
||
let init = rpc_for(&s, &inside, "initialize", json!({})).await;
|
||
let instructions = init["result"]["instructions"].as_str().unwrap();
|
||
assert!(instructions.contains(inventory.to_str().unwrap()), "{instructions}");
|
||
// Clients that load tool descriptions lazily still learn to establish the workspace first (#5751).
|
||
assert!(instructions.contains("first project-related operation in a session, call `get_workspace_roots`"));
|
||
assert!(!instructions.contains("no project of its own"), "{instructions}");
|
||
let list = rpc_for(&s, &inside, "tools/list", json!({})).await;
|
||
assert_eq!(list["result"]["tools"][0]["description"], format!("Names {}", inventory.display()), "{list}");
|
||
let call = rpc_for(&s, &inside, "tools/call", json!({ "name": "where" })).await;
|
||
assert_eq!(call["result"]["structuredContent"]["project"], json!(inventory), "{call}");
|
||
// The argument names it as well, whatever project the header is for.
|
||
let routed = rpc(&s, "tools/call", json!({ "name": "where", "arguments": { "projectPath": inside } })).await;
|
||
assert_eq!(routed["result"]["structuredContent"]["project"], json!(inventory), "{routed}");
|
||
// A folder inside the open project stays with that project.
|
||
let open = rpc(&s, "tools/call", json!({ "name": "where" })).await;
|
||
assert_eq!(open["result"]["structuredContent"]["project"], json!(s.project), "{open}");
|
||
}
|
||
|
||
#[tokio::test(flavor = "multi_thread")]
|
||
async fn the_innermost_project_answers_whether_a_window_has_it_open_or_it_is_served_in_the_background() {
|
||
// The layout of #7040: a window on `project` and `contracts` inside it served in the
|
||
// background. The policy serves the window's root and the folder around it as well, as
|
||
// trusted projects and listed folders do.
|
||
let (s, _) = setup_with_background(&["", "project", "project/contracts"]);
|
||
let contracts = s.project.join("contracts");
|
||
std::fs::create_dir_all(contracts.join("src")).unwrap();
|
||
let base = s.project.parent().unwrap().to_path_buf();
|
||
for (folder, served) in [
|
||
(contracts.join("src"), &contracts),
|
||
(contracts.clone(), &contracts),
|
||
// Folders of the window's project that no nested project holds stay with the window.
|
||
(s.project.join("src"), &s.project),
|
||
(s.project.clone(), &s.project),
|
||
(base.join("elsewhere"), &base),
|
||
] {
|
||
let at = folder.display();
|
||
let call = rpc(&s, "tools/call", json!({ "name": "where", "arguments": { "projectPath": folder } })).await;
|
||
assert_eq!(call["result"]["structuredContent"]["project"], json!(served), "{at}: {call}");
|
||
let list = rpc_for(&s, &folder, "tools/list", json!({})).await;
|
||
assert_eq!(list["result"]["tools"][0]["description"], format!("Names {}", served.display()), "{at}: {list}");
|
||
let init = rpc_for(&s, &folder, "initialize", json!({})).await;
|
||
let instructions = init["result"]["instructions"].as_str().unwrap();
|
||
assert!(instructions.contains(&format!("serves at {}:", served.display())), "{at}: {instructions}");
|
||
}
|
||
}
|
||
|
||
#[tokio::test(flavor = "multi_thread")]
|
||
async fn a_folder_that_is_neither_open_nor_served_in_the_background_says_where_to_turn_it_on() {
|
||
let (s, inventory) = setup_with_background(&[]);
|
||
let list = rpc_for(&s, &inventory, "tools/list", json!({})).await;
|
||
assert_eq!(list["result"]["tools"][0]["name"], "anything", "{list}");
|
||
let reply = rpc_for(&s, &inventory, "tools/call", json!({ "name": "where" })).await;
|
||
assert_eq!(reply["error"]["code"], -32001, "{reply}");
|
||
let message = reply["error"]["message"].as_str().unwrap();
|
||
assert!(message.contains("isn't open in OpenIDEA and isn't served in the background"), "{message}");
|
||
assert!(message.contains("Settings › Agents › IDE MCP Server"), "{message}");
|
||
assert!(message.contains(inventory.to_str().unwrap()) && message.contains(s.project.to_str().unwrap()));
|
||
let init = rpc_for(&s, &inventory, "initialize", json!({})).await;
|
||
let instructions = init["result"]["instructions"].as_str().unwrap();
|
||
assert!(
|
||
instructions.contains("pass `projectPath`, a folder inside a project OpenIDEA serves, in every call"),
|
||
"{instructions}"
|
||
);
|
||
}
|
||
|
||
#[tokio::test(flavor = "multi_thread")]
|
||
async fn serves_folder_names_the_project_that_answers_for_the_connection_folder() {
|
||
let (mut s, inventory) = setup_with_background(&[]);
|
||
let base = s.project.parent().unwrap().to_owned();
|
||
let remote = base.join("remote");
|
||
let registry =
|
||
WithBackground { open: s.project.clone(), background: vec![inventory.clone()], remote: Some(remote.clone()) };
|
||
restart(&mut s, registry);
|
||
let cases = [
|
||
(s.project.join("src"), json!(s.project)),
|
||
(inventory.join("src"), json!(inventory)),
|
||
(base.join("elsewhere"), Value::Null),
|
||
// A remote window's root is that host's to serve.
|
||
(remote, Value::Null),
|
||
];
|
||
for (folder, root) in cases {
|
||
let reply = rpc_for(&s, &folder, "openidea/servesFolder", json!({})).await;
|
||
assert_eq!(reply["result"], json!({ "root": root }), "{}: {reply}", folder.display());
|
||
}
|
||
}
|
||
|
||
#[tokio::test(flavor = "multi_thread")]
|
||
async fn the_discovery_file_lives_while_the_server_runs() {
|
||
let mut s = setup();
|
||
let info = Discovery::read(&s.discovery).unwrap();
|
||
assert_eq!((info.port, info.token.as_str(), info.pid), (s.server().port(), s.server().token(), std::process::id()));
|
||
let port = info.port;
|
||
s.server.take().unwrap().stop();
|
||
assert!(!s.discovery.exists());
|
||
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
|
||
assert!(tokio::net::TcpStream::connect(("127.0.0.1", port)).await.is_err(), "the port is closed");
|
||
}
|
||
|
||
#[tokio::test(flavor = "multi_thread")]
|
||
async fn the_stdio_bridge_relays_lines_and_explains_a_missing_ide() {
|
||
let mut s = setup();
|
||
let input = [
|
||
json!({ "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "protocolVersion": "2025-06-18" } }),
|
||
json!({ "jsonrpc": "2.0", "method": "notifications/initialized" }),
|
||
json!({ "jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": { "name": "echo", "arguments": { "text": "x" } } }),
|
||
]
|
||
.iter()
|
||
.map(|m| format!("{m}\n"))
|
||
.collect::<String>()
|
||
+ "\n";
|
||
let mut output = Vec::new();
|
||
stdio::bridge(&s.discovery, &s.project.join("src"), input.as_bytes(), &mut output).await.unwrap();
|
||
let mut replies: Vec<Value> =
|
||
String::from_utf8(output).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect();
|
||
replies.sort_by_key(|r| r["id"].as_i64());
|
||
assert_eq!(replies.len(), 2, "nothing for the notification: {replies:?}");
|
||
assert_eq!(replies[0]["result"]["protocolVersion"], "2025-06-18");
|
||
assert_eq!(replies[1]["result"]["content"][0]["text"], format!("x in {}", s.project.display()));
|
||
|
||
// The IDE quit: each request gets an error saying what to do.
|
||
s.server.take().unwrap().stop();
|
||
let mut output = Vec::new();
|
||
let input = format!("{}\n", json!({ "jsonrpc": "2.0", "id": 5, "method": "initialize", "params": {} }));
|
||
stdio::bridge(&s.discovery, &s.project, input.as_bytes(), &mut output).await.unwrap();
|
||
let reply: Value = serde_json::from_slice(&output).unwrap();
|
||
assert_eq!(reply["id"], 5);
|
||
assert!(reply["error"]["message"].as_str().unwrap().contains("MCP server is not running"), "{reply}");
|
||
}
|
||
|
||
#[tokio::test(flavor = "multi_thread")]
|
||
async fn the_stdio_bridge_relays_a_long_call_answered_on_an_event_stream() {
|
||
let s = setup();
|
||
let call = json!({ "jsonrpc": "2.0", "id": 4, "method": "tools/call",
|
||
"params": { "name": "sleep", "arguments": { "ms": 1500 }, "_meta": { "progressToken": 4 } } });
|
||
let mut output = Vec::new();
|
||
stdio::bridge(&s.discovery, &s.project, format!("{call}\n").as_bytes(), &mut output).await.unwrap();
|
||
let replies: Vec<Value> =
|
||
String::from_utf8(output).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect();
|
||
let answer = replies.last().unwrap();
|
||
assert_eq!(answer["id"], 4, "{replies:?}");
|
||
assert_eq!(answer["result"]["content"][0]["text"], "slept");
|
||
}
|
||
|
||
#[tokio::test(flavor = "multi_thread")]
|
||
async fn routing_an_argument_overrides_the_header_and_ambiguity_lists_projects() {
|
||
struct Many(Vec<PathBuf>);
|
||
impl ToolRegistry for Many {
|
||
fn projects(&self) -> Vec<PathBuf> {
|
||
self.0.clone()
|
||
}
|
||
fn tools(&self, _: &Path) -> Result<Vec<Tool>, String> {
|
||
Ok(Vec::new())
|
||
}
|
||
fn tools_without_project(&self) -> Vec<Tool> {
|
||
vec![named("anywhere")]
|
||
}
|
||
fn call(
|
||
&self,
|
||
project: &Path,
|
||
_: &str,
|
||
_: &str,
|
||
_: ide_mcp::CancellationToken,
|
||
) -> Result<String, ToolCallError> {
|
||
Ok(json!({"project":project}).to_string())
|
||
}
|
||
}
|
||
let mut s = setup();
|
||
s.server.take().unwrap().stop();
|
||
let second = s.project.parent().unwrap().join("second");
|
||
std::fs::create_dir_all(second.join("nested")).unwrap();
|
||
s.server = Some(
|
||
McpServer::start_with(
|
||
Arc::new(Many(vec![s.project.clone(), second.clone()])),
|
||
None,
|
||
&tokio::runtime::Handle::current(),
|
||
ServerOptions::default(),
|
||
)
|
||
.unwrap(),
|
||
);
|
||
// No folder named and two windows: the list without a project, and a call has to name one.
|
||
let (_, body) = post(&s, "/mcp", &[&bearer(&s)], &json!({"jsonrpc":"2.0","id":1,"method":"tools/list"})).await;
|
||
let list: Value = serde_json::from_str(&body).unwrap();
|
||
assert_eq!(list["result"]["tools"][0]["name"], "anywhere", "{list}");
|
||
let call = json!({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"where"}});
|
||
let (_, body) = post(&s, "/mcp", &[&bearer(&s)], &call).await;
|
||
let reply: Value = serde_json::from_str(&body).unwrap();
|
||
assert_eq!(reply["error"]["code"], -32602, "{reply}");
|
||
let message = reply["error"]["message"].as_str().unwrap();
|
||
assert!(message.contains(s.project.to_str().unwrap()) && message.contains(second.to_str().unwrap()));
|
||
let result = rpc(&s, "tools/call", json!({"name":"where","arguments":{"projectPath":second.join("nested")}})).await;
|
||
assert_eq!(result["result"]["structuredContent"]["project"], json!(second));
|
||
let unknown = rpc(&s, "tools/call", json!({"name":"where","arguments":{"projectPath":"/unknown/project"}})).await;
|
||
assert_eq!(unknown["error"]["code"], -32001);
|
||
}
|
||
|
||
#[tokio::test(flavor = "multi_thread")]
|
||
async fn cancellation_reaches_a_running_tool_without_affecting_another_client() {
|
||
struct Waiting(Arc<tokio::sync::Notify>);
|
||
impl ToolRegistry for Waiting {
|
||
fn projects(&self) -> Vec<PathBuf> {
|
||
vec![PathBuf::from("/project")]
|
||
}
|
||
fn tools(&self, _: &Path) -> Result<Vec<Tool>, String> {
|
||
Ok(Vec::new())
|
||
}
|
||
fn call(
|
||
&self,
|
||
_: &Path,
|
||
_: &str,
|
||
_: &str,
|
||
cancel: ide_mcp::CancellationToken,
|
||
) -> Result<String, ToolCallError> {
|
||
self.0.notify_one();
|
||
tokio::runtime::Handle::current().block_on(cancel.cancelled());
|
||
Err(ToolCallError::Failed("cancelled".into()))
|
||
}
|
||
}
|
||
let mut s = setup();
|
||
s.server.take().unwrap().stop();
|
||
let started = Arc::new(tokio::sync::Notify::new());
|
||
s.server = Some(
|
||
McpServer::start_with(
|
||
Arc::new(Waiting(started.clone())),
|
||
None,
|
||
&tokio::runtime::Handle::current(),
|
||
ServerOptions::default(),
|
||
)
|
||
.unwrap(),
|
||
);
|
||
let body = json!({"jsonrpc":"2.0","id":11,"method":"tools/call","params":{"name":"wait"}});
|
||
let auth = bearer(&s);
|
||
let headers = [&*auth, "Mcp-Session-Id: client-one"];
|
||
let call = post(&s, "/mcp", &headers, &body);
|
||
let cancel = async {
|
||
started.notified().await;
|
||
let notification = json!({"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":11}});
|
||
assert_eq!(post(&s, "/mcp", &[&bearer(&s), "Mcp-Session-Id: client-two"], ¬ification).await.0, 202);
|
||
assert_eq!(post(&s, "/mcp", &[&bearer(&s), "Mcp-Session-Id: client-one"], ¬ification).await.0, 202);
|
||
};
|
||
let ((status, body), ()) =
|
||
tokio::time::timeout(std::time::Duration::from_secs(5), async { tokio::join!(call, cancel) }).await.unwrap();
|
||
assert_eq!(status, 200);
|
||
assert_eq!(serde_json::from_str::<Value>(&body).unwrap()["result"]["isError"], true);
|
||
}
|
||
|
||
#[tokio::test(flavor = "multi_thread")]
|
||
async fn a_cancellation_that_arrives_before_the_call_is_remembered() {
|
||
let s = setup();
|
||
let auth = bearer(&s);
|
||
let headers = [auth.as_str(), "Mcp-Session-Id: early-cancel"];
|
||
let notification = json!({"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":8}});
|
||
assert_eq!(post(&s, "/mcp", &headers, ¬ification).await.0, 202);
|
||
let call = json!({"jsonrpc":"2.0","id":8,"method":"tools/call","params":{"name":"echo","arguments":{"text":"hi"}}});
|
||
let (_, body) = post(&s, "/mcp", &headers, &call).await;
|
||
assert_eq!(serde_json::from_str::<Value>(&body).unwrap()["result"]["isError"], true);
|
||
}
|
||
|
||
#[tokio::test(flavor = "multi_thread")]
|
||
async fn a_fixed_port_and_token_are_used_and_a_taken_port_falls_back_to_a_free_one() {
|
||
let mut s = setup();
|
||
s.server.take().unwrap().stop();
|
||
let free = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap().local_addr().unwrap().port();
|
||
let token = "ab".repeat(32);
|
||
let options = ServerOptions { port: Some(free), token: Some(token.clone()), ..Default::default() };
|
||
let registry = Arc::new(Registry { project: s.project.clone() });
|
||
let runtime = tokio::runtime::Handle::current();
|
||
s.server =
|
||
Some(McpServer::start_with(registry.clone(), Some(s.discovery.clone()), &runtime, options.clone()).unwrap());
|
||
assert_eq!((s.server().port(), s.server().token()), (free, token.as_str()));
|
||
assert!(s.server().port_unavailable().is_none());
|
||
assert_eq!(Discovery::read(&s.discovery).unwrap().port, free);
|
||
let list = rpc(&s, "tools/list", json!({})).await;
|
||
assert_eq!(list["result"]["tools"][0]["name"], "echo");
|
||
|
||
// The port is taken (by the first server): a second one listens elsewhere and says why.
|
||
let second = McpServer::start_with(registry, None, &runtime, options).unwrap();
|
||
assert_ne!(second.port(), free);
|
||
assert!(
|
||
second.port_unavailable().is_some_and(|why| why.contains(&free.to_string())),
|
||
"{:?}",
|
||
second.port_unavailable()
|
||
);
|
||
}
|
||
|
||
#[tokio::test(flavor = "multi_thread")]
|
||
async fn another_listen_address_is_used_and_one_not_on_this_computer_fails() {
|
||
let mut s = setup();
|
||
s.server.take().unwrap().stop();
|
||
let registry = Arc::new(Registry { project: s.project.clone() });
|
||
let runtime = tokio::runtime::Handle::current();
|
||
|
||
// Every address: clients here use loopback; other computers name the server by an address of it.
|
||
let every = ServerOptions { address: Some("0.0.0.0".parse().unwrap()), ..Default::default() };
|
||
s.server = Some(McpServer::start_with(registry.clone(), Some(s.discovery.clone()), &runtime, every).unwrap());
|
||
let port = s.server().port();
|
||
assert_eq!(s.server().address().to_string(), "0.0.0.0");
|
||
assert!(s.server().url(&s.project).starts_with(&format!("http://127.0.0.1:{port}/mcp?")));
|
||
assert_eq!(Discovery::read(&s.discovery).unwrap().address.to_string(), "127.0.0.1");
|
||
let ping = json!({ "jsonrpc": "2.0", "id": 1, "method": "ping" }).to_string();
|
||
let request = |host: String| {
|
||
format!(
|
||
"POST /mcp HTTP/1.1\r\nHost: {host}\r\n{}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{ping}",
|
||
bearer(&s),
|
||
ping.len()
|
||
)
|
||
};
|
||
assert_eq!(http(port, &request(format!("192.0.2.7:{port}"))).await.0, 200);
|
||
assert_eq!(http(port, &request(format!("evil.example:{port}"))).await.0, 403, "never a host name");
|
||
|
||
// Not an address of this computer: the server does not start, and says which address.
|
||
let elsewhere = ServerOptions { address: Some("192.0.2.1".parse().unwrap()), ..Default::default() };
|
||
let error = McpServer::start_with(registry, None, &runtime, elsewhere).err().expect("no such address here");
|
||
assert!(error.to_string().contains("192.0.2.1"), "{error}");
|
||
}
|
||
|
||
#[tokio::test(flavor = "multi_thread")]
|
||
async fn multiple_servers_sharing_app_data_route_by_project_and_survive_one_closing() {
|
||
let tmp = tempfile::tempdir().unwrap();
|
||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||
let (proj_a, proj_b) = (base.join("proj-a"), base.join("proj-b"));
|
||
std::fs::create_dir_all(&proj_a).unwrap();
|
||
std::fs::create_dir_all(&proj_b).unwrap();
|
||
let discovery = discovery_path(&base.join("app-data"));
|
||
let runtime = tokio::runtime::Handle::current();
|
||
|
||
let server_a = McpServer::start_with(
|
||
Arc::new(Registry { project: proj_a.clone() }),
|
||
Some(discovery.clone()),
|
||
&runtime,
|
||
ServerOptions::default(),
|
||
)
|
||
.unwrap();
|
||
let server_b = McpServer::start_with(
|
||
Arc::new(Registry { project: proj_b.clone() }),
|
||
Some(discovery.clone()),
|
||
&runtime,
|
||
ServerOptions::default(),
|
||
)
|
||
.unwrap();
|
||
|
||
let session = |text: &str| {
|
||
[
|
||
json!({ "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "protocolVersion": "2025-06-18", "clientInfo": { "name": "agent", "version": "1" } } }),
|
||
json!({ "jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": { "name": "echo", "arguments": { "text": text } } }),
|
||
]
|
||
.iter()
|
||
.map(|m| format!("{m}\n"))
|
||
.collect::<String>()
|
||
};
|
||
|
||
for (proj, tag) in [(&proj_a, "alpha"), (&proj_b, "beta")] {
|
||
let mut out = Vec::new();
|
||
stdio::bridge(&discovery, proj, session(tag).as_bytes(), &mut out).await.unwrap();
|
||
let mut replies: Vec<Value> =
|
||
String::from_utf8(out).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect();
|
||
replies.sort_by_key(|r| r["id"].as_i64());
|
||
assert!(replies[0]["result"]["instructions"].as_str().unwrap().contains(&proj.display().to_string()));
|
||
assert_eq!(replies[1]["result"]["content"][0]["text"], format!("{tag} in {}", proj.display()));
|
||
}
|
||
|
||
// Closing the newer server promotes the remaining server back to server.json.
|
||
server_b.stop();
|
||
assert_eq!(Discovery::read(&discovery).unwrap().port, server_a.port());
|
||
let mut out = Vec::new();
|
||
stdio::bridge(&discovery, &proj_a, session("still-here").as_bytes(), &mut out).await.unwrap();
|
||
let mut replies: Vec<Value> =
|
||
String::from_utf8(out).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect();
|
||
replies.sort_by_key(|r| r["id"].as_i64());
|
||
assert_eq!(replies[1]["result"]["content"][0]["text"], format!("still-here in {}", proj_a.display()));
|
||
|
||
server_a.stop();
|
||
assert!(!discovery.exists());
|
||
}
|
||
|
||
/// The stdio bridge started in `folder`, driven as MCP clients drive it: each request goes
|
||
/// out once the answer to the one before has come back.
|
||
struct Client {
|
||
input: tokio::io::DuplexStream,
|
||
output: tokio::io::Lines<tokio::io::BufReader<tokio::io::DuplexStream>>,
|
||
bridge: tokio::task::JoinHandle<std::io::Result<()>>,
|
||
id: u64,
|
||
}
|
||
|
||
impl Client {
|
||
fn start(discovery: &Path, folder: &Path) -> Self {
|
||
let (input, bridge_input) = tokio::io::duplex(1 << 16);
|
||
let (bridge_output, output) = tokio::io::duplex(1 << 16);
|
||
let (discovery, folder) = (discovery.to_owned(), folder.to_owned());
|
||
let bridge = tokio::spawn(async move {
|
||
stdio::bridge(&discovery, &folder, tokio::io::BufReader::new(bridge_input), bridge_output).await
|
||
});
|
||
Self { input, output: tokio::io::BufReader::new(output).lines(), bridge, id: 0 }
|
||
}
|
||
|
||
/// Sends a request without waiting for its answer; its id.
|
||
async fn send(&mut self, method: &str, params: Value) -> u64 {
|
||
self.id += 1;
|
||
self.notify(json!({ "jsonrpc": "2.0", "id": self.id, "method": method, "params": params })).await;
|
||
self.id
|
||
}
|
||
|
||
async fn notify(&mut self, message: Value) {
|
||
self.input.write_all(format!("{message}\n").as_bytes()).await.unwrap();
|
||
}
|
||
|
||
async fn answer(&mut self, id: u64) -> Value {
|
||
let answer = async {
|
||
loop {
|
||
let line = self.output.next_line().await.unwrap().expect("the bridge answers");
|
||
let reply: Value = serde_json::from_str(&line).unwrap();
|
||
if reply["id"] == id {
|
||
return reply;
|
||
}
|
||
}
|
||
};
|
||
tokio::time::timeout(std::time::Duration::from_secs(10), answer).await.expect("an answer in time")
|
||
}
|
||
|
||
async fn ask(&mut self, method: &str, params: Value) -> Value {
|
||
let id = self.send(method, params).await;
|
||
self.answer(id).await
|
||
}
|
||
|
||
async fn close(self) {
|
||
let Self { input, output, bridge, .. } = self;
|
||
drop(input);
|
||
bridge.await.unwrap().unwrap();
|
||
drop(output);
|
||
}
|
||
}
|
||
|
||
fn start_in(discovery: &Path, registry: impl ToolRegistry) -> McpServer {
|
||
let runtime = tokio::runtime::Handle::current();
|
||
McpServer::start_with(Arc::new(registry), Some(discovery.to_owned()), &runtime, ServerOptions::default()).unwrap()
|
||
}
|
||
|
||
/// A temporary folder holding `folders` (each with a `src`), and the discovery file of the
|
||
/// servers that share its data directory.
|
||
fn layout(folders: &[&str]) -> (tempfile::TempDir, PathBuf, PathBuf) {
|
||
let tmp = tempfile::tempdir().unwrap();
|
||
let base = dunce::canonicalize(tmp.path()).unwrap();
|
||
for folder in folders {
|
||
std::fs::create_dir_all(base.join(folder).join("src")).unwrap();
|
||
}
|
||
let discovery = discovery_path(&base.join("app-data"));
|
||
(tmp, base, discovery)
|
||
}
|
||
|
||
impl WithBackground {
|
||
/// A window on `open` and `background` served without one.
|
||
fn serving(open: &Path, background: &Path) -> Self {
|
||
Self { open: open.to_owned(), background: vec![background.to_owned()], remote: None }
|
||
}
|
||
}
|
||
|
||
/// What an MCP client started in a folder of `proj-b` gets when two servers share the
|
||
/// discovery directory: A has `proj-a` in a window, B serves `proj-b` in the background.
|
||
/// Each order makes the other server the one in `server.json`.
|
||
#[tokio::test(flavor = "multi_thread")]
|
||
async fn the_bridge_sends_a_folder_to_the_process_that_serves_it_in_either_order() {
|
||
for b_first in [false, true] {
|
||
let (_tmp, base, discovery) = layout(&["proj-a", "proj-b", "proj-c"]);
|
||
let (proj_a, proj_b, proj_c) = (base.join("proj-a"), base.join("proj-b"), base.join("proj-c"));
|
||
let a = || Registry { project: proj_a.clone() };
|
||
let b = || WithBackground::serving(&proj_c, &proj_b);
|
||
let servers = if b_first {
|
||
[start_in(&discovery, b()), start_in(&discovery, a())]
|
||
} else {
|
||
[start_in(&discovery, a()), start_in(&discovery, b())]
|
||
};
|
||
|
||
let mut client = Client::start(&discovery, &proj_b.join("src"));
|
||
let init = client.ask("initialize", json!({ "protocolVersion": "2025-06-18" })).await;
|
||
let instructions = init["result"]["instructions"].as_str().unwrap();
|
||
assert!(instructions.contains(proj_b.to_str().unwrap()), "b_first {b_first}: {instructions}");
|
||
let list = client.ask("tools/list", json!({})).await;
|
||
assert_eq!(list["result"]["tools"][0]["description"], format!("Names {}", proj_b.display()), "{list}");
|
||
let call = client.ask("tools/call", json!({ "name": "where" })).await;
|
||
assert_eq!(call["result"]["structuredContent"]["project"], json!(proj_b), "{call}");
|
||
client.close().await;
|
||
for server in servers {
|
||
server.stop();
|
||
}
|
||
}
|
||
}
|
||
|
||
/// A client started in `work`, a folder neither server serves: the tools of the server
|
||
/// `initialize` picked, and each call goes where its `projectPath` is served.
|
||
#[tokio::test(flavor = "multi_thread")]
|
||
async fn a_bridge_in_a_folder_no_process_serves_lists_tools_and_routes_each_call_by_project_path() {
|
||
for b_first in [false, true] {
|
||
let (_tmp, base, discovery) = layout(&["proj-a", "proj-c", "work/repo"]);
|
||
let (proj_a, proj_c, work) = (base.join("proj-a"), base.join("proj-c"), base.join("work"));
|
||
let repo = work.join("repo");
|
||
let a = || Registry { project: proj_a.clone() };
|
||
let b = || WithBackground::serving(&proj_c, &repo);
|
||
// The server started last is in `server.json`; with neither serving the folder,
|
||
// `initialize` settles on it.
|
||
let (servers, listed) = if b_first {
|
||
([start_in(&discovery, b()), start_in(&discovery, a())], "everything")
|
||
} else {
|
||
([start_in(&discovery, a()), start_in(&discovery, b())], "anything")
|
||
};
|
||
|
||
let mut client = Client::start(&discovery, &work);
|
||
let init = client.ask("initialize", json!({ "protocolVersion": "2025-06-18" })).await;
|
||
let instructions = init["result"]["instructions"].as_str().unwrap();
|
||
assert!(instructions.contains("no project of its own"), "{instructions}");
|
||
let list = client.ask("tools/list", json!({})).await;
|
||
assert_eq!(list["result"]["tools"][0]["name"], listed, "b_first {b_first}: {list}");
|
||
|
||
let in_repo = json!({ "name": "echo", "arguments": { "text": "x", "projectPath": repo.join("src") } });
|
||
let call = client.ask("tools/call", in_repo).await;
|
||
assert_eq!(call["result"]["structuredContent"]["project"], json!(repo), "{call}");
|
||
let in_a = json!({ "name": "echo", "arguments": { "text": "x", "projectPath": proj_a } });
|
||
let call = client.ask("tools/call", in_a).await;
|
||
assert_eq!(call["result"]["content"][0]["text"], format!("x in {}", proj_a.display()), "{call}");
|
||
let unnamed = client.ask("tools/call", json!({ "name": "echo", "arguments": { "text": "x" } })).await;
|
||
assert_eq!(unnamed["error"]["code"], -32001, "{unnamed}");
|
||
// A call sent to the other server doesn't move the connection there.
|
||
let list = client.ask("tools/list", json!({})).await;
|
||
assert_eq!(list["result"]["tools"][0]["name"], listed, "b_first {b_first}: {list}");
|
||
client.close().await;
|
||
for server in servers {
|
||
server.stop();
|
||
}
|
||
}
|
||
}
|
||
|
||
/// The server `initialize` picked stops, or one that serves the folder starts later: the
|
||
/// next message picks again, as `initialize` does.
|
||
#[tokio::test(flavor = "multi_thread")]
|
||
async fn the_bridge_picks_the_server_again_when_the_servers_change() {
|
||
let (_tmp, base, discovery) = layout(&["proj-a", "proj-b", "proj-c"]);
|
||
let (proj_a, proj_b, proj_c) = (base.join("proj-a"), base.join("proj-b"), base.join("proj-c"));
|
||
let a = || Registry { project: proj_a.clone() };
|
||
let b = || WithBackground::serving(&proj_c, &proj_b);
|
||
let serving_b = format!("Names {}", proj_b.display());
|
||
|
||
// Only A runs at `initialize`; B starts afterwards.
|
||
let server_a = start_in(&discovery, a());
|
||
let mut client = Client::start(&discovery, &proj_b.join("src"));
|
||
client.ask("initialize", json!({ "protocolVersion": "2025-06-18" })).await;
|
||
let server_b = start_in(&discovery, b());
|
||
let list = client.ask("tools/list", json!({})).await;
|
||
assert_eq!(list["result"]["tools"][0]["description"], serving_b, "a server started later: {list}");
|
||
|
||
// B restarts, and A restarts after it, so A is first in the discovery file.
|
||
server_b.stop();
|
||
let server_b = start_in(&discovery, b());
|
||
server_a.stop();
|
||
let server_a = start_in(&discovery, a());
|
||
let list = client.ask("tools/list", json!({})).await;
|
||
assert_eq!(list["result"]["tools"][0]["description"], serving_b, "the picked server restarted: {list}");
|
||
client.close().await;
|
||
server_a.stop();
|
||
server_b.stop();
|
||
}
|
||
|
||
/// A server restarted on the port it had (a fixed port in the settings) is another server: one
|
||
/// that didn't serve the folder may serve it now.
|
||
#[tokio::test(flavor = "multi_thread")]
|
||
async fn the_bridge_picks_the_server_again_after_a_restart_on_the_same_port() {
|
||
let (_tmp, base, discovery) = layout(&["proj-a", "proj-b", "proj-c"]);
|
||
let (proj_a, proj_b, proj_c) = (base.join("proj-a"), base.join("proj-b"), base.join("proj-c"));
|
||
// Neither serves `proj-b` at `initialize`, which settles on A, the server started last.
|
||
let server_b = start_in(&discovery, WithBackground { open: proj_c.clone(), background: Vec::new(), remote: None });
|
||
let port = server_b.port();
|
||
let server_a = start_in(&discovery, Registry { project: proj_a.clone() });
|
||
let mut client = Client::start(&discovery, &proj_b.join("src"));
|
||
client.ask("initialize", json!({ "protocolVersion": "2025-06-18" })).await;
|
||
let list = client.ask("tools/list", json!({})).await;
|
||
assert_eq!(list["result"]["tools"][0]["name"], "everything", "{list}");
|
||
|
||
server_b.stop();
|
||
// stop signals the accept task; the listener is closed asynchronously. Wait for
|
||
// the old port to be released, as the IDE does before restarting its server.
|
||
tokio::time::timeout(std::time::Duration::from_secs(5), async {
|
||
while std::net::TcpListener::bind(("127.0.0.1", port)).is_err() {
|
||
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
|
||
}
|
||
})
|
||
.await
|
||
.expect("the stopped server should release its port");
|
||
let server_b = McpServer::start_with(
|
||
Arc::new(WithBackground::serving(&proj_c, &proj_b)),
|
||
Some(discovery.clone()),
|
||
&tokio::runtime::Handle::current(),
|
||
ServerOptions { port: Some(port), ..Default::default() },
|
||
)
|
||
.unwrap();
|
||
assert_eq!(server_b.port(), port, "{:?}", server_b.port_unavailable());
|
||
let list = client.ask("tools/list", json!({})).await;
|
||
assert_eq!(list["result"]["tools"][0]["description"], format!("Names {}", proj_b.display()), "{list}");
|
||
client.close().await;
|
||
server_a.stop();
|
||
server_b.stop();
|
||
}
|
||
|
||
/// Holds every call until it is cancelled: a window on `open`, `background` served without one.
|
||
struct Holding {
|
||
open: PathBuf,
|
||
background: PathBuf,
|
||
}
|
||
|
||
impl ToolRegistry for Holding {
|
||
fn projects(&self) -> Vec<PathBuf> {
|
||
vec![self.open.clone()]
|
||
}
|
||
fn resolve(&self, path: &Path, _: Option<&Path>) -> Option<PathBuf> {
|
||
path.starts_with(&self.background).then(|| self.background.clone())
|
||
}
|
||
fn tools(&self, _: &Path) -> Result<Vec<Tool>, String> {
|
||
Ok(vec![named("hold")])
|
||
}
|
||
fn call(&self, _: &Path, _: &str, _: &str, cancel: ide_mcp::CancellationToken) -> Result<String, ToolCallError> {
|
||
tokio::runtime::Handle::current().block_on(cancel.cancelled());
|
||
Err(ToolCallError::Failed("cancelled".into()))
|
||
}
|
||
}
|
||
|
||
/// The connection is A's, and a call whose `projectPath` B serves runs in B: its
|
||
/// cancellation reaches B.
|
||
#[tokio::test(flavor = "multi_thread")]
|
||
async fn a_cancellation_reaches_the_server_that_runs_the_call() {
|
||
let (_tmp, base, discovery) = layout(&["proj-a", "proj-b", "proj-c"]);
|
||
let (proj_a, proj_b, proj_c) = (base.join("proj-a"), base.join("proj-b"), base.join("proj-c"));
|
||
let server_b = start_in(&discovery, Holding { open: proj_c, background: proj_b.clone() });
|
||
let server_a = start_in(&discovery, Registry { project: proj_a.clone() });
|
||
|
||
let mut client = Client::start(&discovery, &proj_a);
|
||
let init = client.ask("initialize", json!({ "protocolVersion": "2025-06-18" })).await;
|
||
assert!(init["result"]["instructions"].as_str().unwrap().contains(proj_a.to_str().unwrap()), "{init}");
|
||
let call = client.send("tools/call", json!({ "name": "hold", "arguments": { "projectPath": proj_b } })).await;
|
||
client
|
||
.notify(json!({ "jsonrpc": "2.0", "method": "notifications/cancelled", "params": { "requestId": call } }))
|
||
.await;
|
||
let answer = client.answer(call).await;
|
||
assert_eq!(answer["result"]["isError"], true, "{answer}");
|
||
client.close().await;
|
||
server_a.stop();
|
||
server_b.stop();
|
||
}
|
||
|
||
/// An OpenIDEA older than `openidea/servesFolder`, registered in `discovery`: it answers
|
||
/// "method not found" to that, and "not open" to `tools/list` and `tools/call` for a folder
|
||
/// outside `serves`.
|
||
async fn fake_older_ide(discovery: &Path, serves: Option<PathBuf>) -> tokio::task::JoinHandle<()> {
|
||
use http_body_util::{BodyExt, Full};
|
||
let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
|
||
let port = listener.local_addr().unwrap().port();
|
||
let server = tokio::spawn(async move {
|
||
while let Ok((stream, _)) = listener.accept().await {
|
||
let serves = serves.clone();
|
||
let service = hyper::service::service_fn(move |request: hyper::Request<hyper::body::Incoming>| {
|
||
let serves = serves.clone();
|
||
async move {
|
||
let query = request.uri().query().unwrap_or_default().to_owned();
|
||
let folder = query.strip_prefix("project=").unwrap_or_default();
|
||
let folder =
|
||
PathBuf::from(percent_encoding::percent_decode_str(folder).decode_utf8_lossy().as_ref());
|
||
let body = request.into_body().collect().await.unwrap().to_bytes();
|
||
let message: Value = serde_json::from_slice(&body).unwrap();
|
||
let served = serves.as_ref().is_some_and(|root| folder.starts_with(root));
|
||
let id = message["id"].clone();
|
||
let reply = match message["method"].as_str().unwrap_or_default() {
|
||
_ if id.is_null() => None,
|
||
"initialize" => Some(json!({ "jsonrpc": "2.0", "id": id, "result": {
|
||
"protocolVersion": "2025-06-18", "capabilities": { "tools": {} },
|
||
"serverInfo": { "name": "OpenIDEA", "version": "0.1.0" },
|
||
"instructions": "an older OpenIDEA" } })),
|
||
"tools/list" if served => {
|
||
Some(json!({ "jsonrpc": "2.0", "id": id, "result": { "tools": [] } }))
|
||
}
|
||
"tools/call" if served => Some(json!({ "jsonrpc": "2.0", "id": id, "result": {
|
||
"content": [{ "type": "text", "text": "older" }], "isError": false } })),
|
||
"tools/list" | "tools/call" => Some(
|
||
json!({ "jsonrpc": "2.0", "id": id, "error": { "code": -32001, "message": "not open" } }),
|
||
),
|
||
_ => Some(
|
||
json!({ "jsonrpc": "2.0", "id": id, "error": { "code": -32601, "message": "no method" } }),
|
||
),
|
||
};
|
||
let response = match reply {
|
||
Some(reply) => hyper::Response::builder()
|
||
.header("content-type", "application/json")
|
||
.body(Full::new(bytes::Bytes::from(reply.to_string()))),
|
||
None => hyper::Response::builder().status(202).body(Full::new(bytes::Bytes::new())),
|
||
};
|
||
Ok::<_, std::convert::Infallible>(response.unwrap())
|
||
}
|
||
});
|
||
tokio::spawn(async move {
|
||
let io = hyper_util::rt::TokioIo::new(stream);
|
||
let _ = hyper::server::conn::http1::Builder::new().serve_connection(io, service).await;
|
||
});
|
||
}
|
||
});
|
||
// Written once it listens, so the stale-entry sweep of the next server keeps it.
|
||
let info = Discovery {
|
||
address: std::net::Ipv4Addr::LOCALHOST.into(),
|
||
port,
|
||
token: "test-token-older".into(),
|
||
pid: std::process::id(),
|
||
version: "0.1.0".into(),
|
||
};
|
||
info.write(discovery).unwrap();
|
||
server
|
||
}
|
||
|
||
#[tokio::test(flavor = "multi_thread")]
|
||
async fn an_older_ide_without_serves_folder_is_probed_with_tools_list() {
|
||
for older_serves in [false, true] {
|
||
let (_tmp, base, discovery) = layout(&["proj-c", "inventory"]);
|
||
let (proj_c, folder) = (base.join("proj-c"), base.join("inventory"));
|
||
// Either way the server that doesn't serve the folder is in `server.json`.
|
||
let (older, real) = if older_serves {
|
||
let older = fake_older_ide(&discovery, Some(folder.clone())).await;
|
||
(older, start_in(&discovery, Registry { project: proj_c.clone() }))
|
||
} else {
|
||
let real = start_in(&discovery, WithBackground::serving(&proj_c, &folder));
|
||
(fake_older_ide(&discovery, None).await, real)
|
||
};
|
||
|
||
let mut client = Client::start(&discovery, &folder.join("src"));
|
||
let init = client.ask("initialize", json!({ "protocolVersion": "2025-06-18" })).await;
|
||
let instructions = init["result"]["instructions"].as_str().unwrap();
|
||
let expected = if older_serves { "an older OpenIDEA".to_owned() } else { folder.display().to_string() };
|
||
assert!(instructions.contains(&expected), "older_serves {older_serves}: {instructions}");
|
||
let call = client.ask("tools/call", json!({ "name": "where" })).await;
|
||
let answered = match older_serves {
|
||
true => call["result"]["content"][0]["text"] == "older",
|
||
false => call["result"]["structuredContent"]["project"] == json!(folder),
|
||
};
|
||
assert!(answered, "older_serves {older_serves}: {call}");
|
||
client.close().await;
|
||
real.stop();
|
||
older.abort();
|
||
}
|
||
}
|