Skip to content

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

fix(mcp): cancel in-flight calls when a session stops (#1005)

vastsa056153954b37
diff --git a/apps/desktop/electron/main/ipc/register.ts b/apps/desktop/electron/main/ipc/register.ts
index fa464dc7c..494e8af83 100644
--- a/apps/desktop/electron/main/ipc/register.ts
+++ b/apps/desktop/electron/main/ipc/register.ts
@@ -362,7 +362,10 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {
getHost,
getSidecar,
getAgentHostBridge,
- cancelSessionTools: (sessionId: string, reason?: string) => plugins.cancelSessionTools(sessionId, reason),
+ cancelSessionTools: (sessionId: string, reason?: string) => {
+ plugins.cancelSessionTools(sessionId, reason);
+ userMcp.cancelSessionCalls(sessionId);
+ },
logger,
vendorOAuth,
agentExtensions,
diff --git a/apps/desktop/electron/main/mcp-call-registry.ts b/apps/desktop/electron/main/mcp-call-registry.ts
new file mode 100644
index 000000000..52e48452d
--- /dev/null
+++ b/apps/desktop/electron/main/mcp-call-registry.ts
@@ -0,0 +1,42 @@
+/** Owns cancellation for MCP calls without closing a server shared by sessions. */
+export class McpCallRegistry {
+ private readonly calls = new Map<string, Set<AbortController>>();
+
+ async run<T>(
+ sessionId: string | null | undefined,
+ invoke: (signal: AbortSignal | undefined) => Promise<T>,
+ parentSignal?: AbortSignal,
+ ): Promise<T> {
+ if (!sessionId && !parentSignal) return invoke(undefined);
+ const controller = new AbortController();
+ const abort = () => controller.abort();
+ if (parentSignal?.aborted) abort();
+ else parentSignal?.addEventListener("abort", abort, { once: true });
+ if (sessionId) {
+ let active = this.calls.get(sessionId);
+ if (!active) {
+ active = new Set();
+ this.calls.set(sessionId, active);
+ }
+ active.add(controller);
+ }
+ try {
+ return await invoke(controller.signal);
+ } finally {
+ parentSignal?.removeEventListener("abort", abort);
+ if (sessionId) {
+ const active = this.calls.get(sessionId);
+ active?.delete(controller);
+ if (active?.size === 0) this.calls.delete(sessionId);
+ }
+ }
+ }
+
+ cancelSession(sessionId: string): void {
+ for (const controller of this.calls.get(sessionId) ?? []) controller.abort();
+ }
+
+ cancelAll(): void {
+ for (const sessionId of this.calls.keys()) this.cancelSession(sessionId);
+ }
+}
diff --git a/apps/desktop/electron/main/plugin-mcp.ts b/apps/desktop/electron/main/plugin-mcp.ts
index 30f005444..fe96a7170 100644
--- a/apps/desktop/electron/main/plugin-mcp.ts
+++ b/apps/desktop/electron/main/plugin-mcp.ts
@@ -48,7 +48,7 @@ export type JsonRpcMessage = {
* the client speak the same JSON-RPC dialect over a pipe or over HTTP.
*/
export type McpTransport = {
- send: (message: JsonRpcMessage, timeoutMs?: number) => Promise<void>;
+ send: (message: JsonRpcMessage, timeoutMs?: number, signal?: AbortSignal) => Promise<void>;
close: () => void;
};
@@ -297,9 +297,12 @@ function createHttpTransport(
const activeControllers = new Set<AbortController>();
return {
- send: async (message, timeoutMs = options.timeoutMs) => {
+ send: async (message, timeoutMs = options.timeoutMs, signal) => {
if (closed) throw mcpError("UNAVAILABLE", "mcp session is closed");
const controller = new AbortController();
+ const abort = () => controller.abort();
+ if (signal?.aborted) abort();
+ else signal?.addEventListener("abort", abort, { once: true });
activeControllers.add(controller);
const timer = setTimeout(() => controller.abort(), timeoutMs);
let url = options.url;
@@ -384,6 +387,7 @@ function createHttpTransport(
}
} finally {
clearTimeout(timer);
+ signal?.removeEventListener("abort", abort);
activeControllers.delete(controller);
}
},
@@ -465,14 +469,31 @@ export class McpServerClient {
return this.connecting;
}
- async callTool(toolName: string, args: unknown): Promise<unknown> {
- await this.connect();
+ async callTool(toolName: string, args: unknown, signal?: AbortSignal): Promise<unknown> {
+ if (signal?.aborted) throw mcpError("TOOL_ABORTED", "mcp tool call aborted");
+ const connecting = this.connect();
+ if (signal) {
+ let rejectAbort!: (error: Error) => void;
+ const aborted = new Promise<never>((_, reject) => { rejectAbort = reject; });
+ const abort = () => rejectAbort(mcpError("TOOL_ABORTED", "mcp tool call aborted"));
+ signal.addEventListener("abort", abort, { once: true });
+ if (signal.aborted) abort();
+ try {
+ await Promise.race([connecting, aborted]);
+ } finally {
+ signal.removeEventListener("abort", abort);
+ }
+ } else {
+ await connecting;
+ }
+ if (signal?.aborted) throw mcpError("TOOL_ABORTED", "mcp tool call aborted");
const started = Date.now();
try {
const result = (await this.request(
"tools/call",
{ name: toolName, arguments: args ?? {} },
this.opts.callTimeoutMs ?? MCP_CALL_TIMEOUT_MS,
+ signal,
)) as { content?: unknown; isError?: boolean } | null;
if (result && typeof result === "object" && result.isError) {
throw mcpError("TOOL_FAILED", describeMcpContent(result.content) || "mcp tool failed");
@@ -644,24 +665,40 @@ export class McpServerClient {
}
}
- private request(method: string, params: unknown, timeoutMs: number): Promise<unknown> {
+ private request(method: string, params: unknown, timeoutMs: number, signal?: AbortSignal): Promise<unknown> {
const transport = this.transport;
if (!transport) {
return Promise.reject(mcpError("UNAVAILABLE", "mcp server is not connected"));
}
+ if (signal?.aborted) return Promise.reject(mcpError("TOOL_ABORTED", "mcp tool call aborted"));
const id = this.nextId++;
return new Promise<unknown>((resolvePromise, rejectPromise) => {
+ const removeAbort = () => signal?.removeEventListener("abort", abort);
+ const abort = () => {
+ if (!this.pending.delete(id)) return;
+ clearTimeout(timer);
+ removeAbort();
+ rejectPromise(mcpError("TOOL_ABORTED", "mcp tool call aborted"));
+ void transport.send({ jsonrpc: "2.0", method: "notifications/cancelled", params: { requestId: id, reason: "cancelled" } }).catch(() => undefined);
+ };
const timer = setTimeout(() => {
this.pending.delete(id);
+ removeAbort();
rejectPromise(mcpError("TIMEOUT", `mcp ${method} timed out after ${timeoutMs}ms`));
}, timeoutMs);
- this.pending.set(id, { resolve: resolvePromise, reject: rejectPromise, timer });
- void transport.send({ jsonrpc: "2.0", id, method, params }, timeoutMs).catch((error: Error) => {
+ this.pending.set(id, {
+ resolve: (value) => { removeAbort(); resolvePromise(value); },
+ reject: (error) => { removeAbort(); rejectPromise(error); },
+ timer,
+ });
+ signal?.addEventListener("abort", abort, { once: true });
+ if (signal?.aborted) abort();
+ void transport.send({ jsonrpc: "2.0", id, method, params }, timeoutMs, signal).catch((error: Error) => {
const entry = this.pending.get(id);
if (!entry) return;
this.pending.delete(id);
clearTimeout(entry.timer);
- rejectPromise(error);
+ entry.reject(error);
});
});
}
diff --git a/apps/desktop/electron/main/plugin-runtime.ts b/apps/desktop/electron/main/plugin-runtime.ts
index 7d57eba12..89ac117eb 100644
--- a/apps/desktop/electron/main/plugin-runtime.ts
+++ b/apps/desktop/electron/main/plugin-runtime.ts
@@ -87,6 +87,7 @@ import {
import { desktopDataDir } from "./data-paths";
import { McpServerClient, type McpServerClientOptions } from "./plugin-mcp";
import { PluginToolInvocations, type PluginToolInvocation } from "./plugin-tool-invocations";
+import { McpCallRegistry } from "./mcp-call-registry";
import { DevPluginWatcher, type DevPluginWatcherDeps } from "./plugin-watcher";
import { parseAllowedExternalUrl } from "./safe-open-external";
import type { PluginAppearance } from "../shared/plugin-panel-chrome";
@@ -1287,6 +1288,7 @@ export class PluginRuntime {
private themeAssets = new Map<string, Map<string, string>>();
private themeAssetGroups = new Map<string, Map<string, ReadonlyMap<string, string>>>();
private mcpClients = new Map<string, McpServerClient[]>();
+ private readonly mcpCalls = new McpCallRegistry();
private serviceStates = new Map<string, PluginServiceStatus>();
private restarts = new Map<string, RestartRecord>();
private busSubscriptions = new Map<string, BusSubscription>();
@@ -1816,6 +1818,7 @@ export class PluginRuntime {
/** Abort this session's invocations without affecting sibling sessions. */
cancelSessionTools(sessionId: string, reason = "Session tool execution aborted"): void {
this.toolInvocations.cancelSession(sessionId, reason);
+ this.mcpCalls.cancelSession(sessionId);
}
/** Deregister contributions, run `onUnload` in the child, then stop it. */
@@ -1914,6 +1917,7 @@ export class PluginRuntime {
* `onUnload` must never be the reason the app appears to hang on quit.
*/
async disposeAll(): Promise<void> {
+ this.mcpCalls.cancelAll();
const loadedPlugins = [...this.loaded.values()];
// Mark first, in one pass: a child that dies while a sibling is still
// stopping must already be covered by the guard in `handleChildExit`.
@@ -3541,7 +3545,11 @@ export class PluginRuntime {
// Remote code the desktop cannot inspect; never silently auto-approved.
risk: "medium",
schema: tool.inputSchema,
- execute: async (toolArgs) => client.callTool(tool.name, toolArgs),
+ execute: async (toolArgs, ctx) => this.mcpCalls.run(
+ ctx?.sessionId,
+ (signal) => client.callTool(tool.name, toolArgs, signal),
+ ctx?.signal,
+ ),
});
}
}
diff --git a/apps/desktop/electron/main/runtime/host.ts b/apps/desktop/electron/main/runtime/host.ts
index 95bdcfcc1..5f35052eb 100644
--- a/apps/desktop/electron/main/runtime/host.ts
+++ b/apps/desktop/electron/main/runtime/host.ts
@@ -160,14 +160,16 @@ export function createHostRuntime({
let payload: Record<string, unknown>;
if (q.toolName.startsWith("mcp_")) {
try {
- const result = await userMcp.callTool(q.toolName, q.args, projectPath);
+ const result = await userMcp.callTool(q.toolName, q.args, projectPath, q.sessionId);
payload = { executionId: q.executionId, ok: true, content: result ?? null };
} catch (e) {
payload = {
executionId: q.executionId,
ok: false,
errorCode:
- (e as { errorCode?: string })?.errorCode ?? "TOOL_FAILED",
+ (e as { code?: string; errorCode?: string })?.code === "TOOL_ABORTED"
+ ? "TOOL_ABORTED"
+ : (e as { errorCode?: string })?.errorCode ?? "TOOL_FAILED",
content: { error: e instanceof Error ? e.message : String(e) },
};
}
@@ -269,7 +271,7 @@ export function createHostRuntime({
payload = {
executionId: q.executionId,
ok: false,
- errorCode: code === "PERMISSION_DENIED" ? "PERMISSION_DENIED" : "TOOL_FAILED",
+ errorCode: code === "PERMISSION_DENIED" || code === "TOOL_ABORTED" ? code : "TOOL_FAILED",
content: { error: e instanceof Error ? e.message : String(e) },
};
}
diff --git a/apps/desktop/electron/main/user-mcp.ts b/apps/desktop/electron/main/user-mcp.ts
index 5e27f720f..5a7186d31 100644
--- a/apps/desktop/electron/main/user-mcp.ts
+++ b/apps/desktop/electron/main/user-mcp.ts
@@ -6,6 +6,7 @@ import {
} from "@pi-desktop/shared";
import { userMcpToolName } from "@pi-desktop/plugin-sdk";
import type { McpServerClient, McpTool } from "./plugin-mcp";
+import { McpCallRegistry } from "./mcp-call-registry.ts";
/**
* MCP servers the user configured directly, with no plugin around them.
@@ -78,6 +79,7 @@ const MAX_ACTIVE_SERVERS = 16;
export class UserMcpRuntime {
private entries = new Map<string, Entry>();
private statusRefreshes = new Map<string, Promise<void>>();
+ 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[]>();
@@ -213,6 +215,16 @@ export class UserMcpRuntime {
fullName: string,
args: unknown,
projectPath: string | null | undefined,
+ sessionId?: string,
+ ): Promise<unknown> {
+ return this.calls.run(sessionId, (signal) => this.callToolActive(fullName, args, projectPath, signal));
+ }
+
+ private async callToolActive(
+ fullName: string,
+ args: unknown,
+ projectPath: string | null | undefined,
+ signal?: AbortSignal,
): Promise<unknown> {
const found = this.findTool(fullName);
if (!found) {
@@ -252,7 +264,7 @@ export class UserMcpRuntime {
}
// Do not retry tools/call: a failed response may have followed a mutation.
try {
- return await entry.client.callTool(found.toolName, args);
+ 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) {
@@ -304,11 +316,16 @@ export class UserMcpRuntime {
/** Drop every connection, e.g. on quit. */
disposeAll(): void {
+ this.calls.cancelAll();
for (const entry of this.entries.values()) entry.client.close();
this.entries.clear();
this.discoveredTools.clear();
}
+ cancelSessionCalls(sessionId: string): void {
+ this.calls.cancelSession(sessionId);
+ }
+
private findTool(fullName: string): UserMcpToolDescriptor | undefined {
for (const [serverId, tools] of this.discoveredTools) {
for (const tool of tools) {
diff --git a/apps/desktop/test/mcp-call-registry.test.mjs b/apps/desktop/test/mcp-call-registry.test.mjs
new file mode 100644
index 000000000..eebdde80e
--- /dev/null
+++ b/apps/desktop/test/mcp-call-registry.test.mjs
@@ -0,0 +1,20 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { McpCallRegistry } from "../electron/main/mcp-call-registry.ts";
+
+test("canceling one session leaves another MCP call active", async () => {
+ const calls = new McpCallRegistry();
+ let resolveOther;
+ const canceled = calls.run("session-a", (signal) => new Promise((_, reject) => {
+ signal.addEventListener("abort", () => reject(new Error("aborted")), { once: true });
+ }));
+ const other = calls.run("session-b", (signal) => new Promise((resolve, reject) => {
+ resolveOther = resolve;
+ signal.addEventListener("abort", () => reject(new Error("wrong session aborted")), { once: true });
+ }));
+
+ calls.cancelSession("session-a");
+ await assert.rejects(canceled, /aborted/);
+ resolveOther("finished");
+ assert.equal(await other, "finished");
+});
diff --git a/apps/desktop/test/plugin-mcp.test.mjs b/apps/desktop/test/plugin-mcp.test.mjs
index ac41df145..9ffc46926 100644
--- a/apps/desktop/test/plugin-mcp.test.mjs
+++ b/apps/desktop/test/plugin-mcp.test.mjs
@@ -380,6 +380,86 @@ test("a remote MCP tool can run longer than the connection timeout", async (t) =
const result = await client.callTool("slow", {});
assert.equal(describeMcpContent(result.content), "finished");
});
+test("aborting one HTTP MCP call cancels its request", async (t) => {
+ let callStarted;
+ let cancellationReceived;
+ const started = new Promise((resolve) => { callStarted = resolve; });
+ const canceled = new Promise((resolve) => { cancellationReceived = resolve; });
+ let callId;
+ const fetchImpl = async (_url, options) => {
+ const message = JSON.parse(options.body);
+ if (message.method === "notifications/initialized") return new Response(null, { status: 202 });
+ if (message.method === "notifications/cancelled") {
+ cancellationReceived(message.params.requestId);
+ return new Response(null, { status: 202 });
+ }
+ if (message.method === "tools/call") {
+ callId = message.id;
+ callStarted();
+ return new Promise((_, reject) => {
+ options.signal.addEventListener("abort", () => reject(new DOMException("aborted", "AbortError")), { once: true });
+ });
+ }
+ const result = message.method === "initialize"
+ ? { protocolVersion: message.params.protocolVersion, capabilities: {} }
+ : { tools: [{ name: "slow" }] };
+ return new Response(JSON.stringify({ jsonrpc: "2.0", id: message.id, result }), {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ });
+ };
+ const client = new McpServerClient({
+ rootPath: mkdtempSync(join(tmpdir(), "pi-mcp-cancel-")),
+ server: { id: "remote", transport: "http", url: "https://mcp.example.com/mcp" },
+ values: {},
+ fetchImpl,
+ });
+ t.after(() => client.close());
+ await client.connect();
+
+ const controller = new AbortController();
+ const call = client.callTool("slow", {}, controller.signal);
+ await started;
+ controller.abort();
+ await assert.rejects(call, { code: "TOOL_ABORTED" });
+ assert.equal(await canceled, callId);
+});
+
+test("aborting a tool waiting for a shared handshake does not send tools/call", async (t) => {
+ let finishInitialize;
+ let initializeStarted;
+ const started = new Promise((resolve) => { initializeStarted = resolve; });
+ const methods = [];
+ const fetchImpl = async (_url, options) => {
+ const message = JSON.parse(options.body);
+ methods.push(message.method);
+ if (message.method === "initialize") {
+ initializeStarted();
+ return new Promise((resolve) => { finishInitialize = () => resolve(new Response(JSON.stringify({
+ jsonrpc: "2.0", id: message.id,
+ result: { protocolVersion: message.params.protocolVersion, capabilities: {} },
+ }), { status: 200, headers: { "content-type": "application/json" } })); });
+ }
+ if (message.method === "notifications/initialized") return new Response(null, { status: 202 });
+ return new Response(JSON.stringify({ jsonrpc: "2.0", id: message.id, result: { tools: [{ name: "echo" }] } }), {
+ status: 200, headers: { "content-type": "application/json" },
+ });
+ };
+ const client = new McpServerClient({
+ rootPath: mkdtempSync(join(tmpdir(), "pi-mcp-cancel-")),
+ server: { id: "remote", transport: "http", url: "https://mcp.example.com/mcp" },
+ values: {}, fetchImpl,
+ });
+ t.after(() => client.close());
+ const controller = new AbortController();
+ const call = client.callTool("echo", {}, controller.signal);
+ await started;
+ controller.abort();
+ await assert.rejects(call, { code: "TOOL_ABORTED" });
+ finishInitialize();
+ await client.connect();
+ assert.ok(!methods.includes("tools/call"));
+});
test("an http failure is reported as HTTP_ERROR", async (t) => {
const { url } = await startHttpServer(t);
@@ -556,7 +636,8 @@ test("discovered mcp tools ride the existing plugin tool path", () => {
assert.match(register, /this\.tools\.set\(fullName/);
// Remote code the desktop cannot inspect never auto-approves.
assert.match(register, /risk: "medium"/);
- assert.match(register, /client\.callTool\(tool\.name, toolArgs\)/);
+ assert.match(register, /this\.mcpCalls\.run\(/);
+ assert.match(register, /client\.callTool\(tool\.name, toolArgs, signal\)/);
// A server that fails to answer must not fail the plugin load.
assert.match(register, /await client\.connect\(\);\s*\n\s*\} catch \{/);
});
diff --git a/apps/desktop/test/user-mcp.test.mjs b/apps/desktop/test/user-mcp.test.mjs
index 16722a7bc..576dcd389 100644
--- a/apps/desktop/test/user-mcp.test.mjs
+++ b/apps/desktop/test/user-mcp.test.mjs
@@ -157,6 +157,37 @@ test("refreshing HTTP MCP status detects a server that went offline", async (t)
assert.deepEqual(await pendingCall, { content: [{ type: "text", text: "completed" }] });
assert.equal(pings, 2);
});
+test("stopping one session cancels only its active MCP call", async (t) => {
+ const started = new Map();
+ const finish = new Map();
+ const client = {
+ isConnected: () => true,
+ getTools: () => [{ name: "lookup" }],
+ close: () => {},
+ connect: async () => [{ name: "lookup" }],
+ callTool: async (_name, args, signal) => new Promise((resolve, reject) => {
+ finish.set(args.id, resolve);
+ signal.addEventListener("abort", () => reject(new Error("aborted")), { once: true });
+ started.get(args.id)();
+ }),
+ };
+ const rt = new UserMcpRuntime({ createClient: () => client });
+ t.after(() => rt.disposeAll());
+ rt.setRecords([stubRecord("/unused")]);
+ await rt.toolsForProject("/repo");
+
+ const firstStarted = new Promise((resolve) => started.set("first", resolve));
+ const first = rt.callTool("mcp_stub_lookup", { id: "first" }, "/repo", "session-a");
+ await firstStarted;
+ const secondStarted = new Promise((resolve) => started.set("second", resolve));
+ const second = rt.callTool("mcp_stub_lookup", { id: "second" }, "/repo", "session-b");
+ await secondStarted;
+
+ rt.cancelSessionCalls("session-a");
+ await assert.rejects(first, /aborted/);
+ finish.get("second")("finished");
+ assert.equal(await second, "finished");
+});
test("a project-scoped server is invisible outside its projects", async (t) => {
const dir = stubDir();
diff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.md
index bfc1d5f8c..e88bdf42e 100644
--- a/docs/spec/03-runtime/01-ipc-protocol.md
+++ b/docs/spec/03-runtime/01-ipc-protocol.md
@@ -1465,6 +1465,11 @@ 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.
+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.
+Cancellation stops the local wait, while a server may ignore the notification
+and finish an already started side effect.
Desktop-only channels scan configuration written by other agent tools on the
same machine — Claude Desktop (`claude_desktop_config.json` on macOS, Windows
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 9ad5f6648..6f4b0fd01 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -2775,6 +2775,20 @@ identify the platform validation still needed.
- **Acceptance**: G (MCP bridge) + E (tools & permissions) + Security
- **Status**: Unit-covered (`plugin-mcp.test.mjs` stdio + HTTP stubs); agent-facing scenario Draft
+#### E2E-MCP-CANCEL: Stop interrupts only the calling session's MCP request
+
+- **Preconditions**: Two Agent sessions share one user or plugin MCP server;
+ each has a pending tool call, and the server records cancellation notifications.
+- **Steps**: Stop the first session while both calls are pending, then allow the
+ second call to finish. Repeat with a remote HTTP server and a stdio server.
+- **Expected**: The first request receives `notifications/cancelled` and cannot
+ produce a successful tool result after Stop. The second session's call finishes normally;
+ its server connection remains available. Closing the app cancels remaining
+ requests without retaining listeners.
+- **Specs linked**: `03-runtime/01-ipc-protocol.md` §12a,
+ `07-plugins/04-plugin-security.md` §8.1
+- **Status**: Client and session-isolation unit-covered; full desktop journey Draft
+
#### E2E-024L: Resident plugin service is supervised and visible
- **Preconditions**: `examples/plugins/hello` enabled with `background.service` granted.
diff --git a/docs/spec/07-plugins/04-plugin-security.md b/docs/spec/07-plugins/04-plugin-security.md
index ffaac8bc1..dcc91511b 100644
--- a/docs/spec/07-plugins/04-plugin-security.md
+++ b/docs/spec/07-plugins/04-plugin-security.md
@@ -375,6 +375,9 @@ manifest did not name:
deferred on-demand entries behind `ToolSearch`, not as an always-present list.
Servers are connected lazily and torn down when the plugin unloads or is
disabled.
+ Stopping the calling session cancels that session's in-flight MCP request and
+ sends `notifications/cancelled` to the server. A shared server connection and
+ calls owned by other sessions remain active.
## 8.2 Desktop control and device access
diff --git a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md
index d11d1d4c0..e75493ac4 100644
--- a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md
+++ b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md
@@ -1199,6 +1199,8 @@ type PluginSummary = {
的 label 让项目记录遮蔽全局记录,再过滤关闭项;因此关闭的项目记录仍然会
遮蔽全局项。仅桌面的 `mcp/test` IPC 操作用于强制连接测试,并把状态返回
MCP 编辑器。设置页的 `mcp.list` 在返回状态前会探测此前就绪的远程连接;服务器失联时,列表显示 `failed`,而不是保留过时的 `ready`。服务器恢复后,“测试连接”会重试。探测失败不会中断正在执行的工具调用;“测试连接”会先关闭旧客户端再重试。
+MCP 编辑器。
+停止会话会中止该会话正在执行的用户 MCP 工具调用,并向服务器发送 `notifications/cancelled`。其他会话共用的连接保持可用;已取消的调用不会重放。取消会结束本地等待,但服务器可能忽略通知并完成已经开始的副作用。
```ts
type McpServerStatus = {
diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
index c863a37b1..5e1711352 100644
--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
@@ -1392,6 +1392,14 @@ task-candidate E2E 从请求工作树运行,但使用主工作区已经准备
- **接受**:G(MCP 桥)+ E(工具和权限)+ 安全
- **状态**:单位覆盖(`plugin-mcp.test.mjs` stdio + HTTP 存根);面向代理的场景草稿
+#### E2E-MCP-CANCEL:停止操作只中断调用方会话的 MCP 请求
+
+- **先决条件**:两个 Agent 会话共用用户或插件 MCP 服务器,均有待处理工具调用,服务器记录取消通知。
+- **步骤**:两项调用待处理时停止第一个会话,再让第二项调用完成;分别对远程 HTTP 和 stdio 服务器重复。
+- **预期**:第一个请求收到 `notifications/cancelled`,停止后不会产生成功的工具结果;第二个会话的调用正常完成且连接可继续使用。关闭应用会取消其余请求并清理监听器。
+- **关联规格**:`03-runtime/01-ipc-protocol.md` §12a、`07-plugins/04-plugin-security.md` §8.1
+- **状态**:客户端及会话隔离已有单元测试;完整桌面流程待验证
+
#### E2E-024L:常驻插件服务受监督且可见
- **先决条件**:在授予 `background.service` 的情况下启用 `examples/plugins/hello`。
diff --git a/docs/zh-CN/spec/07-plugins/04-plugin-security.md b/docs/zh-CN/spec/07-plugins/04-plugin-security.md
index 0622d7d6a..1486cf0c6 100644
--- a/docs/zh-CN/spec/07-plugins/04-plugin-security.md
+++ b/docs/zh-CN/spec/07-plugins/04-plugin-security.md
@@ -290,6 +290,7 @@ MCP 服务器是 `net.fetch` 旁边的第二个出口路径,因此它是声明
拒绝,而不是贡献其目录的一个前缀,因为 MCP 工具是以延迟加载的按需条目
(`ToolSearch` 之后)而非常驻列表的形式到达模型的。服务器按需连接,
并在插件卸载或禁用时关闭。
+ 停止调用方会话会取消该会话正在执行的 MCP 请求,并向服务器发送 `notifications/cancelled`;共享连接及其他会话的调用保持有效。
## 8.2 桌面控制与设备访问