patchwork-os 0.2.0-beta.10.canary.136 → 0.2.0-beta.10.canary.139

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -118,7 +118,7 @@ The bridge runs without any flags. No recipes, no automation, no dashboard — j
118
118
  | Client | Protocol |
119
119
  |---|---|
120
120
  | Claude Code CLI | WebSocket `ws://127.0.0.1:<port>` |
121
- | Claude Desktop | stdio shim → WebSocket |
121
+ | Claude Desktop, Grok Build (Grok CLI) | stdio shim → WebSocket |
122
122
  | Gemini CLI, Codex CLI, claude.ai | Streamable HTTP + Bearer token |
123
123
 
124
124
  **Connecting Gemini CLI:**
@@ -134,6 +134,25 @@ gemini mcp add patchwork http://127.0.0.1:<port>/mcp \
134
134
 
135
135
  The bridge auto-responds to the GET probe Gemini sends before initializing, so it shows as **Connected** immediately.
136
136
 
137
+ **Connecting Grok Build (Grok CLI):**
138
+
139
+ Grok Build connects over the same **stdio shim** as Claude Desktop. Add this block to `~/.grok/config.toml` (the `--workspace` arg is the important part):
140
+
141
+ ```toml
142
+ [mcp_servers.patchwork]
143
+ command = "claude-ide-bridge"
144
+ args = ["shim", "--workspace", "/absolute/path/to/your/project"]
145
+ enabled = true
146
+ ```
147
+
148
+ Three gotchas that look like bugs but aren't:
149
+
150
+ - **`--workspace` is required.** Without it the shim picks the newest bridge lock across *all* workspaces — in a multi-bridge setup (orchestrator, leftover dev bridges) that can be the wrong or a dead bridge, so tools act on the wrong project or hang. Always pin it to your project path.
151
+ - **`grok mcp doctor` hangs — don't use it.** The shim is a long-lived relay that stays open for the session, so `doctor` waits forever for it to exit. Verify with the in-TUI **`/mcps`** instead, or run `claude-ide-bridge shim --ping` (one-shot: connects, lists tools, exits).
152
+ - **The approval gate can park tool calls.** If `~/.patchwork/config.json` has `"approvalGate": "all"` (or `"high"`), tool calls queue for human approval in the dashboard and look like they're hanging to Grok. Set it to `"high"` (gate only risky writes) or `"off"`, or approve in the dashboard at `localhost:3000`.
153
+
154
+ Grok Build can also connect over Streamable HTTP + Bearer (same as Gemini, above) if you'd rather not use the shim.
155
+
137
156
  **Tool modes:**
138
157
 
139
158
  | Mode | Tools | When to use |
@@ -4,7 +4,12 @@ import { OpenAIAdapter } from "./openai.js";
4
4
  * https://api.x.ai/v1 — same shape as OpenAI Chat Completions.
5
5
  */
6
6
  const API_URL = "https://api.x.ai/v1/chat/completions";
