Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(mcp): scope user stdio clients by workspace

vastsa05f1e8ce1579
diff --git a/apps/desktop/electron/main/user-mcp.ts b/apps/desktop/electron/main/user-mcp.ts
index e798a2321..8aee65164 100644
--- a/apps/desktop/electron/main/user-mcp.ts
+++ b/apps/desktop/electron/main/user-mcp.ts
@@ -1,4 +1,5 @@
import { homedir } from "node:os";
+import { resolve } from "node:path";
import {
isActiveInProject,
type McpServerRecord,
@@ -12,11 +13,12 @@ import { McpCallRegistry } from "./mcp-call-registry.ts";
* MCP servers the user configured directly, with no plugin around them.
*
* host-core owns the records; this runtime owns the processes and sockets. A
- * server is connected the first time a session that can see it is assembled,
- * and its tool list is cached afterwards, so opening a second session on the
- * same project costs nothing. Editing or disabling a server drops its
- * connection. Previously discovered names survive transport loss as routing
- * hints, never as permission to call a tool absent from the new handshake.
+ * server is connected the first time a session that can see it is assembled.
+ * Stdio clients are cached per workspace, so another session in the same
+ * project reuses the process while a different project gets its own cwd.
+ * Editing or disabling a server drops all of its connections. Previously
+ * discovered names survive transport loss as routing hints, never as
+ * permission to call a tool absent from the new handshake.
*/
export type UserMcpToolDescriptor = {
/** `mcp_<serverId>_<tool>`, the name the model calls. */
@@ -60,11 +62,14 @@ export type UserMcpRuntimeOptions = {
};
type Entry = {
+ key: string;
record: McpServerRecord;
client: UserMcpClient;
status: McpServerStatus;
connecting?: Promise<McpTool[]>;
oauthToken?: string | null;
+ activeCalls: number;
+ lastUsedAt: number;
};
/**
@@ -75,6 +80,7 @@ type Entry = {
* sixteen MCP servers has a configuration problem, not a limit problem.
*/
const MAX_ACTIVE_SERVERS = 16;
+const MAX_CACHED_CONNECTIONS = MAX_ACTIVE_SERVERS * 4;
export class UserMcpRuntime {
private entries = new Map<string, Entry>();
@@ -82,7 +88,7 @@ export class UserMcpRuntime {
private readonly calls = new McpCallRegistry();
// Routing identity must survive a transport clearing its own tools on close.
// These names are hints only: dispatch revalidates the fresh handshake list.
- private discoveredTools = new Map<string, McpTool[]>();
+ private discoveredTools = new Map<string, Set<string>>();
private records: McpServerRecord[] = [];
private options: UserMcpRuntimeOptions;
@@ -103,11 +109,11 @@ export class UserMcpRuntime {
for (const id of this.discoveredTools.keys()) {
if (!byId.has(id)) this.discoveredTools.delete(id);
}
- for (const [id, entry] of [...this.entries]) {
- const next = byId.get(id);
+ for (const [key, entry] of [...this.entries]) {
+ const next = byId.get(entry.record.id);
if (!next || configurationChanged(entry.record, next)) {
entry.client.close();
- this.entries.delete(id);
+ this.entries.delete(key);
continue;
}
entry.record = next;
@@ -125,15 +131,15 @@ export class UserMcpRuntime {
/** Confirm ready remote connections when the settings page refreshes. */
async refreshStatuses(): Promise<McpServerStatus[]> {
- await Promise.all([...this.entries].map(async ([id, entry]) => {
+ await Promise.all([...this.entries].map(async ([key, entry]) => {
if (entry.record.transport === "stdio" || entry.status.state !== "ready") return;
- let pending = this.statusRefreshes.get(id);
+ let pending = this.statusRefreshes.get(key);
if (!pending) {
pending = (async () => {
try {
await entry.client.ping();
} catch (error) {
- if (this.entries.get(id) !== entry) return;
+ if (this.entries.get(key) !== entry) return;
// A settings probe must not abort a tool call already in flight.
// Test connection will close this client before retrying.
const message = error instanceof Error ? error.message : "mcp server did not respond";
@@ -146,19 +152,21 @@ export class UserMcpRuntime {
};
}
})();
- this.statusRefreshes.set(id, pending);
+ this.statusRefreshes.set(key, pending);
}
try {
await pending;
} finally {
- if (this.statusRefreshes.get(id) === pending) this.statusRefreshes.delete(id);
+ if (this.statusRefreshes.get(key) === pending) this.statusRefreshes.delete(key);
}
}));
return this.listStatuses();
}
statusFor(serverId: string): McpServerStatus {
- const entry = this.entries.get(serverId);
+ const entry = [...this.entries.values()]
+ .filter((candidate) => candidate.record.id === serverId)
+ .sort((left, right) => right.status.updatedAt - left.status.updatedAt)[0];
if (entry) return { ...entry.status };
return {
serverId,
@@ -184,7 +192,10 @@ export class UserMcpRuntime {
skipped: active.length - admitted.length,
});
}
- const lists = await Promise.all(admitted.map((record) => this.connect(record)));
+ const lists = await Promise.all(admitted.map(async (record) => {
+ const result = await this.connect(record, projectPath);
+ return result.tools;
+ }));
const out: UserMcpToolDescriptor[] = [];
admitted.forEach((record, index) => {
for (const tool of lists[index]) {
@@ -239,44 +250,52 @@ export class UserMcpRuntime {
{ errorCode: "TOOL_NOT_FOUND" },
);
}
- await this.connect(record);
- // Configuration or scope can change while the handshake is in flight.
- const current = this.records.find((entry) => entry.id === found.serverId);
- if (!current || !isActiveInProject(current, projectPath)) {
- throw Object.assign(
- new Error(`mcp server ${found.serverId} is not active for this session`),
- { errorCode: "TOOL_NOT_FOUND" },
- );
- }
- const entry = this.entries.get(found.serverId);
- if (
- !entry || configurationChanged(record, current) ||
- entry.status.state !== "ready" || !entry.client.isConnected()
- ) {
+ const { entry } = await this.connect(record, projectPath, true);
+ if (!entry) {
throw Object.assign(new Error(`mcp server ${found.serverId} is unavailable`), {
errorCode: "UNAVAILABLE",
});
}
- if (!entry.client.getTools().some((tool) => tool.name === found.toolName)) {
- throw Object.assign(new Error(`unknown mcp tool: ${fullName}`), {
- errorCode: "TOOL_NOT_FOUND",
- });
- }
- // Do not retry tools/call: a failed response may have followed a mutation.
try {
- return await entry.client.callTool(found.toolName, args, signal);
- } catch (error) {
- const msg = (error as Error).message || "";
- if (msg.includes("401") || (error as { status?: number }).status === 401) {
- entry.status = {
- ...entry.status,
- state: "failed",
- authRequired: true,
- message: msg.slice(0, 500),
- updatedAt: Date.now(),
- };
+ // Configuration or scope can change while the handshake is in flight.
+ const current = this.records.find((entry) => entry.id === found.serverId);
+ if (!current || !isActiveInProject(current, projectPath)) {
+ throw Object.assign(
+ new Error(`mcp server ${found.serverId} is not active for this session`),
+ { errorCode: "TOOL_NOT_FOUND" },
+ );
+ }
+ if (
+ configurationChanged(record, current) ||
+ entry.status.state !== "ready" || !entry.client.isConnected()
+ ) {
+ throw Object.assign(new Error(`mcp server ${found.serverId} is unavailable`), {
+ errorCode: "UNAVAILABLE",
+ });
+ }
+ if (!entry.client.getTools().some((tool) => tool.name === found.toolName)) {
+ throw Object.assign(new Error(`unknown mcp tool: ${fullName}`), {
+ errorCode: "TOOL_NOT_FOUND",
+ });
+ }
+ // Do not retry tools/call: a failed response may have followed a mutation.
+ try {
+ return await entry.client.callTool(found.toolName, args, signal);
+ } catch (error) {
+ const msg = (error as Error).message || "";
+ if (msg.includes("401") || (error as { status?: number }).status === 401) {
+ entry.status = {
+ ...entry.status,
+ state: "failed",
+ authRequired: true,
+ message: msg.slice(0, 500),
+ updatedAt: Date.now(),
+ };
+ }
+ throw error;
}
- throw error;
+ } finally {
+ entry.activeCalls -= 1;
}
}
@@ -298,18 +317,20 @@ export class UserMcpRuntime {
}
// Force a fresh handshake so a fixed command is retried rather than
// reporting the cached failure.
- this.entries.get(serverId)?.client.close();
- this.entries.delete(serverId);
- await this.connect(record);
+ const key = connectionKey(record, null);
+ this.entries.get(key)?.client.close();
+ this.entries.delete(key);
+ await this.connect(record, null);
return this.statusFor(serverId);
}
/** Drop a cached connection and tools for a server. */
invalidate(serverId: string): void {
- const existing = this.entries.get(serverId);
- if (existing) {
- existing.client.close();
- this.entries.delete(serverId);
+ for (const [key, entry] of [...this.entries]) {
+ if (entry.record.id === serverId) {
+ entry.client.close();
+ this.entries.delete(key);
+ }
}
this.discoveredTools.delete(serverId);
}
@@ -319,6 +340,7 @@ export class UserMcpRuntime {
this.calls.cancelAll();
for (const entry of this.entries.values()) entry.client.close();
this.entries.clear();
+ this.statusRefreshes.clear();
this.discoveredTools.clear();
}
@@ -326,24 +348,22 @@ export class UserMcpRuntime {
this.calls.cancelSession(sessionId);
}
- private findTool(fullName: string): UserMcpToolDescriptor | undefined {
+ private findTool(fullName: string): { serverId: string; toolName: string } | undefined {
for (const [serverId, tools] of this.discoveredTools) {
- for (const tool of tools) {
- if (userMcpToolName(serverId, tool.name) === fullName) {
- return {
- fullName,
- serverId,
- toolName: tool.name,
- description: tool.description ?? tool.name,
- schema: tool.inputSchema,
- };
+ for (const toolName of tools) {
+ if (userMcpToolName(serverId, toolName) === fullName) {
+ return { serverId, toolName };
}
}
}
return undefined;
}
- private async connect(record: McpServerRecord): Promise<McpTool[]> {
+ private async connect(
+ record: McpServerRecord,
+ projectPath: string | null | undefined = null,
+ pin = false,
+ ): Promise<{ tools: McpTool[]; entry?: Entry }> {
let oauthToken: string | null = null;
if (record.transport === "http" && this.options.oauth) {
try {
@@ -353,25 +373,48 @@ export class UserMcpRuntime {
}
}
- let existing = this.entries.get(record.id);
+ const key = connectionKey(record, projectPath);
+ let existing = this.entries.get(key);
if (existing && record.transport === "http" && existing.oauthToken !== oauthToken) {
existing.client.close();
- this.entries.delete(record.id);
+ this.entries.delete(key);
existing = undefined;
}
- if (existing?.connecting) return existing.connecting;
- if (existing?.client.isConnected()) return existing.client.getTools();
+ if (!existing && !this.makeRoom()) {
+ this.options.log?.("warn", "user mcp connection cache is full", {
+ serverId: record.id,
+ limit: MAX_CACHED_CONNECTIONS,
+ });
+ return { tools: [] };
+ }
+
+ if (existing?.connecting) {
+ if (pin) existing.activeCalls += 1;
+ existing.lastUsedAt = Date.now();
+ return { tools: await existing.connecting, entry: existing };
+ }
+ if (existing?.client.isConnected()) {
+ if (pin) existing.activeCalls += 1;
+ existing.lastUsedAt = Date.now();
+ return { tools: existing.client.getTools(), entry: existing };
+ }
// A server that already failed its handshake this run stays failed until the
// user edits it or asks for a test, so every session assembly does not pay
// the connect timeout again.
- if (existing?.status.state === "failed") return [];
+ if (existing?.status.state === "failed") {
+ if (pin) existing.activeCalls += 1;
+ existing.lastUsedAt = Date.now();
+ return { tools: [], entry: existing };
+ }
- const entry = existing ?? this.createEntry(record, oauthToken);
+ const entry = existing ?? this.createEntry(record, oauthToken, key, projectPath);
+ if (pin) entry.activeCalls += 1;
+ entry.lastUsedAt = Date.now();
entry.connecting = this.handshake(record, entry).finally(() => {
entry.connecting = undefined;
});
- return entry.connecting;
+ return { tools: await entry.connecting, entry };
}
private async handshake(record: McpServerRecord, entry: Entry): Promise<McpTool[]> {
@@ -383,11 +426,13 @@ export class UserMcpRuntime {
try {
const tools = await entry.client.connect();
// An edited/deleted record must not resurrect a discarded connection.
- if (this.entries.get(record.id) !== entry) {
+ if (this.entries.get(entry.key) !== entry) {
entry.client.close();
return [];
}
- this.discoveredTools.set(record.id, [...tools]);
+ const catalog = this.discoveredTools.get(record.id) ?? new Set<string>();
+ for (const tool of tools) catalog.add(tool.name);
+ this.discoveredTools.set(record.id, catalog);
entry.status = {
serverId: record.id,
state: "ready",
@@ -416,7 +461,12 @@ export class UserMcpRuntime {
}
}
- private createEntry(record: McpServerRecord, oauthToken?: string | null): Entry {
+ private createEntry(
+ record: McpServerRecord,
+ oauthToken: string | null | undefined,
+ key: string,
+ projectPath: string | null | undefined,
+ ): Entry {
const headers = {
...(record.headers ?? {}),
...(oauthToken ? { Authorization: `Bearer ${oauthToken}` } : {}),
@@ -426,9 +476,9 @@ export class UserMcpRuntime {
? record.timeoutSeconds * 1000
: undefined;
const client = this.options.createClient({
- // No plugin owns this server; `rootPath` is only the child's cwd, and the
- // user's own command may live anywhere on the machine.
- rootPath: homedir(),
+ // Stdio servers inherit the session workspace as their cwd. HTTP
+ // transports do not spawn a child and keep the existing home default.
+ rootPath: record.transport === "stdio" ? workspacePath(projectPath) : homedir(),
commandPolicy: "trusted",
server: {
id: record.id,
@@ -448,9 +498,12 @@ export class UserMcpRuntime {
discoveryTimeoutMs: customTimeoutMs ? Math.max(customTimeoutMs, this.options.discoveryTimeoutMs ?? 0) : this.options.discoveryTimeoutMs,
});
const entry: Entry = {
+ key,
record,
client,
oauthToken,
+ activeCalls: 0,
+ lastUsedAt: Date.now(),
status: {
serverId: record.id,
state: "idle",
@@ -458,9 +511,35 @@ export class UserMcpRuntime {
updatedAt: Date.now(),
},
};
- this.entries.set(record.id, entry);
+ this.entries.set(key, entry);
return entry;
}
+
+ private makeRoom(): boolean {
+ if (this.entries.size < MAX_CACHED_CONNECTIONS) return true;
+ const candidate = [...this.entries.values()]
+ .filter((entry) =>
+ !entry.connecting &&
+ entry.activeCalls === 0 &&
+ !this.statusRefreshes.has(entry.key)
+ )
+ .sort((left, right) => left.lastUsedAt - right.lastUsedAt)[0];
+ if (!candidate) return false;
+ candidate.client.close();
+ this.entries.delete(candidate.key);
+ return true;
+ }
+}
+
+function workspacePath(projectPath: string | null | undefined): string {
+ return projectPath ? resolve(projectPath) : homedir();
+}
+
+function connectionKey(record: McpServerRecord, projectPath: string | null | undefined): string {
+ if (record.transport !== "stdio") return JSON.stringify([record.id, "http"]);
+ const rootPath = workspacePath(projectPath);
+ const identity = process.platform === "win32" ? rootPath.toLowerCase() : rootPath;
+ return JSON.stringify([record.id, identity]);
}
/**
diff --git a/apps/desktop/test/user-mcp.test.mjs b/apps/desktop/test/user-mcp.test.mjs
index 4f8b01a71..7e55cdd93 100644
--- a/apps/desktop/test/user-mcp.test.mjs
+++ b/apps/desktop/test/user-mcp.test.mjs
@@ -1,7 +1,7 @@
import assert from "node:assert/strict";
import test from "node:test";
-import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
-import { tmpdir } from "node:os";
+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
+import { homedir, tmpdir } from "node:os";
import { join } from "node:path";
import { UserMcpRuntime, configurationChanged } from "../electron/main/user-mcp.ts";
@@ -39,7 +39,12 @@ function handle(msg) {
jsonrpc: "2.0",
id: msg.id,
result: {
- tools: [{ name: "lookup", description: "Look something up" }, { name: "ping" }],
+ tools: [
+ { name: "lookup", description: "Look something up" },
+ { name: "ping" },
+ ...(process.env.STUB_REPORT_CWD ? [{ name: "cwd" }] : []),
+ ...(process.cwd() === process.env.STUB_TOOL_ONLY_IN_CWD ? [{ name: "project_only" }] : []),
+ ],
// A server that keeps handing back the same cursor can never be listed
// to its last page, so the client has to refuse it.
...(process.env.STUB_REPEAT_CURSOR ? { nextCursor: "more" } : {}),
@@ -52,7 +57,14 @@ function handle(msg) {
send({
jsonrpc: "2.0",
id: msg.id,
- result: { content: [{ type: "text", text: tag + ":" + msg.params.name }] },
+ result: {
+ content: [{
+ type: "text",
+ text: msg.params.name === "cwd"
+ ? process.cwd() + "|" + process.pid
+ : tag + ":" + msg.params.name,
+ }],
+ },
});
return;
}
@@ -66,6 +78,10 @@ function stubDir() {
return dir;
}
+function projectDir(name = "project") {
+ return realpathSync(mkdtempSync(join(tmpdir(), `pi-user-mcp-${name}-`)));
+}
+
/** A saved record for the stub, scoped globally unless told otherwise. */
function stubRecord(dir, overrides = {}) {
return {
@@ -95,10 +111,11 @@ function runtime(t, options = {}) {
test("a global server contributes mcp_-prefixed tools to any session", async (t) => {
const dir = stubDir();
+ const projectPath = projectDir();
const rt = runtime(t);
rt.setRecords([stubRecord(dir)]);
- const tools = await rt.toolsForProject("/repo");
+ const tools = await rt.toolsForProject(projectPath);
assert.deepEqual(
tools.map((tool) => tool.fullName),
["mcp_stub_lookup", "mcp_stub_ping"],
@@ -113,6 +130,90 @@ test("a global server contributes mcp_-prefixed tools to any session", async (t)
assert.equal((await rt.toolsForProject(null)).length, 2);
});
+test("a stdio server runs from and is reused only within its session workspace", async (t) => {
+ const serverDir = stubDir();
+ const firstProject = projectDir("project-a");
+ const secondProject = projectDir("project-b");
+ const rt = runtime(t);
+ rt.setRecords([stubRecord(serverDir, {
+ env: { STUB_REPORT_CWD: "1", STUB_TOOL_ONLY_IN_CWD: firstProject },
+ })]);
+
+ const firstTools = await rt.toolsForProject(firstProject);
+ const secondTools = await rt.toolsForProject(secondProject);
+ const projectlessTools = await rt.toolsForProject(null);
+ assert.ok(firstTools.some((tool) => tool.fullName === "mcp_stub_cwd"));
+ assert.ok(secondTools.some((tool) => tool.fullName === "mcp_stub_cwd"));
+ assert.ok(firstTools.some((tool) => tool.fullName === "mcp_stub_project_only"));
+ assert.ok(!secondTools.some((tool) => tool.fullName === "mcp_stub_project_only"));
+ assert.ok(projectlessTools.some((tool) => tool.fullName === "mcp_stub_cwd"));
+
+ const firstResult = await rt.callTool("mcp_stub_cwd", {}, firstProject);
+ const firstAgain = await rt.callTool("mcp_stub_cwd", {}, firstProject);
+ const secondResult = await rt.callTool("mcp_stub_cwd", {}, secondProject);
+ const projectlessResult = await rt.callTool("mcp_stub_cwd", {}, null);
+ const firstValue = firstResult.content[0].text;
+ const firstAgainValue = firstAgain.content[0].text;
+ const secondValue = secondResult.content[0].text;
+ const projectlessValue = projectlessResult.content[0].text;
+
+ assert.equal(firstValue.split("|")[0], firstProject);
+ assert.equal(firstAgainValue, firstValue, "the same workspace should reuse its process");
+ assert.equal(secondValue.split("|")[0], secondProject);
+ assert.notEqual(secondValue.split("|")[1], firstValue.split("|")[1]);
+ assert.equal(projectlessValue.split("|")[0], realpathSync(homedir()));
+ await assert.rejects(
+ rt.callTool("mcp_stub_project_only", {}, secondProject),
+ { errorCode: "TOOL_NOT_FOUND" },
+ "a tool advertised in one workspace must not be dispatched through another",
+ );
+});
+
+test("the stdio connection cache stays bounded and evicted workspaces reconnect", async (t) => {
+ let active = 0;
+ let peakActive = 0;
+ let handshakes = 0;
+ const rt = new UserMcpRuntime({
+ createClient: () => {
+ let connected = false;
+ const tools = [{ name: "lookup" }];
+ return {
+ connect: async () => {
+ handshakes += 1;
+ connected = true;
+ active += 1;
+ peakActive = Math.max(peakActive, active);
+ return tools;
+ },
+ getTools: () => connected ? tools : [],
+ isConnected: () => connected,
+ callTool: async () => "called",
+ ping: async () => {},
+ close: () => {
+ if (!connected) return;
+ connected = false;
+ active -= 1;
+ },
+ };
+ },
+ });
+ t.after(() => rt.disposeAll());
+ rt.setRecords([stubRecord("/unused")]);
+
+ for (let index = 0; index < 65; index += 1) {
+ await rt.toolsForProject(`/workspace/${index}`);
+ }
+ assert.equal(active, 64);
+ assert.equal(peakActive, 64);
+
+ assert.equal(await rt.callTool("mcp_stub_lookup", {}, "/workspace/0"), "called");
+ assert.equal(active, 64);
+ assert.equal(handshakes, 66, "the evicted workspace should reconnect on demand");
+
+ rt.disposeAll();
+ assert.equal(active, 0);
+});
+
test("refreshing HTTP MCP status detects a server that went offline", async (t) => {
let online = true;
let pings = 0;
@@ -191,13 +292,16 @@ test("stopping one session cancels only its active MCP call", async (t) => {
test("a project-scoped server is invisible outside its projects", async (t) => {
const dir = stubDir();
+ const projectPath = projectDir();
+ const nestedProject = join(projectPath, "apps", "web");
+ mkdirSync(nestedProject, { recursive: true });
const rt = runtime(t);
- rt.setRecords([stubRecord(dir, { scope: { mode: "projects", projects: ["/repo"] } })]);
+ rt.setRecords([stubRecord(dir, { scope: { mode: "projects", projects: [projectPath] } })]);
assert.deepEqual(await rt.toolsForProject("/elsewhere"), []);
assert.deepEqual(await rt.toolsForProject(null), []);
// Subdirectories of a scoped project count as inside it.
- assert.equal((await rt.toolsForProject("/repo/apps/web")).length, 2);
+ assert.equal((await rt.toolsForProject(nestedProject)).length, 2);
});
test("a disabled server contributes nothing and is never connected", async (t) => {
@@ -213,16 +317,18 @@ test("a disabled server contributes nothing and is never connected", async (t) =
// narrowed the scope still remembers the tool name.
test("a call is refused once the server no longer applies to the session", async (t) => {
const dir = stubDir();
+ const projectPath = projectDir();
+ const otherProject = projectDir("other");
const rt = runtime(t);
rt.setRecords([stubRecord(dir)]);
- await rt.toolsForProject("/repo");
+ await rt.toolsForProject(projectPath);
- const before = await rt.callTool("mcp_stub_lookup", {}, "/repo");
+ const before = await rt.callTool("mcp_stub_lookup", {}, projectPath);
assert.match(JSON.stringify(before), /lookup/);
- rt.setRecords([stubRecord(dir, { scope: { mode: "projects", projects: ["/other"] } })]);
- await rt.toolsForProject("/other");
- await assert.rejects(rt.callTool("mcp_stub_lookup", {}, "/repo"), (error) => {
+ rt.setRecords([stubRecord(dir, { scope: { mode: "projects", projects: [otherProject] } })]);
+ await rt.toolsForProject(otherProject);
+ await assert.rejects(rt.callTool("mcp_stub_lookup", {}, projectPath), (error) => {
assert.equal(error.errorCode, "TOOL_NOT_FOUND");
assert.match(error.message, /not active for this session/);
return true;
@@ -231,11 +337,12 @@ test("a call is refused once the server no longer applies to the session", async
test("a name the server never advertised is refused, not forwarded", async (t) => {
const dir = stubDir();
+ const projectPath = projectDir();
const rt = runtime(t);
rt.setRecords([stubRecord(dir)]);
- await rt.toolsForProject("/repo");
+ await rt.toolsForProject(projectPath);
- await assert.rejects(rt.callTool("mcp_stub_delete_everything", {}, "/repo"), (error) => {
+ await assert.rejects(rt.callTool("mcp_stub_delete_everything", {}, projectPath), (error) => {
assert.equal(error.errorCode, "TOOL_NOT_FOUND");
return true;
});
@@ -243,46 +350,49 @@ test("a name the server never advertised is refused, not forwarded", async (t) =
test("editing what a server runs drops the live connection", async (t) => {
const dir = stubDir();
+ const projectPath = projectDir();
const rt = runtime(t);
rt.setRecords([stubRecord(dir, { env: { STUB_TAG: "first" } })]);
- await rt.toolsForProject("/repo");
- assert.match(JSON.stringify(await rt.callTool("mcp_stub_lookup", {}, "/repo")), /first:lookup/);
+ await rt.toolsForProject(projectPath);
+ assert.match(JSON.stringify(await rt.callTool("mcp_stub_lookup", {}, projectPath)), /first:lookup/);
rt.setRecords([stubRecord(dir, { env: { STUB_TAG: "second" } })]);
// Routing survives the edit, but dispatch must handshake the new config.
assert.equal(rt.hasTool("mcp_stub_lookup"), true);
assert.equal(rt.statusFor("stub").state, "idle");
- assert.match(JSON.stringify(await rt.callTool("mcp_stub_lookup", {}, "/repo")), /second:lookup/);
+ assert.match(JSON.stringify(await rt.callTool("mcp_stub_lookup", {}, projectPath)), /second:lookup/);
});
test("a terminated stdio process recovers on the next tool call", async (t) => {
const dir = stubDir();
+ const projectPath = projectDir();
const pidFile = join(dir, "pid");
let client;
const rt = runtime(t, {
createClient: (config) => { client = new McpServerClient(config); return client; },
});
rt.setRecords([stubRecord(dir, { env: { STUB_PID_FILE: pidFile } })]);
- await rt.toolsForProject("/repo");
+ await rt.toolsForProject(projectPath);
process.kill(Number(readFileSync(pidFile, "utf8")), "SIGTERM");
for (let attempt = 0; client.isConnected() && attempt < 100; attempt += 1) {
await new Promise((resolve) => setTimeout(resolve, 10));
}
assert.equal(client.isConnected(), false);
assert.deepEqual(client.getTools(), []);
- assert.match(JSON.stringify(await rt.callTool("mcp_stub_lookup", {}, "/repo")), /lookup/);
+ assert.match(JSON.stringify(await rt.callTool("mcp_stub_lookup", {}, projectPath)), /lookup/);
assert.equal(rt.statusFor("stub").state, "ready");
});
test("changing only scope or label keeps the connection", async (t) => {
const dir = stubDir();
+ const projectPath = projectDir();
const rt = runtime(t);
rt.setRecords([stubRecord(dir)]);
- await rt.toolsForProject("/repo");
+ await rt.toolsForProject(projectPath);
rt.setRecords([
- stubRecord(dir, { label: "Renamed", scope: { mode: "projects", projects: ["/repo"] } }),
+ stubRecord(dir, { label: "Renamed", scope: { mode: "projects", projects: [projectPath] } }),
]);
assert.equal(rt.statusFor("stub").state, "ready");
assert.equal(rt.hasTool("mcp_stub_lookup"), true);
@@ -460,10 +570,11 @@ test("testing a server that is not saved reports it instead of throwing", async
test("statuses are listed for every saved server, connected or not", async (t) => {
const dir = stubDir();
+ const projectPath = projectDir();
const rt = runtime(t);
rt.setRecords([stubRecord(dir), stubRecord(dir, { id: "second", enabled: false })]);
- await rt.toolsForProject("/repo");
+ await rt.toolsForProject(projectPath);
const statuses = rt.listStatuses();
assert.deepEqual(
statuses.map((entry) => [entry.serverId, entry.state]),
@@ -476,6 +587,7 @@ test("statuses are listed for every saved server, connected or not", async (t) =
test("disposing the runtime kills the server processes", async (t) => {
const dir = stubDir();
+ const projectPath = projectDir();
const pidFile = join(dir, "pid");
const rt = new UserMcpRuntime({
createClient: (config) => new McpServerClient(config),
@@ -484,7 +596,7 @@ test("disposing the runtime kills the server processes", async (t) => {
});
rt.setRecords([stubRecord(dir, { env: { STUB_PID_FILE: pidFile } })]);
- await rt.toolsForProject("/repo");
+ await rt.toolsForProject(projectPath);
const pid = Number(readFileSync(pidFile, "utf8"));
rt.disposeAll();
@@ -531,19 +643,20 @@ test("configurationChanged separates what a server is from who may use it", () =
test("a server whose catalog cannot be listed lands as failed with the reason", async (t) => {
const dir = stubDir();
+ const projectPath = projectDir();
const rt = runtime(t);
rt.setRecords([stubRecord(dir, { env: { STUB_REPEAT_CURSOR: "1" } })]);
// The guard trips inside the handshake, so the server contributes nothing
// rather than a prefix of its catalog.
- assert.deepEqual(await rt.toolsForProject("/repo"), []);
+ assert.deepEqual(await rt.toolsForProject(projectPath), []);
const status = rt.statusFor("stub");
assert.equal(status.state, "failed");
assert.equal(status.toolCount, 0);
assert.match(status.message, /repeated a tools\/list cursor/);
// A server that already failed this run is not handshaken again per session.
- assert.deepEqual(await rt.toolsForProject("/repo"), []);
+ assert.deepEqual(await rt.toolsForProject(projectPath), []);
assert.equal(rt.statusFor("stub").state, "failed");
});
diff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.md
index 9f550e223..fd36aa224 100644
--- a/docs/spec/03-runtime/01-ipc-protocol.md
+++ b/docs/spec/03-runtime/01-ipc-protocol.md
@@ -1499,6 +1499,12 @@ returns its status to the MCP editor.
The desktop's `mcp.list` IPC response probes previously ready remote connections
before reporting their status. If a server no longer responds, its row reports
`failed` instead of retaining a stale `ready` status; Test connection retries it. A failed settings probe does not interrupt an in-flight tool call; Test connection closes the old client before retrying.
+Each user stdio MCP child starts with the resolved workspace path of the
+session that uses it as its working directory. Sessions in the same workspace
+share that child; sessions in different workspaces use separate children.
+A projectless session uses the user's home directory. Idle cached connections
+may be closed under the runtime's connection limit and are reconnected when
+the session needs them again.
Stopping a session aborts its in-flight user MCP tool calls. The client sends
`notifications/cancelled` for each active request without closing a connection
used by other sessions; a completed or canceled tool call is never replayed.
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index f5a699460..21fa875a6 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -7817,7 +7817,8 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
2. Confirm the import, then open the imported stdio server and press Test
connection.
3. Leave the server at **Everywhere** and ask the agent in each project to
- list its available tools.
+ list its available tools. Have the stdio fixture report its working
+ directory and process id; open a second session in `~/work/api` as well.
4. Set the server to **These projects**, with only `~/work/api` picked.
5. Ask again in each project.
6. In the already-open `~/personal/site` session — assembled while the server
@@ -7849,6 +7850,9 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
- Test reports connected with the tool names it found, and the row's glyph
turns from connecting to ready.
- While global, both sessions see `mcp_<serverId>_<tool>` names.
+ - The stdio fixture runs from each session's project directory. Sessions in
+ `~/work/api` share one process, while `~/personal/site` uses a separate
+ process. A projectless session uses the user's home directory.
- After narrowing, only the `~/work/api` session sees them; the summary chip
reads "1 project" and names it.
- The stale call from step 6 fails with `TOOL_NOT_FOUND` and "not active for