Skip to content

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

fix(mcp): refresh remote server status in settings (#1004)

咕噜水蜜桃8511c486ad74
diff --git a/apps/desktop/electron/main/ipc/mcp-ipc.ts b/apps/desktop/electron/main/ipc/mcp-ipc.ts
index eedb04b95..224bd95e8 100644
--- a/apps/desktop/electron/main/ipc/mcp-ipc.ts
+++ b/apps/desktop/electron/main/ipc/mcp-ipc.ts
@@ -63,7 +63,7 @@ handle(IPC.invoke.mcpList, async (query: Partial<AgentCapabilityQuery> = {}) =>
// list itself must include disabled records for the settings page.
await refreshUserMcp(currentWorkspacePath());
const statuses = await Promise.all(
- userMcp.listStatuses().map(async (status) => ({
+ (await userMcp.refreshStatuses()).map(async (status) => ({
...status,
hasOauth: oauth ? await oauth.hasOAuth(status.serverId) : false,
})),
diff --git a/apps/desktop/electron/main/plugin-mcp.ts b/apps/desktop/electron/main/plugin-mcp.ts
index dfa93f2e6..30f005444 100644
--- a/apps/desktop/electron/main/plugin-mcp.ts
+++ b/apps/desktop/electron/main/plugin-mcp.ts
@@ -485,6 +485,11 @@ export class McpServerClient {
}
}
+ /** Probe a live connection without changing its discovered tool catalog. */
+ async ping(timeoutMs = 5_000): Promise<void> {
+ await this.request("ping", {}, timeoutMs);
+ }
+
close(): void {
const transport = this.transport;
this.transport = null;
diff --git a/apps/desktop/electron/main/user-mcp.ts b/apps/desktop/electron/main/user-mcp.ts
index 6aaf08fdf..5e27f720f 100644
--- a/apps/desktop/electron/main/user-mcp.ts
+++ b/apps/desktop/electron/main/user-mcp.ts
@@ -29,7 +29,7 @@ export type UserMcpToolDescriptor = {
/** The slice of {@link McpServerClient} this runtime drives. */
export type UserMcpClient = Pick<
McpServerClient,
- "connect" | "callTool" | "getTools" | "isConnected" | "close"
+ "connect" | "callTool" | "getTools" | "isConnected" | "close" | "ping"
>;
export type UserMcpClientConfig = ConstructorParameters<typeof McpServerClient>[0];
@@ -77,6 +77,7 @@ const MAX_ACTIVE_SERVERS = 16;
export class UserMcpRuntime {
private entries = new Map<string, Entry>();
+ private statusRefreshes = new Map<string, Promise<void>>();
// 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[]>();
@@ -120,6 +121,40 @@ export class UserMcpRuntime {
return this.records.map((record) => this.statusFor(record.id));
}
+ /** Confirm ready remote connections when the settings page refreshes. */
+ async refreshStatuses(): Promise<McpServerStatus[]> {
+ await Promise.all([...this.entries].map(async ([id, entry]) => {
+ if (entry.record.transport === "stdio" || entry.status.state !== "ready") return;
+ let pending = this.statusRefreshes.get(id);
+ if (!pending) {
+ pending = (async () => {
+ try {
+ await entry.client.ping();
+ } catch (error) {
+ if (this.entries.get(id) !== 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";
+ entry.status = {
+ ...entry.status,
+ state: "failed",
+ toolCount: 0,
+ message: message.slice(0, 500),
+ updatedAt: Date.now(),
+ };
+ }
+ })();
+ this.statusRefreshes.set(id, pending);
+ }
+ try {
+ await pending;
+ } finally {
+ if (this.statusRefreshes.get(id) === pending) this.statusRefreshes.delete(id);
+ }
+ }));
+ return this.listStatuses();
+ }
+
statusFor(serverId: string): McpServerStatus {
const entry = this.entries.get(serverId);
if (entry) return { ...entry.status };
diff --git a/apps/desktop/test/plugin-mcp.test.mjs b/apps/desktop/test/plugin-mcp.test.mjs
index 3082748a8..ac41df145 100644
--- a/apps/desktop/test/plugin-mcp.test.mjs
+++ b/apps/desktop/test/plugin-mcp.test.mjs
@@ -285,6 +285,11 @@ async function startHttpServer(t, { slowToolDelayMs } = {}) {
res.writeHead(202, { "content-type": "text/plain" }).end("Accepted");
return;
}
+ if (message.method === "ping") {
+ res.writeHead(200, { "content-type": "application/json" });
+ res.end(JSON.stringify({ jsonrpc: "2.0", id: message.id, result: {} }));
+ return;
+ }
if (message.method === "tools/list") {
res.writeHead(200, { "content-type": "text/event-stream" });
res.end(
@@ -352,6 +357,8 @@ test("a remote mcp server negotiates over http and keeps its session", async (t)
);
const result = await client.callTool("headers", {});
assert.equal(describeMcpContent(result.content), `sess-42|sk-test|${MCP_PROTOCOL_VERSION}`);
+ await client.ping();
+ assert.equal(requests.at(-1).message.method, "ping");
// The very first request cannot carry a session id, later ones must.
assert.equal(requests[0].headers["mcp-session-id"], undefined);
assert.equal(requests[0].headers["x-api-key"], "sk-test");
diff --git a/apps/desktop/test/user-mcp.test.mjs b/apps/desktop/test/user-mcp.test.mjs
index a8585023b..16722a7bc 100644
--- a/apps/desktop/test/user-mcp.test.mjs
+++ b/apps/desktop/test/user-mcp.test.mjs
@@ -113,6 +113,51 @@ test("a global server contributes mcp_-prefixed tools to any session", async (t)
assert.equal((await rt.toolsForProject(null)).length, 2);
});
+test("refreshing HTTP MCP status detects a server that went offline", async (t) => {
+ let online = true;
+ let pings = 0;
+ let connected = false;
+ let finishCall;
+ let failCall;
+ let markCallStarted;
+ const callStarted = new Promise((resolve) => { markCallStarted = resolve; });
+ const client = {
+ isConnected: () => connected,
+ getTools: () => [{ name: "lookup" }],
+ connect: async () => { connected = true; return [{ name: "lookup" }]; },
+ callTool: () => new Promise((resolve, reject) => {
+ finishCall = resolve;
+ failCall = reject;
+ markCallStarted();
+ }),
+ ping: async () => {
+ pings += 1;
+ if (!online) throw new Error("server offline");
+ },
+ close: () => {
+ connected = false;
+ failCall?.(new Error("tool call interrupted by close"));
+ },
+ };
+ const rt = new UserMcpRuntime({ createClient: () => client });
+ t.after(() => rt.disposeAll());
+ rt.setRecords([stubRecord("/unused", { transport: "http", command: undefined, args: undefined, url: "http://127.0.0.1:9999/mcp" })]);
+
+ await rt.toolsForProject("/repo");
+ assert.equal(rt.statusFor("stub").state, "ready");
+ assert.equal((await rt.refreshStatuses())[0].state, "ready");
+ const pendingCall = rt.callTool("mcp_stub_lookup", {}, "/repo");
+ await callStarted;
+ online = false;
+ const statuses = await rt.refreshStatuses();
+ assert.equal(statuses[0].state, "failed");
+ assert.equal(rt.statusFor("stub").state, "failed");
+ assert.equal(connected, true, "a settings probe must not close an in-flight call");
+ finishCall({ content: [{ type: "text", text: "completed" }] });
+ assert.deepEqual(await pendingCall, { content: [{ type: "text", text: "completed" }] });
+ assert.equal(pings, 2);
+});
+
test("a project-scoped server is invisible outside its projects", async (t) => {
const dir = stubDir();
const rt = runtime(t);
diff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.md
index f1e6abd50..bfc1d5f8c 100644
--- a/docs/spec/03-runtime/01-ipc-protocol.md
+++ b/docs/spec/03-runtime/01-ipc-protocol.md
@@ -1462,6 +1462,9 @@ project records from the global set by id or case-insensitive label before it
filters disabled records, so a disabled project record still shadows a global
one. The desktop-only `mcp/test` IPC action forces one connection test and
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.
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 c0c86e58b..9ad5f6648 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -6830,7 +6830,9 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
the same tool in the existing session without searching again.
11. Repeat with the restarted stub omitting that tool, and with the server
disabled or scoped away before recovery. Also try concurrent calls after
- a disconnect and a server that fails its recovery handshake.
+ a disconnect and a server that fails its recovery handshake.
+ 12. Connect the HTTP server, stop it, and refresh the MCP settings page.
+ Test connection again after restarting the server.
- **Expected**:
- The activated tool works after a transport restart without a second search;
concurrent calls share one handshake. The fresh server list must still
@@ -6854,6 +6856,8 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
- The broken command records `failed` with a message, contributes no tools,
and is not re-dialled on the following session assembly; pressing Test
retries it.
+ - A stopped HTTP server loses its `ready` status on settings refresh and
+ reports `failed`; Test connection restores `ready` after it restarts.
- **Specs linked**: `07-plugins/01-plugin-system.md` §12,
`03-runtime/01-ipc-protocol.md` §12a, `08-meta/decisions-log.md` (D192, D193)
- **Acceptance**: E (tools & permissions), Quality
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 04148043a..d11d1d4c0 100644
--- a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md
+++ b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md
@@ -1198,7 +1198,7 @@ type PluginSummary = {
项目级请求缺少 `projectPath` 时无效。`mcp.active` 会先按 ID 或不区分大小写
的 label 让项目记录遮蔽全局记录,再过滤关闭项;因此关闭的项目记录仍然会
遮蔽全局项。仅桌面的 `mcp/test` IPC 操作用于强制连接测试,并把状态返回
-MCP 编辑器。
+MCP 编辑器。设置页的 `mcp.list` 在返回状态前会探测此前就绪的远程连接;服务器失联时,列表显示 `failed`,而不是保留过时的 `ready`。服务器恢复后,“测试连接”会重试。探测失败不会中断正在执行的工具调用;“测试连接”会先关闭旧客户端再重试。
```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 58176c5f0..c863a37b1 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
@@ -4653,6 +4653,7 @@ eleven-tool-round desktop paths are verified by
调用之间终止 stub 服务器进程。在同一会话中再次调用该工具,不再搜索。
11. 用重启后不再提供该工具的 stub 重复;以及在恢复前禁用或改出作用域。
也试一次断开后的并发调用,以及恢复握手失败的服务器。
+ 12. 连接 HTTP 服务器后将其停止,刷新 MCP 设置页;重启服务器后再次测试连接。
- **预期**:
- 传输重启后,已激活的工具无需再次搜索即可使用;并发调用共享一次握手。
新的服务器列表仍须公布该工具。已移除的工具和未激活的服务器在不执行
@@ -4675,6 +4676,7 @@ eleven-tool-round desktop paths are verified by
- 损坏的命令记录 `failed` 并带有一条消息,不提供任何工具,
并且不会在下一次会议上重拨;压制测试
重试。
+ - HTTP 服务器停止后,设置页刷新显示 `failed`;重启后“测试连接”恢复为 `ready`。
- **链接规格**:`07-plugins/01-plugin-system.md` §12,
`03-runtime/01-ipc-protocol.md` §12a、`08-meta/decisions-log.md`(D192、D193)
- **验收**:E(工具和权限)、质量