7
- const DEFAULT_MODEL = "grok-beta";
7
+ // Keep in sync with the driver path (src/drivers/grok/index.ts), which already
8
+ // defaults to grok-2-latest. grok-beta is a legacy alias; defaulting the two
9
+ // Grok entry points to different models meant the effective model depended on
10
+ // which path ran. grok-2-latest is a stable alias — verify the current model
11
+ // at console.x.ai before bumping further (e.g. to grok-4.x).
12
+ const DEFAULT_MODEL = "grok-2-latest";
8
13
  export function createGrokAdapter(opts) {
9
14
  const apiKey = opts.apiKey ?? process.env.XAI_API_KEY;
10
15
  if (!apiKey)
@@ -1 +1 @@
1
- {"version":3,"file":"grok.js","sourceRoot":"","sources":["../../src/adapters/grok.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAE5C;;;GAGG;AAEH,MAAM,OAAO,GAAG,sCAAsC,CAAC;AACvD,MAAM,aAAa,GAAG,WAAW,CAAC;AAElC,MAAM,UAAU,iBAAiB,CAAC,IAKjC;IACC,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,IAAI,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC;IACtD,IAAI,CAAC,MAAM;QACT,MAAM,IAAI,KAAK,CACb,iEAAiE,CAClE,CAAC;IACJ,OAAO,IAAI,aAAa,CAAC;QACvB,WAAW,EAAE,MAAM;QACnB,OAAO,EAAE,IAAI,CAAC,OAAO,IAAI,OAAO;QAChC,YAAY,EAAE,IAAI,CAAC,YAAY,IAAI,aAAa;QAChD,MAAM;QACN,aAAa,EAAE,IAAI;QACnB,SAAS,EAAE,IAAI,CAAC,SAAS;KAC1B,CAAC,CAAC;AACL,CAAC"}
1
+ {"version":3,"file":"grok.js","sourceRoot":"","sources":["../../src/adapters/grok.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAE5C;;;GAGG;AAEH,MAAM,OAAO,GAAG,sCAAsC,CAAC;AACvD,+EAA+E;AAC/E,6EAA6E;AAC7E,8EAA8E;AAC9E,6EAA6E;AAC7E,6DAA6D;AAC7D,MAAM,aAAa,GAAG,eAAe,CAAC;AAEtC,MAAM,UAAU,iBAAiB,CAAC,IAKjC;IACC,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,IAAI,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC;IACtD,IAAI,CAAC,MAAM;QACT,MAAM,IAAI,KAAK,CACb,iEAAiE,CAClE,CAAC;IACJ,OAAO,IAAI,aAAa,CAAC;QACvB,WAAW,EAAE,MAAM;QACnB,OAAO,EAAE,IAAI,CAAC,OAAO,IAAI,OAAO;QAChC,YAAY,EAAE,IAAI,CAAC,YAAY,IAAI,aAAa;QAChD,MAAM;QACN,aAAa,EAAE,IAAI;QACnB,SAAS,EAAE,IAAI,CAAC,SAAS;KAC1B,CAAC,CAAC;AACL,CAAC"}
package/dist/mcpRoutes.js CHANGED
@@ -37,7 +37,7 @@ export function tryHandleMcpRoute(req, res, parsedUrl, deps) {
37
37
  const card = {
38
38
  name: "claude-ide-bridge",
39
39
  version: BRIDGE_PROTOCOL_VERSION,
40
- description: "MCP bridge providing full IDE integration for Claude Code — LSP, diagnostics, file operations, terminal, debug adapters, and AI task orchestration",
40
+ description: "MCP bridge providing full IDE integration for AI coding assistants — LSP, diagnostics, file operations, terminal, debug adapters, and AI task orchestration",
41
41
  homepage: "https://github.com/Oolab-labs/claude-ide-bridge",
42
42
  transport: ["websocket", "stdio", "streamable-http"],
43
43
  capabilities: {
@@ -1 +1 @@
1
- {"version":3,"file":"mcpRoutes.js","sourceRoot":"","sources":["../src/mcpRo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,eAAe;YACxB,UAAU,EAAE,iDAAiD;SAC9D,CAAC;QACF,GAAG,CAAC,SAAS,CAAC,GAAG,EAAE;YACjB,cAAc,EAAE,kBAAkB;YAClC,6BAA6B,EAAE,GAAG;SACnC,CAAC,CAAC;QACH,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC;QACvC,OAAO,IAAI,CAAC;IACd,CAAC;IAED,8EAA8E;IAC9E,iFAAiF;IACjF,IAAI,GAAG,CAAC,MAAM,KAAK,SAAS,IAAI,SAAS,CAAC,QAAQ,KAAK,MAAM,EAAE,CAAC;QAC9D,MAAM,MAAM,GAAG,UAAU,CAAC,GAAG,CAAC,OAAO,CAAC,MAAM,EAAE,IAAI,CAAC,gBAAgB,CAAC,CAAC;QACrE,IAAI,MAAM,EAAE,CAAC;YACX,GAAG,CAAC,SAAS,CAAC,6BAA6B,EAAE,MAAM,CAAC,CAAC;YACrD,GAAG,CAAC,SAAS,CACX,8BAA8B,EAC9B,4BAA4B,CAC7B,CAAC;YACF,GAAG,CAAC,SAAS,CACX,8BAA8B,EAC9B,6CAA6C,CAC9C,CAAC;YACF,GAAG,CAAC,SAAS,CAAC,+BAA+B,EAAE,gBAAgB,CAAC,CAAC;QACnE,CAAC;QACD,GAAG,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;QACnB,GAAG,CAAC,GAAG,EAAE,CAAC;QACV,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "patchwork-os",
3
- "version": "0.2.0-beta.10.canary.136",
3
+ "version": "0.2.0-beta.10.canary.139",
4
4
  "description": "Your personal AI runtime, local-first. Patchwork OS gives any AI model a consistent set of tools, YAML recipes, a delegation policy with approval queue, and a durable trace memory — all on your machine, all under your policy.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -30,6 +30,27 @@ const { randomUUID } = require("node:crypto");
30
30
  // Resolve ws from the bridge's own node_modules (script lives in scripts/)
31
31
  const { WebSocket } = require(path.join(__dirname, "..", "node_modules", "ws"));
32
32
 
33
+ // process.kill(pid, 0) probes liveness without delivering a signal: it throws
34
+ // ESRCH when the process is gone and EPERM when it exists but isn't ours (still
35
+ // alive). A stale lock whose bridge has exited would otherwise be "selected"
36
+ // (newest mtime within its tier) and every connect would hang on a refused port
37
+ // until backoff gives up — the multi-bridge footgun. Mirrors the shared
38
+ // src/bridgeLockDiscovery.ts isLive() check.
39
+ function isAlive(pid) {
40
+ if (typeof pid !== "number" || !Number.isFinite(pid)) return true; // unknown pid → don't exclude
41
+ try {
42
+ process.kill(pid, 0);
43
+ return true;
44
+ } catch (err) {
45
+ return err.code === "EPERM";
46
+ }
47
+ }
48
+
49
+ // Remembers the last lock we logged a selection for, so the diagnostic below
50
+ // fires once at startup (and again only when the selection actually changes)
51
+ // rather than on every poll tick.
52
+ let lastSelectedLockPath = null;
53
+
33
54
  function findLockFile() {
34
55
  const lockDir = path.join(
35
56
  process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), ".claude"),
@@ -38,49 +59,40 @@ function findLockFile() {
38
59
  // Three-tier preference: orchestrator > bridge > any lock (each by newest mtime).
39
60
  // Orchestrator locks win because child bridge restarts produce newer lock files,
40
61
  // which would hijack the shim away from the orchestrator if we only used mtime.
41
- let orchestratorLock = null;
42
- let orchestratorMtime = 0;
43
- let bridgeLock = null;
44
- let bridgeMtime = 0;
45
- let fallbackLock = null;
46
- let fallbackMtime = 0;
62
+ const orchestrator = { path: null, mtime: 0, data: null };
63
+ const bridge = { path: null, mtime: 0, data: null };
64
+ const fallback = { path: null, mtime: 0, data: null };
47
65
  try {
48
66
  for (const f of fs.readdirSync(lockDir)) {
49
67
  if (!f.endsWith(".lock")) continue;
50
68
  const fullPath = path.join(lockDir, f);
51
69
  try {
52
70
  const stat = fs.statSync(fullPath);
53
- let isBridge = false;
54
- let isOrchestrator = false;
71
+ let data = null;
55
72
  try {
56
- const data = JSON.parse(fs.readFileSync(fullPath, "utf8"));
57
- isBridge = data.isBridge === true;
58
- isOrchestrator = data.orchestrator === true;
59
- // Skip locks that don't match the requested workspace
60
- if (
61
- workspaceFilter &&
62
- data.workspace &&
63
- data.workspace !== workspaceFilter
64
- )
65
- continue;
73
+ data = JSON.parse(fs.readFileSync(fullPath, "utf8"));
66
74
  } catch {
67
- // unparseable — treat as non-bridge
75
+ // unparseable — treated as a fallback lock with no metadata
68
76
  }
69
- if (isOrchestrator) {
70
- if (stat.mtimeMs > orchestratorMtime) {
71
- orchestratorMtime = stat.mtimeMs;
72
- orchestratorLock = fullPath;
73
- }
74
- } else if (isBridge) {
75
- if (stat.mtimeMs > bridgeMtime) {
76
- bridgeMtime = stat.mtimeMs;
77
- bridgeLock = fullPath;
78
- }
79
- } else {
80
- if (stat.mtimeMs > fallbackMtime) {
81
- fallbackMtime = stat.mtimeMs;
82
- fallbackLock = fullPath;
83
- }
77
+ // Skip locks whose owning bridge process has exited. Without this a
78
+ // wedged/stale lock can be picked and the connection hangs.
79
+ if (data && !isAlive(data.pid)) continue;
80
+ // When a workspace filter is set, require an EXACT workspace match — a
81
+ // lock with a missing/blank workspace field must not be picked under the
82
+ // filter (otherwise the shim can latch onto an unrelated bridge).
83
+ if (workspaceFilter && (!data || data.workspace !== workspaceFilter))
84
+ continue;
85
+ const isBridge = data ? data.isBridge === true : false;
86
+ const isOrchestrator = data ? data.orchestrator === true : false;
87
+ const tier = isOrchestrator
88
+ ? orchestrator
89
+ : isBridge
90
+ ? bridge
91
+ : fallback;
92
+ if (stat.mtimeMs > tier.mtime) {
93
+ tier.mtime = stat.mtimeMs;
94
+ tier.path = fullPath;
95
+ tier.data = data;
84
96
  }
85
97
  } catch {
86
98
  // skip unreadable files
@@ -90,7 +102,25 @@ function findLockFile() {
90
102
  // lock dir doesn't exist
91
103
  }
92
104
  // Prefer orchestrator > bridge > fallback (each newest mtime within tier)
93
- return orchestratorLock ?? bridgeLock ?? fallbackLock;
105
+ const chosen = orchestrator.path
106
+ ? orchestrator
107
+ : bridge.path
108
+ ? bridge
109
+ : fallback.path
110
+ ? fallback
111
+ : null;
112
+ // One-line stderr diagnostic so operators can see which bridge/workspace the
113
+ // shim latched onto — silent wrong-bridge selection was a real footgun. stderr
114
+ // is not the JSON-RPC stream, so this never corrupts protocol traffic.
115
+ if (chosen && chosen.path !== lastSelectedLockPath) {
116
+ lastSelectedLockPath = chosen.path;
117
+ const wsName = chosen.data?.workspace || "(unknown workspace)";
118
+ const pid = chosen.data?.pid || "?";
119
+ process.stderr.write(
120
+ `mcp-stdio-shim: selected ${path.basename(chosen.path)} (workspace=${wsName}, pid=${pid})\n`,
121
+ );
122
+ }
123
+ return chosen ? chosen.path : null;
94
124
  }
95
125
 
96
126
  function parseLock(lockPath) {
@@ -199,11 +229,16 @@ function scheduleBackoffReconnect(errorType) {
199
229
  // Parse named flags first so they don't pollute positional port/token detection.
200
230
  const args = process.argv.slice(2);
201
231
  let workspaceFilter = null;
232
+ let pingMode = false;
202
233
  for (let i = 0; i < args.length; i++) {
203
- if (args[i] === "--workspace" && args[i + 1]) {
234
+ if (args[i] === "--ping" || args[i] === "--probe") {
235
+ pingMode = true;
236
+ args.splice(i, 1);
237
+ i--;
238
+ } else if (args[i] === "--workspace" && args[i + 1] !== undefined) {
204
239
  workspaceFilter = args[i + 1];
205
240
  args.splice(i, 2);
206
- break;
241
+ i--;
207
242
  }
208
243
  }
209
244
  const explicitPort = args[0] && args[1] ? Number(args[0]) : null;
@@ -369,8 +404,104 @@ function startPoll() {
369
404
  }, POLL_INTERVAL_MS);
370
405
  }
371
406
 
372
- // --- Initial connection ---
373
- if (explicitPort !== null) {
407
+ // --- Ping mode: one-shot probe, then exit ---
408
+ // `grok mcp doctor` (and similar stdio MCP verifiers) hang on this shim because
409
+ // it is a long-lived relay that only exits on stdin EOF. `--ping` / `--probe`
410
+ // gives those tools a clean check: connect, run initialize + tools/list, print a
411
+ // one-line summary, and exit. It skips the relay, lock watcher, and reconnect
412
+ // loops entirely.
413
+ if (pingMode) {
414
+ let pingPort = explicitPort;
415
+ let pingToken = explicitToken;
416
+ if (pingPort === null) {
417
+ const lockFile = findLockFile();
418
+ if (!lockFile) {
419
+ process.stderr.write("mcp-stdio-shim: --ping: no bridge lock found.\n");
420
+ process.exit(1);
421
+ }
422
+ try {
423
+ const parsed = parseLock(lockFile);
424
+ pingPort = parsed.port;
425
+ pingToken = parsed.authToken;
426
+ } catch (err) {
427
+ process.stderr.write(
428
+ `mcp-stdio-shim: --ping: lock unreadable (${err.message}).\n`,
429
+ );
430
+ process.exit(1);
431
+ }
432
+ }
433
+ let pingDone = false;
434
+ const pingWs = new WebSocket(`ws://127.0.0.1:${pingPort}`, {
435
+ headers: {
436
+ "x-claude-code-ide-authorization": pingToken,
437
+ "x-claude-code-session-id": CLIENT_SESSION_ID,
438
+ },
439
+ });
440
+ const failPing = (msg) => {
441
+ if (pingDone) return;
442
+ pingDone = true;
443
+ process.stderr.write(`mcp-stdio-shim: --ping: ${msg}\n`);
444
+ try {
445
+ pingWs.terminate();
446
+ } catch {
447
+ /* ignore */
448
+ }
449
+ process.exit(1);
450
+ };
451
+ const pingTimer = setTimeout(
452
+ () => failPing(`timed out after 5s (port ${pingPort})`),
453
+ 5000,
454
+ );
455
+ pingWs.on("open", () => {
456
+ pingWs.send(
457
+ JSON.stringify({
458
+ jsonrpc: "2.0",
459
+ id: 1,
460
+ method: "initialize",
461
+ params: {
462
+ protocolVersion: "2025-06-18",
463
+ capabilities: {},
464
+ clientInfo: { name: "shim-ping", version: "1" },
465
+ },
466
+ }),
467
+ );
468
+ });
469
+ pingWs.on("message", (raw) => {
470
+ let msg;
471
+ try {
472
+ msg = JSON.parse(raw.toString());
473
+ } catch {
474
+ return;
475
+ }
476
+ if (msg.id === 1) {
477
+ pingWs.send(
478
+ JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }),
479
+ );
480
+ pingWs.send(
481
+ JSON.stringify({ jsonrpc: "2.0", id: 2, method: "tools/list" }),
482
+ );
483
+ } else if (msg.id === 2) {
484
+ clearTimeout(pingTimer);
485
+ pingDone = true;
486
+ const n =
487
+ msg.result && Array.isArray(msg.result.tools)
488
+ ? msg.result.tools.length
489
+ : "?";
490
+ process.stdout.write(`bridge OK — port ${pingPort}, ${n} tools\n`);
491
+ try {
492
+ pingWs.close();
493
+ } catch {
494
+ /* ignore */
495
+ }
496
+ process.exit(0);
497
+ }
498
+ });
499
+ pingWs.on("error", (err) => failPing(`connect failed (${err.message})`));
500
+ pingWs.on("close", (code) =>
501
+ failPing(`closed before tools/list (code ${code})`),
502
+ );
503
+ } else if (explicitPort !== null) {
504
+ // --- Initial connection ---
374
505
  connect(explicitPort, explicitToken);
375
506
  } else {
376
507
  const lockFile = findLockFile();
@@ -398,7 +529,7 @@ if (explicitPort !== null) {
398
529
  // Watches ~/.claude/ide/ for .lock file changes. When a new bridge lock appears
399
530
  // on a different port, reconnects automatically. This means Claude Desktop never
400
531
  // needs to be restarted when the bridge restarts on a new port.
401
- if (explicitPort === null) {
532
+ if (!pingMode && explicitPort === null) {
402
533
  const lockDir = path.join(
403
534
  process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), ".claude"),
404
535
  "ide",
@@ -439,52 +570,38 @@ if (explicitPort === null) {
439
570
 
440
571
  // --- stdin → bridge (newline-delimited JSON-RPC) ---
441
572
  // Messages that arrive before the WebSocket is open are queued and flushed on connect.
442
- process.stdin.setEncoding("utf8");
443
- process.stdin.on("data", (chunk) => {
444
- buffer += chunk;
445
- const lines = buffer.split("\n");
446
- buffer = lines.pop() ?? "";
447
- for (const line of lines) {
448
- const trimmed = line.trim();
449
- if (!trimmed) continue;
450
- if (ws && ws.readyState === WebSocket.OPEN) {
451
- try {
452
- ws.send(trimmed);
453
- } catch (sendErr) {
573
+ // Skipped in --ping mode — the one-shot probe manages its own lifecycle and exits.
574
+ if (!pingMode) {
575
+ process.stdin.setEncoding("utf8");
576
+ process.stdin.on("data", (chunk) => {
577
+ buffer += chunk;
578
+ const lines = buffer.split("\n");
579
+ buffer = lines.pop() ?? "";
580
+ for (const line of lines) {
581
+ const trimmed = line.trim();
582
+ if (!trimmed) continue;
583
+ if (ws && ws.readyState === WebSocket.OPEN) {
584
+ try {
585
+ ws.send(trimmed);
586
+ } catch (sendErr) {
587
+ process.stderr.write(
588
+ `mcp-stdio-shim: ws.send failed (${sendErr.message}) — queuing message.\n`,
589
+ );
590
+ if (pendingLines.length < MAX_PENDING_LINES) {
591
+ pendingLines.push(trimmed);
592
+ }
593
+ }
594
+ } else if (pendingLines.length < MAX_PENDING_LINES) {
595
+ pendingLines.push(trimmed);
596
+ } else {
454
597
  process.stderr.write(
455
- `mcp-stdio-shim: ws.send failed (${sendErr.message}) — queuing message.\n`,
598
+ `mcp-stdio-shim: pendingLines overflow (${MAX_PENDING_LINES}) — dropping message (bridge not connected)\n`,
456
599
  );
457
- if (pendingLines.length < MAX_PENDING_LINES) {
458
- pendingLines.push(trimmed);
459
- }
460
600
  }
461
- } else if (pendingLines.length < MAX_PENDING_LINES) {
462
- pendingLines.push(trimmed);
463
- } else {
464
- process.stderr.write(
465
- `mcp-stdio-shim: pendingLines overflow (${MAX_PENDING_LINES}) — dropping message (bridge not connected)\n`,
466
- );
467
601
  }
468
- }
469
- });
470
-
471
- process.stdin.on("end", () => {
472
- if (ws) {
473
- try {
474
- ws.close();
475
- } catch {
476
- /* ignore */
477
- }
478
- }
479
- process.exit(0);
480
- });
602
+ });
481
603
 
482
- process.stdin.on("error", (err) => {
483
- // EPIPE / ERR_STREAM_DESTROYED means the MCP host closed the pipe — clean shutdown.
484
- if (err.code === "EPIPE" || err.code === "ERR_STREAM_DESTROYED") {
485
- process.stderr.write(
486
- `mcp-stdio-shim: stdin closed (${err.code}) — shutting down.\n`,
487
- );
604
+ process.stdin.on("end", () => {
488
605
  if (ws) {
489
606
  try {
490
607
  ws.close();
@@ -493,6 +610,23 @@ process.stdin.on("error", (err) => {
493
610
  }
494
611
  }
495
612
  process.exit(0);
496
- }
497
- process.stderr.write(`mcp-stdio-shim: stdin error: ${err.message}\n`);
498
- });
613
+ });
614
+
615
+ process.stdin.on("error", (err) => {
616
+ // EPIPE / ERR_STREAM_DESTROYED means the MCP host closed the pipe — clean shutdown.
617
+ if (err.code === "EPIPE" || err.code === "ERR_STREAM_DESTROYED") {
618
+ process.stderr.write(
619
+ `mcp-stdio-shim: stdin closed (${err.code}) — shutting down.\n`,
620
+ );
621
+ if (ws) {
622
+ try {
623
+ ws.close();
624
+ } catch {
625
+ /* ignore */
626
+ }
627
+ }
628
+ process.exit(0);
629
+ }
630
+ process.stderr.write(`mcp-stdio-shim: stdin error: ${err.message}\n`);
631
+ });
632
+ }