Skip to content

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

fix(desktop): keep each project's MCP servers when another project refreshes

zszz3bcaeae6cc19b
diff --git a/apps/desktop/electron/main/ipc/composer-ipc.ts b/apps/desktop/electron/main/ipc/composer-ipc.ts
index e900bf1f5..63923c0cd 100644
--- a/apps/desktop/electron/main/ipc/composer-ipc.ts
+++ b/apps/desktop/electron/main/ipc/composer-ipc.ts
@@ -125,11 +125,11 @@ export function createComposerCommandService({
id: trustedExtensionCommandId(command.name),
}));
const skillCommands = await loadComposerSkillCommands(root, options.remote === true).catch(() => []);
- const statuses = userMcp?.listStatuses() ?? [];
+ const statuses = userMcp?.listStatuses(root) ?? [];
const ready = new Set(statuses
.filter((status) => status.state === "ready" && status.toolCount > 0)
.map((status) => status.serverId));
- const mcpCommands: ComposerCommand[] = (userMcp?.listRecords() ?? [])
+ const mcpCommands: ComposerCommand[] = (userMcp?.listRecords(root) ?? [])
.filter((record) => ready.has(record.id) && isActiveInProject(record, root))
.flatMap((record) => {
const server: ComposerCommand = {
diff --git a/apps/desktop/electron/main/ipc/mcp-ipc.ts b/apps/desktop/electron/main/ipc/mcp-ipc.ts
index bfe9a5ee2..d94966303 100644
--- a/apps/desktop/electron/main/ipc/mcp-ipc.ts
+++ b/apps/desktop/electron/main/ipc/mcp-ipc.ts
@@ -34,6 +34,17 @@ export function registerMcpIpc({
searchMcpMarket,
}: McpIpcDependencies): void {
let host: HostProcess | null = null;
+ /**
+ * Re-read every workspace the runtime holds a list for. A saved server can
+ * be active in several projects, so deleting, disabling or rescoping it has
+ * to reach all of them, not only the project open in the window.
+ */
+ const refreshAllWorkspaces = async (): Promise<void> => {
+ const current = currentWorkspacePath();
+ const others = userMcp.listedWorkspaces().filter((projectPath) => projectPath !== current);
+ for (const projectPath of others) await refreshUserMcp(projectPath);
+ await refreshUserMcp(current);
+ };
const handle = (channel: string, fn: (...args: any[]) => Promise<any>) => {
registrar.handle(channel, async (...args) => {
host = getHost();
@@ -61,9 +72,10 @@ handle(IPC.invoke.mcpList, async (query: Partial<AgentCapabilityQuery> = {}) =>
);
// Status belongs to the currently open project's active runtime, while the
// list itself must include disabled records for the settings page.
- await refreshUserMcp(currentWorkspacePath());
+ const current = currentWorkspacePath();
+ await refreshUserMcp(current);
const statuses = await Promise.all(
- (await userMcp.refreshStatuses()).map(async (status) => ({
+ (await userMcp.refreshStatuses(current)).map(async (status) => ({
...status,
hasOauth: oauth ? await oauth.hasOAuth(status.serverId) : false,
})),
@@ -74,7 +86,7 @@ handle(IPC.invoke.mcpList, async (query: Partial<AgentCapabilityQuery> = {}) =>
handle(IPC.invoke.mcpUpsert, async (server: McpServerInput) => {
if (!host) throw new Error("host unavailable");
const res = await host.call<{ server: McpServerRecord }>("mcp.upsert", { server });
- await refreshUserMcp(currentWorkspacePath());
+ await refreshAllWorkspaces();
sendToRenderer(IPC.event.pluginChanged, { reason: "mcp", pluginId: res.server?.id });
if (res.server && res.server.enabled !== false) {
void userMcp
@@ -93,7 +105,7 @@ handle(IPC.invoke.mcpList, async (query: Partial<AgentCapabilityQuery> = {}) =>
if (!host) throw new Error("host unavailable");
const res = await host.call("mcp.remove", payload);
await oauth?.deleteOAuth(payload.id);
- await refreshUserMcp(currentWorkspacePath());
+ await refreshAllWorkspaces();
sendToRenderer(IPC.event.pluginChanged,{ reason: "mcp", pluginId: payload.id });
return res;
},
@@ -104,7 +116,7 @@ handle(IPC.invoke.mcpList, async (query: Partial<AgentCapabilityQuery> = {}) =>
async (payload: { id: string; enabled: boolean } & Partial<AgentCapabilityQuery>) => {
if (!host) throw new Error("host unavailable");
const res = await host.call("mcp.setEnabled", payload);
- await refreshUserMcp(currentWorkspacePath());
+ await refreshAllWorkspaces();
sendToRenderer(IPC.event.pluginChanged,{ reason: "mcp", pluginId: payload.id });
return res;
},
@@ -115,7 +127,7 @@ handle(IPC.invoke.mcpList, async (query: Partial<AgentCapabilityQuery> = {}) =>
async (payload: { id: string; scope: ActivationScope }) => {
if (!host) throw new Error("host unavailable");
const res = await host.call("mcp.setScope", payload);
- await refreshUserMcp(currentWorkspacePath());
+ await refreshAllWorkspaces();
sendToRenderer(IPC.event.pluginChanged,{ reason: "mcp", pluginId: payload.id });
return res;
},
@@ -134,7 +146,7 @@ handle(IPC.invoke.mcpList, async (query: Partial<AgentCapabilityQuery> = {}) =>
if (res.server?.id && payload.id && payload.id !== res.server.id) {
await oauth?.transferOAuth(payload.id, res.server.id);
}
- await refreshUserMcp(currentWorkspacePath());
+ await refreshAllWorkspaces();
sendToRenderer(IPC.event.pluginChanged,{ reason: "mcp", pluginId: res.server?.id });
return res;
});
@@ -148,14 +160,10 @@ handle(IPC.invoke.mcpList, async (query: Partial<AgentCapabilityQuery> = {}) =>
...(payload.projectPath ? { projectPath: payload.projectPath } : {}),
} satisfies Partial<AgentCapabilityQuery>;
const listed = await host.call<{ servers: McpServerRecord[] }>("mcp.list", query);
- // Test may target a project different from the current session. Keep the
- // requested record long enough for the handshake, then restore the
- // current project's active runtime below.
- userMcp.setRecords([
- ...userMcp.listRecords().filter((record) => !listed.servers.some((item) => item.id === record.id)),
- ...(listed.servers ?? []),
- ]);
- const status = await userMcp.test(payload.id, payload.projectPath ?? currentWorkspacePath());
+ // Test the saved record directly: it may be disabled or belong to a
+ // project other than the open one, and no workspace's list changes.
+ const saved = (listed.servers ?? []).find((record) => record.id === payload.id);
+ const status = await userMcp.test(payload.id, payload.projectPath ?? currentWorkspacePath(), saved);
await refreshUserMcp(currentWorkspacePath());
sendToRenderer(IPC.event.pluginChanged,{ reason: "mcp", pluginId: payload.id });
const hasOauth = oauth ? await oauth.hasOAuth(payload.id) : false;
@@ -209,7 +217,7 @@ handle(IPC.invoke.mcpList, async (query: Partial<AgentCapabilityQuery> = {}) =>
failed.push({ id: server.id, reason: describeError(error) });
}
}
- await refreshUserMcp(currentWorkspacePath());
+ await refreshAllWorkspaces();
if (imported.length) {
sendToRenderer(IPC.event.pluginChanged,{ reason: "mcp" });
}
diff --git a/apps/desktop/electron/main/runtime/session-launch.ts b/apps/desktop/electron/main/runtime/session-launch.ts
index edd987642..b5ea477b3 100644
--- a/apps/desktop/electron/main/runtime/session-launch.ts
+++ b/apps/desktop/electron/main/runtime/session-launch.ts
@@ -114,7 +114,9 @@ export function createSessionLaunchRuntime({
projectPath: projectPath ?? null,
});
const servers = result.servers ?? [];
- userMcp.setRecords(servers);
+ // Each workspace keeps its own active list; refreshing this one must not
+ // take another project's servers away from a turn running there.
+ userMcp.setRecords(servers, projectPath ?? null);
return servers;
} catch (error) {
if (!isHostUnavailable(error)) {
diff --git a/apps/desktop/electron/main/services/plugin-services.ts b/apps/desktop/electron/main/services/plugin-services.ts
index 447e6c2f6..7dc4ac1c5 100644
--- a/apps/desktop/electron/main/services/plugin-services.ts
+++ b/apps/desktop/electron/main/services/plugin-services.ts
@@ -548,15 +548,11 @@ export function createPluginServices({
log: (level, message, data) => logger.app("plugin", level, message, { data }),
onAuthorized: async (serverId, record): Promise<McpServerStatus> => {
const existed = userMcp.listRecords().some((item) => item.id === serverId);
- if (record && !existed) {
- userMcp.setRecords([...userMcp.listRecords(), record]);
- }
userMcp.invalidate(serverId);
- const status: McpServerStatus = await userMcp.test(serverId);
- if (!existed) {
- userMcp.invalidate(serverId);
- userMcp.setRecords(userMcp.listRecords().filter((item) => item.id !== serverId));
- }
+ // A server no workspace lists yet is tested as saved, without being
+ // adopted into a list, and its probe connection is dropped afterwards.
+ const status: McpServerStatus = await userMcp.test(serverId, null, existed ? undefined : record);
+ if (!existed) userMcp.invalidate(serverId);
sendToRenderer(IPC.event.pluginChanged, { reason: "mcp", pluginId: serverId });
return status;
},
diff --git a/apps/desktop/electron/main/user-mcp.ts b/apps/desktop/electron/main/user-mcp.ts
index 7d1738fb4..31cf52f4b 100644
--- a/apps/desktop/electron/main/user-mcp.ts
+++ b/apps/desktop/electron/main/user-mcp.ts
@@ -63,6 +63,8 @@ export type UserMcpRuntimeOptions = {
type Entry = {
key: string;
+ /** Workspace a stdio process runs in; `null` for a shared HTTP connection. */
+ workspace: string | null;
record: McpServerRecord;
client: UserMcpClient;
status: McpServerStatus;
@@ -88,8 +90,17 @@ 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, Set<string>>();
- private records: McpServerRecord[] = [];
+ // Keyed like `records`, so a project server never borrows the names of the
+ // global server it overrides.
+ private discoveredTools = new Map<string, { serverId: string; tools: Set<string> }>();
+ // One copy of every saved server some workspace can use, keyed by
+ // `recordKey`: a global server is shared by all workspaces, a project server
+ // belongs to its project.
+ private records = new Map<string, McpServerRecord>();
+ // Which of those servers host-core reported active in each workspace. Every
+ // workspace keeps its own answer, because a global server can be switched off
+ // per project and a project server can override a global one.
+ private workspaces = new Map<string, { projectPath: string | null; keys: string[] }>();
private options: UserMcpRuntimeOptions;
// Spelled out rather than a constructor parameter property, because the test
@@ -99,19 +110,36 @@ export class UserMcpRuntime {
}
/**
- * Adopt a fresh list from host-core. Servers whose configuration changed —
- * or that vanished — lose their connection so the next call re-handshakes
- * against what the user actually saved.
+ * Adopt host-core's active list for one workspace (`null` = no project).
+ *
+ * Other workspaces keep theirs: refreshing project B must not take project
+ * A's servers away from a turn still running there. A workspace that was
+ * never refreshed reads the projectless list. A connection is dropped when
+ * its server's configuration changed, when its own workspace no longer lists
+ * the server, or when no workspace lists it any more, so the next call
+ * re-handshakes against what the user actually saved.
*/
- setRecords(records: McpServerRecord[]): void {
- this.records = records.map((record) => ({ ...record }));
- const byId = new Map(this.records.map((record) => [record.id, record]));
- for (const id of this.discoveredTools.keys()) {
- if (!byId.has(id)) this.discoveredTools.delete(id);
+ setRecords(records: McpServerRecord[], projectPath: string | null = null): void {
+ const keys: string[] = [];
+ for (const record of records) {
+ const key = recordKey(record);
+ this.records.set(key, { ...record });
+ keys.push(key);
+ }
+ this.workspaces.set(workspaceIdentity(projectPath), { projectPath, keys });
+ const listed = new Set([...this.workspaces.values()].flatMap((workspace) => workspace.keys));
+ for (const key of [...this.records.keys()]) {
+ if (!listed.has(key)) this.records.delete(key);
+ }
+ for (const key of [...this.discoveredTools.keys()]) {
+ if (!listed.has(key)) this.discoveredTools.delete(key);
}
for (const [key, entry] of [...this.entries]) {
- const next = byId.get(entry.record.id);
- if (!next || configurationChanged(entry.record, next)) {
+ const id = recordKey(entry.record);
+ const next = this.records.get(id);
+ // HTTP connections are shared by every workspace (`workspace === null`).
+ const stillListed = entry.workspace === null || this.listedKeys(entry.workspace).includes(id);
+ if (!next || !stillListed || configurationChanged(entry.record, next)) {
entry.client.close();
this.entries.delete(key);
continue;
@@ -120,17 +148,33 @@ export class UserMcpRuntime {
}
}
- listRecords(): McpServerRecord[] {
- return this.records.map((record) => ({ ...record }));
+ /** The workspaces that hold their own list, for refreshing them all at once. */
+ listedWorkspaces(): (string | null)[] {
+ return [...this.workspaces.values()].map((workspace) => workspace.projectPath);
+ }
+
+ listRecords(projectPath: string | null = null): McpServerRecord[] {
+ return this.listedRecords(projectPath).map((record) => ({ ...record }));
}
/** Per-server connection state for the Extensions page. */
- listStatuses(): McpServerStatus[] {
- return this.records.map((record) => this.statusFor(record.id));
+ listStatuses(projectPath: string | null = null): McpServerStatus[] {
+ return this.listedRecords(projectPath).map((record) => this.statusForRecord(record));
+ }
+
+ private listedKeys(workspace: string): string[] {
+ return (this.workspaces.get(workspace) ?? this.workspaces.get(workspaceIdentity(null)))?.keys ?? [];
+ }
+
+ /** The servers listed for a workspace, enabled or not. */
+ private listedRecords(projectPath: string | null | undefined): McpServerRecord[] {
+ return this.listedKeys(workspaceIdentity(projectPath))
+ .map((key) => this.records.get(key))
+ .filter((record): record is McpServerRecord => record !== undefined);
}
/** Confirm ready remote connections when the settings page refreshes. */
- async refreshStatuses(): Promise<McpServerStatus[]> {
+ async refreshStatuses(projectPath: string | null = null): Promise<McpServerStatus[]> {
await Promise.all([...this.entries].map(async ([key, entry]) => {
if (entry.record.transport === "stdio" || entry.status.state !== "ready") return;
let pending = this.statusRefreshes.get(key);
@@ -160,12 +204,25 @@ export class UserMcpRuntime {
if (this.statusRefreshes.get(key) === pending) this.statusRefreshes.delete(key);
}
}));
- return this.listStatuses();
+ return this.listStatuses(projectPath);
}
statusFor(serverId: string): McpServerStatus {
+ return this.latestStatus(serverId, (record) => record.id === serverId);
+ }
+
+ /** Status of one saved server, never of a same-id server in another project. */
+ private statusForRecord(record: McpServerRecord): McpServerStatus {
+ const key = recordKey(record);
+ return this.latestStatus(record.id, (candidate) => recordKey(candidate) === key);
+ }
+
+ private latestStatus(
+ serverId: string,
+ matches: (record: McpServerRecord) => boolean,
+ ): McpServerStatus {
const entry = [...this.entries.values()]
- .filter((candidate) => candidate.record.id === serverId)
+ .filter((candidate) => matches(candidate.record))
.sort((left, right) => right.status.updatedAt - left.status.updatedAt)[0];
if (entry) return { ...entry.status };
return {
@@ -184,7 +241,7 @@ export class UserMcpRuntime {
* status rather than thrown.
*/
async toolsForProject(projectPath: string | null | undefined): Promise<UserMcpToolDescriptor[]> {
- const active = this.records.filter((record) => isActiveInProject(record, projectPath));
+ const active = this.listedRecords(projectPath).filter((record) => isActiveInProject(record, projectPath));
const admitted = active.slice(0, MAX_ACTIVE_SERVERS);
if (admitted.length < active.length) {
this.options.log?.("warn", "user mcp servers skipped over the active cap", {
@@ -213,7 +270,12 @@ export class UserMcpRuntime {
/** Whether a saved server advertised this name (not a readiness check). */
hasTool(fullName: string): boolean {
- return this.findTool(fullName) !== undefined;
+ for (const { serverId, tools } of this.discoveredTools.values()) {
+ for (const toolName of tools) {
+ if (userMcpToolName(serverId, toolName) === fullName) return true;
+ }
+ }
+ return false;
}
/**
@@ -237,31 +299,32 @@ export class UserMcpRuntime {
projectPath: string | null | undefined,
signal?: AbortSignal,
): Promise<unknown> {
- const found = this.findTool(fullName);
+ const found = this.findTool(fullName, projectPath);
if (!found) {
throw Object.assign(new Error(`unknown mcp tool: ${fullName}`), {
errorCode: "TOOL_NOT_FOUND",
});
}
- const record = this.records.find((entry) => entry.id === found.serverId);
- if (!record || !isActiveInProject(record, projectPath)) {
+ const { record } = found;
+ if (!isActiveInProject(record, projectPath)) {
throw Object.assign(
- new Error(`mcp server ${found.serverId} is not active for this session`),
+ new Error(`mcp server ${record.id} is not active for this session`),
{ errorCode: "TOOL_NOT_FOUND" },
);
}
const { entry } = await this.connect(record, projectPath, true);
if (!entry) {
- throw Object.assign(new Error(`mcp server ${found.serverId} is unavailable`), {
+ throw Object.assign(new Error(`mcp server ${record.id} is unavailable`), {
errorCode: "UNAVAILABLE",
});
}
try {
// Configuration or scope can change while the handshake is in flight.
- const current = this.records.find((entry) => entry.id === found.serverId);
+ const key = recordKey(record);
+ const current = this.listedRecords(projectPath).find((candidate) => recordKey(candidate) === key);
if (!current || !isActiveInProject(current, projectPath)) {
throw Object.assign(
- new Error(`mcp server ${found.serverId} is not active for this session`),
+ new Error(`mcp server ${record.id} is not active for this session`),
{ errorCode: "TOOL_NOT_FOUND" },
);
}
@@ -269,7 +332,7 @@ export class UserMcpRuntime {
configurationChanged(record, current) ||
entry.status.state !== "ready" || !entry.client.isConnected()
) {
- throw Object.assign(new Error(`mcp server ${found.serverId} is unavailable`), {
+ throw Object.assign(new Error(`mcp server ${record.id} is unavailable`), {
errorCode: "UNAVAILABLE",
});
}
@@ -303,12 +366,16 @@ export class UserMcpRuntime {
* Handshake once and report what happened, for the editor's "Test connection"
* button. The connection is kept: a user who just tested a server is about to
* use it.
+ *
+ * `saved` tests a record the workspace does not list — a disabled server, or
+ * one in another project — without adopting it into any workspace.
*/
async test(
serverId: string,
projectPath: string | null | undefined = null,
+ saved?: McpServerRecord,
): Promise<McpServerStatus> {
- const record = this.records.find((entry) => entry.id === serverId);
+ const record = saved ?? this.listedRecords(projectPath).find((entry) => entry.id === serverId);
if (!record) {
return {
serverId,
@@ -322,9 +389,10 @@ export class UserMcpRuntime {
// workspace caches. A successful home test must not leave project sessions
// stuck on an earlier failure. Never interrupt a handshake or tool call.
const targetKey = connectionKey(record, projectPath);
+ const savedKey = recordKey(record);
for (const [key, entry] of [...this.entries]) {
if (
- entry.record.id !== serverId || entry.connecting || entry.activeCalls > 0 ||
+ recordKey(entry.record) !== savedKey || entry.connecting || entry.activeCalls > 0 ||
(key !== targetKey && entry.status.state !== "failed")
) continue;
entry.client.close();
@@ -348,7 +416,9 @@ export class UserMcpRuntime {
this.entries.delete(key);
}
}
- this.discoveredTools.delete(serverId);
+ for (const [key, discovered] of [...this.discoveredTools]) {
+ if (discovered.serverId === serverId) this.discoveredTools.delete(key);
+ }
}
/** Drop every connection, e.g. on quit. */
@@ -364,11 +434,15 @@ export class UserMcpRuntime {
this.calls.cancelSession(sessionId);
}
- private findTool(fullName: string): { serverId: string; toolName: string } | undefined {
- for (const [serverId, tools] of this.discoveredTools) {
- for (const toolName of tools) {
- if (userMcpToolName(serverId, toolName) === fullName) {
- return { serverId, toolName };
+ /** Resolve a tool name against the servers this workspace lists. */
+ private findTool(
+ fullName: string,
+ projectPath: string | null | undefined,
+ ): { record: McpServerRecord; toolName: string } | undefined {
+ for (const record of this.listedRecords(projectPath)) {
+ for (const toolName of this.discoveredTools.get(recordKey(record))?.tools ?? []) {
+ if (userMcpToolName(record.id, toolName) === fullName) {
+ return { record, toolName };
}
}
}
@@ -451,9 +525,10 @@ export class UserMcpRuntime {
entry.client.close();
return [];
}
- 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);
+ const key = recordKey(record);
+ const catalog = this.discoveredTools.get(key) ?? { serverId: record.id, tools: new Set<string>() };
+ for (const tool of tools) catalog.tools.add(tool.name);
+ this.discoveredTools.set(key, catalog);
entry.status = {
serverId: record.id,
state: "ready",
@@ -520,6 +595,7 @@ export class UserMcpRuntime {
});
const entry: Entry = {
key,
+ workspace: record.transport === "stdio" ? workspaceIdentity(projectPath) : null,
record,
client,
oauthToken,
@@ -556,11 +632,24 @@ 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"]);
+function workspaceIdentity(projectPath: string | null | undefined): string {
const rootPath = workspacePath(projectPath);
- const identity = process.platform === "win32" ? rootPath.toLowerCase() : rootPath;
- return JSON.stringify([record.id, identity]);
+ return process.platform === "win32" ? rootPath.toLowerCase() : rootPath;
+}
+
+/**
+ * Which saved server a record is: a global server is one server everywhere,
+ * while a project server is its own server even when it reuses a global id.
+ */
+function recordKey(record: McpServerRecord): string {
+ return record.level === "project" && record.projectPath
+ ? JSON.stringify([record.id, workspaceIdentity(record.projectPath)])
+ : JSON.stringify([record.id]);
+}
+
+function connectionKey(record: McpServerRecord, projectPath: string | null | undefined): string {
+ if (record.transport !== "stdio") return JSON.stringify([recordKey(record), "http"]);
+ return JSON.stringify([recordKey(record), workspaceIdentity(projectPath)]);
}
/**
diff --git a/apps/desktop/test/mcp-project-isolation.test.mjs b/apps/desktop/test/mcp-project-isolation.test.mjs
new file mode 100644
index 000000000..58606df48
--- /dev/null
+++ b/apps/desktop/test/mcp-project-isolation.test.mjs
@@ -0,0 +1,171 @@
+import assert from "node:assert/strict";
+import { createRequire, register } from "node:module";
+import { mkdtemp, realpath, rm, writeFile, mkdir } from "node:fs/promises";
+import { join } from "node:path";
+import test from "node:test";
+import { pathToFileURL } from "node:url";
+import { IPC } from "@pi-desktop/shared";
+import { repositoryRoot } from "../../../scripts/e2e/boot.mjs";
+
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+const { UserMcpRuntime } = await import("../electron/main/user-mcp.ts");
+const { McpServerClient } = await import("../electron/main/plugin-mcp.ts");
+const { registerMcpIpc } = await import("../electron/main/ipc/mcp-ipc.ts");
+
+const root = repositoryRoot();
+const { build } = createRequire(join(root, "packages/agent-runtime/package.json"))("esbuild");
+
+// Answers the handshake with one tool that reports the process cwd, so a call
+// proves which workspace's server served it.
+const SERVER = `
+let input = "";
+process.stdin.setEncoding("utf8");
+process.stdin.on("data", (chunk) => {
+ input += chunk;
+ for (let index; (index = input.indexOf("\\n")) >= 0;) {
+ const line = input.slice(0, index); input = input.slice(index + 1);
+ if (!line) continue;
+ const request = JSON.parse(line);
+ let result;
+ if (request.method === "initialize") result = { protocolVersion: request.params.protocolVersion, capabilities: { tools: {} } };
+ else if (request.method === "tools/list") result = { tools: [{ name: "cwd" }] };
+ else if (request.method === "tools/call") result = { content: [{ type: "text", text: process.cwd() }] };
+ else continue;
+ process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: request.id, result }) + "\\n");
+ }
+});
+`;
+
+async function fixture(t) {
+ // Resolve the temp root so it matches the child cwd on macOS (/var -> /private/var).
+ const temp = await realpath(await mkdtemp(join(root, "apps/desktop/.mcp-project-isolation-")));
+ const projectA = join(temp, "project-a");
+ const projectB = join(temp, "project-b");
+ await mkdir(projectA);
+ await mkdir(projectB);
+ const server = join(temp, "server.mjs");
+ await writeFile(server, SERVER);
+ const userMcp = new UserMcpRuntime({
+ createClient: (config) => new McpServerClient(config),
+ connectTimeoutMs: 5_000,
+ callTimeoutMs: 5_000,
+ });
+ t.after(async () => {
+ userMcp.disposeAll();
+ await rm(temp, { recursive: true, force: true, maxRetries: 10, retryDelay: 25 });
+ });
+ const record = (id, overrides = {}) => ({
+ id,
+ label: id,
+ transport: "stdio",
+ command: "node",
+ args: [server],
+ env: {},
+ enabled: true,
+ scope: { mode: "global", projects: [] },
+ createdAt: "2026-01-01T00:00:00Z",
+ updatedAt: "2026-01-01T00:00:00Z",
+ ...overrides,
+ });
+ return { temp, projectA, projectB, userMcp, record };
+}
+
+async function sessionLaunch(temp, { host, userMcp }) {
+ const bundle = join(temp, "session-launch.mjs");
+ await build({
+ entryPoints: [join(root, "apps/desktop/electron/main/runtime/session-launch.ts")],
+ outfile: bundle,
+ bundle: true,
+ platform: "node",
+ format: "esm",
+ packages: "external",
+ nodePaths: [join(root, "apps/desktop/node_modules")],
+ });
+ const { createSessionLaunchRuntime } = await import(pathToFileURL(bundle).href);
+ return createSessionLaunchRuntime({
+ runtimeState: { host, sidecar: { setVendorAuthBindings() {} }, agentHostBridge: null },
+ logger: { app() {} },
+ userMcp,
+ plugins: { getTools: () => [], getSkills: () => [], listLoaded: () => [], getAgentExtensions: () => [] },
+ sessionProjects: new Map(),
+ dataDir: temp,
+ vendorOAuth: { async bindingFor() { return undefined; } },
+ modelsDevCatalog: { async ensureLoaded() {}, configureAccount() {}, findModel() { return undefined; } },
+ getWorkspacePath: () => null,
+ pluginActiveInProject: () => true,
+ bindingForModel: () => undefined,
+ effectiveSubagentModelConfig: () => ({ modelConfig: undefined, capabilities: {} }),
+ normalizeThinkingLevel: () => "off",
+ });
+}
+
+// #2332: a session launched in project B refreshes B's active MCP list. A turn
+// still running in project A must keep calling A's own server.
+test("launching a session in another project keeps a running project's MCP tools", async (t) => {
+ const { temp, projectA, projectB, userMcp, record } = await fixture(t);
+ const demo = record("demo", {
+ level: "project",
+ projectPath: projectA,
+ scope: { mode: "projects", projects: [projectA] },
+ });
+ const active = new Map([[projectA, [demo]], [projectB, []]]);
+ const host = {
+ isAvailable: () => true,
+ async call(method, params) {
+ assert.equal(method, "mcp.active");
+ return { servers: active.get(params.projectPath) ?? [] };
+ },
+ };
+ const launch = await sessionLaunch(temp, { host, userMcp });
+
+ await launch.refreshUserMcp(projectA);
+ assert.deepEqual((await userMcp.toolsForProject(projectA)).map((tool) => tool.fullName), ["mcp_demo_cwd"]);
+ assert.equal((await userMcp.callTool("mcp_demo_cwd", {}, projectA)).content[0].text, projectA);
+
+ await launch.refreshUserMcp(projectB);
+
+ assert.deepEqual(await userMcp.toolsForProject(projectB), []);
+ assert.equal((await userMcp.callTool("mcp_demo_cwd", {}, projectA)).content[0].text, projectA);
+});
+
+// Settings changes run against the open project, but a saved server can be
+// active in several projects: switching it off has to reach all of them.
+test("disabling a global server in settings stops it in every project", async (t) => {
+ const { projectA, projectB, userMcp, record } = await fixture(t);
+ const global = record("shared");
+ let enabled = true;
+ const refreshUserMcp = async (projectPath) => {
+ const servers = enabled ? [global] : [];
+ userMcp.setRecords(servers, projectPath ?? null);
+ return servers;
+ };
+ const handlers = new Map();
+ registerMcpIpc({
+ registrar: { handle: (channel, handler) => handlers.set(channel, handler) },
+ getHost: () => ({
+ call: async (method) => {
+ assert.equal(method, "mcp.setEnabled");
+ enabled = false;
+ return {};
+ },
+ }),
+ userMcp,
+ currentWorkspacePath: () => projectB,
+ refreshUserMcp,
+ describeError: (error) => error.message,
+ sendToRenderer: () => {},
+ searchMcpMarket: async () => ({ entries: [] }),
+ });
+ await refreshUserMcp(projectA);
+ await refreshUserMcp(projectB);
+ await userMcp.toolsForProject(projectA);
+ assert.equal((await userMcp.callTool("mcp_shared_cwd", {}, projectA)).content[0].text, projectA);
+
+ await handlers.get(IPC.invoke.mcpSetEnabled)({ id: "shared", enabled: false });
+
+ assert.deepEqual(await userMcp.toolsForProject(projectA), []);
+ await assert.rejects(userMcp.callTool("mcp_shared_cwd", {}, projectA), (error) => {
+ assert.equal(error.errorCode, "TOOL_NOT_FOUND");
+ return true;
+ });
+});
diff --git a/apps/desktop/test/user-mcp.test.mjs b/apps/desktop/test/user-mcp.test.mjs
index afba53136..e8df10a3b 100644
--- a/apps/desktop/test/user-mcp.test.mjs
+++ b/apps/desktop/test/user-mcp.test.mjs
@@ -97,6 +97,19 @@ function stubRecord(dir, overrides = {}) {
};
}
+/** Poll until a stub process is gone; closing the client signals it. */
+async function waitForExit(pid) {
+ for (let attempt = 0; attempt < 100; attempt += 1) {
+ try {
+ process.kill(pid, 0);
+ } catch {
+ return;
+ }
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ }
+ assert.fail(`user mcp child ${pid} is still running`);
+}
+
function runtime(t, options = {}) {
const { spawnImpl, ...rest } = options;
const instance = new UserMcpRuntime({
@@ -335,6 +348,119 @@ test("a call is refused once the server no longer applies to the session", async
});
});
+/** A server saved in a project's own `.agents/servers`, as host-core lists it. */
+function projectStubRecord(dir, projectPath, overrides = {}) {
+ return stubRecord(dir, {
+ level: "project",
+ projectPath,
+ scope: { mode: "projects", projects: [projectPath] },
+ ...overrides,
+ });
+}
+
+// #2332: host-core answers `mcp.active` per project, and each session refreshes
+// its own project. One project's answer must not replace another's.
+test("refreshing another project keeps a running project's own server callable", async (t) => {
+ const dir = stubDir();
+ const projectA = projectDir("a");
+ const projectB = projectDir("b");
+ const rt = runtime(t);
+ rt.setRecords([projectStubRecord(dir, projectA)], projectA);
+ assert.equal((await rt.toolsForProject(projectA)).length, 2);
+
+ rt.setRecords([], projectB);
+
+ assert.deepEqual(await rt.toolsForProject(projectB), []);
+ assert.equal(rt.hasTool("mcp_stub_lookup"), true);
+ assert.match(JSON.stringify(await rt.callTool("mcp_stub_lookup", {}, projectA)), /lookup/);
+ assert.equal((await rt.toolsForProject(projectA)).length, 2);
+ await assert.rejects(rt.callTool("mcp_stub_lookup", {}, projectB), (error) => {
+ assert.equal(error.errorCode, "TOOL_NOT_FOUND");
+ return true;
+ });
+});
+
+test("a global server switched off in one project stays on in another", async (t) => {
+ const dir = stubDir();
+ const projectA = projectDir("a");
+ const projectB = projectDir("b");
+ const rt = runtime(t);
+ rt.setRecords([stubRecord(dir)], projectA);
+ rt.setRecords([], projectB);
+
+ assert.equal((await rt.toolsForProject(projectA)).length, 2);
+ assert.deepEqual(await rt.toolsForProject(projectB), []);
+ assert.match(JSON.stringify(await rt.callTool("mcp_stub_lookup", {}, projectA)), /lookup/);
+ await assert.rejects(rt.callTool("mcp_stub_lookup", {}, projectB), /unknown mcp tool/);
+ assert.deepEqual(rt.listRecords(projectA).map((record) => record.id), ["stub"]);
+ assert.deepEqual(rt.listRecords(projectB), []);
+});
+
+test("a global server edited from one project reaches every project at once", async (t) => {
+ const dir = stubDir();
+ const projectA = projectDir("a");
+ const projectB = projectDir("b");
+ const rt = runtime(t);
+ rt.setRecords([stubRecord(dir, { env: { STUB_TAG: "old" } })], projectA);
+ rt.setRecords([stubRecord(dir, { env: { STUB_TAG: "old" } })], projectB);
+ await rt.toolsForProject(projectA);
+ assert.match(JSON.stringify(await rt.callTool("mcp_stub_lookup", {}, projectA)), /old:lookup/);
+
+ // The settings page refreshes only the open project; the saved server is one.
+ rt.setRecords([stubRecord(dir, { env: { STUB_TAG: "new" } })], projectB);
+
+ await rt.toolsForProject(projectA);
+ assert.match(JSON.stringify(await rt.callTool("mcp_stub_lookup", {}, projectA)), /new:lookup/);
+});
+
+test("a project server reusing a global id is a separate server", async (t) => {
+ const dir = stubDir();
+ const projectA = projectDir("a");
+ const projectB = projectDir("b");
+ const rt = runtime(t);
+ rt.setRecords([projectStubRecord(dir, projectA, { env: { STUB_TAG: "project" } })], projectA);
+ rt.setRecords([stubRecord(dir, { env: { STUB_TAG: "global" } })], projectB);
+ await rt.toolsForProject(projectA);
+ await rt.toolsForProject(projectB);
+
+ assert.match(JSON.stringify(await rt.callTool("mcp_stub_lookup", {}, projectA)), /project:lookup/);
+ assert.match(JSON.stringify(await rt.callTool("mcp_stub_lookup", {}, projectB)), /global:lookup/);
+ // Refreshing B with the same global server leaves A's own server in place.
+ rt.setRecords([stubRecord(dir, { env: { STUB_TAG: "global" } })], projectB);
+ assert.match(JSON.stringify(await rt.callTool("mcp_stub_lookup", {}, projectA)), /project:lookup/);
+ assert.deepEqual(rt.listedWorkspaces().sort(), [projectA, projectB].sort());
+});
+
+test("a server no project lists any more is disconnected", async (t) => {
+ const dir = stubDir();
+ const pidFile = join(dir, "pid");
+ const projectA = projectDir("a");
+ const rt = runtime(t);
+ rt.setRecords([stubRecord(dir, { env: { STUB_PID_FILE: pidFile } })], projectA);
+ await rt.toolsForProject(projectA);
+ const pid = Number(readFileSync(pidFile, "utf8"));
+
+ rt.setRecords([], projectA);
+
+ assert.equal(rt.hasTool("mcp_stub_lookup"), false);
+ assert.equal(rt.statusFor("stub").state, "idle");
+ await waitForExit(pid);
+});
+
+test("testing a saved server another workspace does not list adopts it nowhere", async (t) => {
+ const dir = stubDir();
+ const projectA = projectDir("a");
+ const rt = runtime(t);
+ rt.setRecords([], projectA);
+ const saved = projectStubRecord(dir, projectA, { enabled: false });
+
+ const status = await rt.test("stub", projectA, saved);
+
+ assert.equal(status.state, "ready");
+ assert.deepEqual(rt.listRecords(projectA), []);
+ assert.deepEqual(await rt.toolsForProject(projectA), []);
+});
+
test("a name the server never advertised is refused, not forwarded", async (t) => {
const dir = stubDir();
const projectPath = projectDir();