pi-charset 0.1.7 → 0.1.9

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.
@@ -3,13 +3,14 @@
3
3
  // expectedVersion concurrency, atomic Windows retries, 4 edit modes, multi-file apply_patch, multi-encoding grep,
4
4
  // bounded outline/ranges/window views, controlled repair, and zero-side-effect dry-run undo).
5
5
  import { once } from "node:events";
6
- import { mkdir } from "node:fs/promises";
7
6
  import * as path from "node:path";
8
7
  import { findNearestConfig, getRuntimeDefaults } from "../config.js";
8
+ import { getIncidentRecorder } from "../diagnostics/incidents.js";
9
9
  import { containsNul } from "../encoding/classify.js";
10
10
  import { detectSupportedImageMimeType } from "../encoding/mime.js";
11
11
  import { compactRangeDiff, executeApplyPatch } from "../edit/apply-patch-core.js";
12
12
  import { EditError } from "../edit/diagnostics.js";
13
+ import { CharsetFault, isCharsetFault, REPORTABLE_FAULT_CODES, toMcpErrorEnvelope } from "../faults.js";
13
14
  import { formatUpdatedHashlines, planHashlineEdits } from "../edit/hashline.js";
14
15
  import { planPatchEdits } from "../edit/patch.js";
15
16
  import { resolveEditPath, resolveReadPathCompat } from "../edit/paths.js";
@@ -25,16 +26,84 @@ const SUPPORTED_PROTOCOLS = new Set(["2025-06-18", "2025-03-26", "2024-11-05"]);
25
26
  const DEFAULT_READ_LIMIT = 2000;
26
27
  const MAX_READ_BYTES = 50 * 1024;
27
28
  const MAX_PENDING_REQUESTS = 64;
29
+ const MAX_CONCURRENT_READS = 8;
30
+ const MAX_FRAME_BYTES = 32 * 1024 * 1024;
31
+ const READ_ONLY_TOOLS = new Set(["charset_read", "charset_grep", "charset_check"]);
28
32
  const MCP_INSTRUCTIONS = "pi-charset-mcp works out-of-the-box with zero configuration (no .pi-charset.json needed). " +
29
33
  "Use charset_read, charset_edit, charset_apply_patch, charset_write, charset_grep, charset_check, and charset_fix " +
30
34
  "for all text file operations to preserve exact encodings (GBK/GB18030/Big5/Shift_JIS/EUC-KR/UTF-16/UTF-8), BOM, and CRLF/LF line endings. " +
31
35
  "When multiple agents share a workspace, pass the `version` returned by charset_read as `expectedVersion` to charset_write/charset_edit.";
32
- class InputValidationError extends Error {
36
+ class InputValidationError extends CharsetFault {
33
37
  constructor(message) {
34
- super(`[INVALID_INPUT; not_applied] ${message}`);
38
+ super(`[INVALID_INPUT; not_applied] ${message}`, {
39
+ code: "INVALID_INPUT",
40
+ category: "input",
41
+ phase: "validate",
42
+ outcome: "not_applied",
43
+ retryable: false,
44
+ actionHint: "Fix the tool input parameters and retry.",
45
+ });
35
46
  this.name = "InputValidationError";
36
47
  }
37
48
  }
49
+ function mapClientName(raw) {
50
+ if (typeof raw !== "string")
51
+ return "generic";
52
+ const s = raw.trim().toLowerCase();
53
+ if (s.includes("codex"))
54
+ return "codex";
55
+ if (s.includes("antigravity-ide"))
56
+ return "antigravity-ide";
57
+ if (s.includes("antigravity-app"))
58
+ return "antigravity-app";
59
+ if (s.includes("antigravity") || s === "agy")
60
+ return "agy";
61
+ if (s.includes("claude"))
62
+ return "claude";
63
+ if (s.includes("cursor"))
64
+ return "cursor";
65
+ if (s.includes("windsurf"))
66
+ return "windsurf";
67
+ if (s === "pi")
68
+ return "pi";
69
+ return "generic";
70
+ }
71
+ function toolToOperation(toolName) {
72
+ switch (toolName) {
73
+ case "charset_read": return "read";
74
+ case "charset_write": return "write";
75
+ case "charset_edit": return "edit";
76
+ case "charset_apply_patch": return "apply_patch";
77
+ case "charset_grep": return "grep";
78
+ case "charset_check": return "check";
79
+ case "charset_fix": return "fix";
80
+ default: return "unknown";
81
+ }
82
+ }
83
+ function faultFromCaught(err) {
84
+ if (isCharsetFault(err))
85
+ return err.fault;
86
+ if (err instanceof EditError)
87
+ return err.toFaultMetadata();
88
+ const code = err?.code;
89
+ if (code === "ENOENT") {
90
+ return { code: "NOT_FOUND", category: "io", phase: "detect", outcome: "not_applied", retryable: false, actionHint: "Check the file path and retry." };
91
+ }
92
+ if (code === "EACCES" || code === "EPERM") {
93
+ return { code: "PERMISSION_DENIED", category: "io", phase: "validate", outcome: "not_applied", retryable: false, actionHint: "Check file permissions and retry." };
94
+ }
95
+ if (code === "EBUSY") {
96
+ return { code: "LOCK_BUSY", category: "io", phase: "commit", retryable: true, outcome: "not_applied", actionHint: "Close external editors locking the file and retry." };
97
+ }
98
+ return {
99
+ code: "INTERNAL",
100
+ category: "engine",
101
+ phase: "unknown",
102
+ outcome: "unknown",
103
+ retryable: false,
104
+ actionHint: "Re-read the target file to verify on-disk state; run `pi-charset feedback list` to inspect sanitized local diagnostics.",
105
+ };
106
+ }
38
107
  function coercePathArg(args) {
39
108
  const raw = typeof args.path === "string" ? args.path : typeof args.file_path === "string" ? args.file_path : undefined;
40
109
  return raw && raw.trim() ? raw : undefined;
@@ -103,6 +172,14 @@ export const MCP_TOOLS = [
103
172
  {
104
173
  name: "charset_read",
105
174
  description: "Read a text file preserving exact encoding/BOM/EOL (GBK, GB18030, Big5, Shift_JIS, EUC-KR, UTF-16, UTF-8) and return its SHA-1 version for safe edits. Supports outline=true, ranges=[[start,end],...], offset/limit, and hashlines=true. Output is strictly bounded.",
175
+ annotations: {
176
+ title: "Read File (Encoding-Safe)",
177
+ readOnlyHint: true,
178
+ destructiveHint: false,
179
+ idempotentHint: true,
180
+ openWorldHint: false,
181
+ },
182
+ _meta: { "antigravity/alwaysLoad": true },
106
183
  inputSchema: {
107
184
  type: "object",
108
185
  additionalProperties: false,
@@ -125,6 +202,13 @@ export const MCP_TOOLS = [
125
202
  {
126
203
  name: "charset_write",
127
204
  description: "Write a file through pi-charset's Gate 1/2/3 safety pipeline (preserves existing encoding/BOM/EOL or inherits sibling/config encoding, atomic temp-file replace with Windows lock retries, SHA-1 baseline & optional expectedVersion check, and session undo).",
205
+ annotations: {
206
+ title: "Write File (Encoding-Safe)",
207
+ readOnlyHint: false,
208
+ destructiveHint: false,
209
+ idempotentHint: true,
210
+ openWorldHint: false,
211
+ },
128
212
  inputSchema: {
129
213
  type: "object",
130
214
  additionalProperties: false,
@@ -144,6 +228,14 @@ export const MCP_TOOLS = [
144
228
  {
145
229
  name: "charset_edit",
146
230
  description: "Edit a file atomically while preserving its exact encoding, BOM, line endings, and untouched bytes. Supply exactly one of: edits ([{oldText, newText}]), hashlines (anchored replace/delete/insert_after/insert_before), patch (unified/Codex/Aider diff), or wholeFile.",
231
+ annotations: {
232
+ title: "Edit File (Encoding-Safe)",
233
+ readOnlyHint: false,
234
+ destructiveHint: false,
235
+ idempotentHint: false,
236
+ openWorldHint: false,
237
+ },
238
+ _meta: { "antigravity/alwaysLoad": true },
147
239
  inputSchema: {
148
240
  type: "object",
149
241
  additionalProperties: false,
@@ -178,6 +270,13 @@ export const MCP_TOOLS = [
178
270
  {
179
271
  name: "charset_apply_patch",
180
272
  description: "Pre-validate and apply a multi-file patch (Codex `*** Begin Patch` with Update/Hashline/Add/Delete/Move, Aider multi-file SEARCH/REPLACE, or unified `diff --git`) across mixed GBK/UTF-8 files with deadlock-free path locking and batch undo.",
273
+ annotations: {
274
+ title: "Apply Multi-File Patch (Encoding-Safe)",
275
+ readOnlyHint: false,
276
+ destructiveHint: true,
277
+ idempotentHint: false,
278
+ openWorldHint: false,
279
+ },
181
280
  inputSchema: {
182
281
  type: "object",
183
282
  additionalProperties: false,
@@ -191,6 +290,14 @@ export const MCP_TOOLS = [
191
290
  {
192
291
  name: "charset_grep",
193
292
  description: "Search files across UTF-8, GBK, GB18030, Big5, Shift_JIS, EUC-KR, EUC-JP, and UTF-16 using encoding-verified multi-pass ripgrep. Supports filesOnly=true and hashlines=true. Propagates ripgrep errors explicitly.",
293
+ annotations: {
294
+ title: "Search Files (Multi-Encoding)",
295
+ readOnlyHint: true,
296
+ destructiveHint: false,
297
+ idempotentHint: true,
298
+ openWorldHint: false,
299
+ },
300
+ _meta: { "antigravity/alwaysLoad": true },
194
301
  inputSchema: {
195
302
  type: "object",
196
303
  additionalProperties: false,
@@ -213,6 +320,13 @@ export const MCP_TOOLS = [
213
320
  {
214
321
  name: "charset_check",
215
322
  description: "Read-only encoding diagnostics: pass `path` to explain a single file's byte verdict, matched rule, BOM/EOL, and write status; omit `path` to run a workspace health scan for mixed line endings and damaged/unknown files.",
323
+ annotations: {
324
+ title: "Check Encoding & Health",
325
+ readOnlyHint: true,
326
+ destructiveHint: false,
327
+ idempotentHint: true,
328
+ openWorldHint: false,
329
+ },
216
330
  inputSchema: {
217
331
  type: "object",
218
332
  additionalProperties: false,
@@ -226,6 +340,13 @@ export const MCP_TOOLS = [
226
340
  {
227
341
  name: "charset_fix",
228
342
  description: "Controlled, Gate-1/2-verified encoding maintenance & undo: normalize_eol (single file CRLF/LF), auto_fix_eol (batch mixed-EOL repair to majority style), convert (verified transcoding with BOM control), or undo (revert latest session write/batch; supports zero-side-effect dryRun=true preview).",
343
+ annotations: {
344
+ title: "Fix Encoding / EOL / Undo",
345
+ readOnlyHint: false,
346
+ destructiveHint: false,
347
+ idempotentHint: false,
348
+ openWorldHint: false,
349
+ },
229
350
  inputSchema: {
230
351
  type: "object",
231
352
  additionalProperties: false,
@@ -271,7 +392,30 @@ function validateRpcEnvelope(raw) {
271
392
  }
272
393
  return { ok: true, req: obj };
273
394
  }
274
- export function createMcpDispatcher(defaultCwd, scope = createReadScope()) {
395
+ export function createMcpDispatcher(defaultCwd, scope = createReadScope(), opts) {
396
+ let activeClient = mapClientName(opts?.client);
397
+ const recordFault = (fault, operation) => {
398
+ if (!REPORTABLE_FAULT_CODES.has(fault.code))
399
+ return;
400
+ const rec = opts?.recorder ?? getIncidentRecorder(activeClient);
401
+ rec.record({
402
+ code: fault.code,
403
+ operation,
404
+ phase: fault.phase,
405
+ outcome: fault.outcome,
406
+ encoding: fault.encoding,
407
+ eol: fault.eol,
408
+ fileBytes: fault.fileBytes,
409
+ });
410
+ };
411
+ const failTool = (message, fault, operation) => {
412
+ recordFault(fault, operation);
413
+ return {
414
+ text: message,
415
+ isError: true,
416
+ structuredContent: toMcpErrorEnvelope(fault),
417
+ };
418
+ };
275
419
  const resolveCwd = (args) => {
276
420
  const cwdArg = coerceOptionalString(args, "cwd");
277
421
  return cwdArg && cwdArg.trim() ? path.resolve(defaultCwd, cwdArg) : defaultCwd;
@@ -281,7 +425,7 @@ export function createMcpDispatcher(defaultCwd, scope = createReadScope()) {
281
425
  if (name === "charset_read") {
282
426
  const pathArg = coercePathArg(args);
283
427
  if (!pathArg) {
284
- return { text: "[INVALID_INPUT; not_applied] path is required.", isError: true };
428
+ return failTool("[INVALID_INPUT; not_applied] path is required.", { code: "INVALID_INPUT", category: "input", phase: "validate", outcome: "not_applied", retryable: false, actionHint: "Pass path or file_path." }, "read");
285
429
  }
286
430
  const outlineArg = coerceOptionalBoolean(args, "outline") ?? false;
287
431
  const hashlinesOpt = coerceOptionalBoolean(args, "hashlines");
@@ -297,18 +441,10 @@ export function createMcpDispatcher(defaultCwd, scope = createReadScope()) {
297
441
  notes.push(note); }, (m) => { meta = m; });
298
442
  const buf = await readOps.readFile(absPath);
299
443
  if (detectSupportedImageMimeType(buf)) {
300
- return {
301
- text: `[BINARY_IMAGE] ${absPath} (${buf.length}B) is an image file; use a binary/image reader.`,
302
- isError: true,
303
- structuredContent: { path: absPath, kind: "image", bytesOnDisk: buf.length },
304
- };
444
+ return failTool(`[BINARY_IMAGE] ${absPath} (${buf.length}B) is an image file; use a binary/image reader.`, { code: "BINARY_FILE", category: "policy", phase: "detect", outcome: "not_applied", retryable: false, actionHint: "Use an image/binary reader for image files.", fileBytes: buf.length }, "read");
305
445
  }
306
446
  if (containsNul(buf)) {
307
- return {
308
- text: `[BINARY_FILE] ${absPath} (${buf.length}B) contains NUL bytes and cannot be displayed as text.`,
309
- isError: true,
310
- structuredContent: { path: absPath, kind: "binary", bytesOnDisk: buf.length },
311
- };
447
+ return failTool(`[BINARY_FILE] ${absPath} (${buf.length}B) contains NUL bytes and cannot be displayed as text.`, { code: "BINARY_FILE", category: "policy", phase: "detect", outcome: "not_applied", retryable: false, actionHint: "Binary files are refused by text tools.", fileBytes: buf.length }, "read");
312
448
  }
313
449
  if (scope.epoch === epoch && observed)
314
450
  scope.baselines.set(observed.key, observed.version);
@@ -364,11 +500,11 @@ export function createMcpDispatcher(defaultCwd, scope = createReadScope()) {
364
500
  if (name === "charset_write") {
365
501
  const pathArg = coercePathArg(args);
366
502
  if (!pathArg || typeof args.content !== "string") {
367
- return { text: "[INVALID_INPUT; not_applied] path and content are required.", isError: true };
503
+ return failTool("[INVALID_INPUT; not_applied] path and content are required.", { code: "INVALID_INPUT", category: "input", phase: "validate", outcome: "not_applied", retryable: false, actionHint: "Pass path (or file_path) and content." }, "write");
368
504
  }
369
505
  const expectedVersion = coerceOptionalString(args, "expectedVersion");
370
506
  const absPath = resolveEditPath(pathArg, baseCwd);
371
- await mkdir(path.dirname(absPath), { recursive: true });
507
+ // Parent directory creation happens inside writeFileDetailed ONLY after expectedVersion + Gate 1/3 pass.
372
508
  const outcome = await writeFileDetailed(absPath, args.content, scope, expectedVersion);
373
509
  const suffix = notesToSuffix(drainEncodingNotes(absPath));
374
510
  return {
@@ -379,7 +515,7 @@ export function createMcpDispatcher(defaultCwd, scope = createReadScope()) {
379
515
  if (name === "charset_edit") {
380
516
  const pathArg = coercePathArg(args);
381
517
  if (!pathArg) {
382
- return { text: "[INVALID_INPUT; not_applied] path is required.", isError: true };
518
+ return failTool("[INVALID_INPUT; not_applied] path is required.", { code: "INVALID_INPUT", category: "input", phase: "validate", outcome: "not_applied", retryable: false, actionHint: "Pass path or file_path." }, "edit");
383
519
  }
384
520
  const expectedVersion = coerceOptionalString(args, "expectedVersion");
385
521
  const presentModes = [
@@ -389,10 +525,7 @@ export function createMcpDispatcher(defaultCwd, scope = createReadScope()) {
389
525
  args.wholeFile !== undefined ? "wholeFile" : null,
390
526
  ].filter((m) => m !== null);
391
527
  if (presentModes.length !== 1) {
392
- return {
393
- text: "[INVALID_INPUT; not_applied] Supply exactly one of: edits, hashlines, patch, or wholeFile.",
394
- isError: true,
395
- };
528
+ return failTool("[INVALID_INPUT; not_applied] Supply exactly one of: edits, hashlines, patch, or wholeFile.", { code: "INVALID_INPUT", category: "input", phase: "validate", outcome: "not_applied", retryable: false, actionHint: "Pass exactly one edit payload: edits, hashlines, patch, or wholeFile." }, "edit");
396
529
  }
397
530
  const mode = presentModes[0];
398
531
  const editsArg = mode === "edits" ? coerceArrayArg(args.edits, "edits", true) : undefined;
@@ -438,7 +571,7 @@ export function createMcpDispatcher(defaultCwd, scope = createReadScope()) {
438
571
  }
439
572
  if (name === "charset_apply_patch") {
440
573
  if (typeof args.patch !== "string" || !args.patch.trim()) {
441
- return { text: "[INVALID_INPUT; not_applied] patch is required.", isError: true };
574
+ return failTool("[INVALID_INPUT; not_applied] patch is required.", { code: "INVALID_INPUT", category: "input", phase: "validate", outcome: "not_applied", retryable: false, actionHint: "Pass a non-empty patch string." }, "apply_patch");
442
575
  }
443
576
  const res = await executeApplyPatch(baseCwd, args.patch, scope, signal);
444
577
  return {
@@ -456,7 +589,7 @@ export function createMcpDispatcher(defaultCwd, scope = createReadScope()) {
456
589
  }
457
590
  if (name === "charset_grep") {
458
591
  if (typeof args.pattern !== "string" || !args.pattern) {
459
- return { text: "[INVALID_INPUT; not_applied] pattern is required.", isError: true };
592
+ return failTool("[INVALID_INPUT; not_applied] pattern is required.", { code: "INVALID_INPUT", category: "input", phase: "validate", outcome: "not_applied", retryable: false, actionHint: "Pass a non-empty search pattern." }, "grep");
460
593
  }
461
594
  const ignoreCase = coerceOptionalBoolean(args, "ignoreCase") ?? false;
462
595
  const literal = coerceOptionalBoolean(args, "literal") ?? false;
@@ -477,23 +610,13 @@ export function createMcpDispatcher(defaultCwd, scope = createReadScope()) {
477
610
  filesOnly,
478
611
  }, signal);
479
612
  if (!res) {
480
- return {
481
- text: "[GREP_UNAVAILABLE] ripgrep (rg) was not found or search path is invalid.",
482
- isError: true,
483
- structuredContent: { status: "failed", error: "ripgrep unavailable or invalid path" },
484
- };
613
+ return failTool("[GREP_UNAVAILABLE] ripgrep (rg) was not found or search path is invalid.", { code: "SEARCH_ENGINE_FAILED", category: "compatibility", phase: "search", outcome: "not_applied", retryable: false, actionHint: "Run `pi-charset doctor` to verify ripgrep availability and search path." }, "grep");
485
614
  }
486
615
  if (res.status === "failed") {
487
- return {
488
- text: res.text,
489
- isError: true,
490
- structuredContent: {
491
- status: "failed",
492
- error: res.error,
493
- searchedWith: res.searchedWith,
494
- failedPasses: res.failedPasses,
495
- },
496
- };
616
+ const isSyntax = /regex parse error/i.test(res.error ?? "");
617
+ return failTool(res.text, isSyntax
618
+ ? { code: "INVALID_INPUT", category: "input", phase: "search", outcome: "not_applied", retryable: false, actionHint: "Fix the regular expression or pass literal=true." }
619
+ : { code: "SEARCH_ENGINE_FAILED", category: "compatibility", phase: "search", outcome: "not_applied", retryable: true, actionHint: "Check search pattern and ripgrep status via `pi-charset doctor`." }, "grep");
497
620
  }
498
621
  return {
499
622
  text: res.text,
@@ -533,7 +656,7 @@ export function createMcpDispatcher(defaultCwd, scope = createReadScope()) {
533
656
  if (action === "normalize_eol") {
534
657
  const to = (toArg ?? "").toUpperCase();
535
658
  if (!pathArg || (to !== "CRLF" && to !== "LF")) {
536
- return { text: "[INVALID_INPUT; not_applied] normalize_eol requires path and to='CRLF'|'LF'.", isError: true };
659
+ return failTool("[INVALID_INPUT; not_applied] normalize_eol requires path and to='CRLF'|'LF'.", { code: "INVALID_INPUT", category: "input", phase: "validate", outcome: "not_applied", retryable: false, actionHint: "Pass path and to='CRLF' or to='LF'." }, "fix");
537
660
  }
538
661
  const absPath = resolveEditPath(pathArg, baseCwd);
539
662
  const res = await normalizeFileLineEndings(absPath, to, scope, dryRun);
@@ -545,7 +668,7 @@ export function createMcpDispatcher(defaultCwd, scope = createReadScope()) {
545
668
  }
546
669
  if (action === "convert") {
547
670
  if (!pathArg || !toArg || !toArg.trim()) {
548
- return { text: "[INVALID_INPUT; not_applied] convert requires path and to='<encoding>'.", isError: true };
671
+ return failTool("[INVALID_INPUT; not_applied] convert requires path and to='<encoding>'.", { code: "INVALID_INPUT", category: "input", phase: "validate", outcome: "not_applied", retryable: false, actionHint: "Pass path and target encoding in to." }, "fix");
549
672
  }
550
673
  const absPath = resolveEditPath(pathArg, baseCwd);
551
674
  const res = await convertFileEncoding(absPath, toArg, scope, { bom, dryRun });
@@ -571,7 +694,20 @@ export function createMcpDispatcher(defaultCwd, scope = createReadScope()) {
571
694
  return {
572
695
  text: res.reason,
573
696
  isError: true,
574
- structuredContent: { ok: false, action: "undo", dryRun, applied: false, reason: res.reason },
697
+ structuredContent: {
698
+ ...toMcpErrorEnvelope({
699
+ code: "CONFLICT",
700
+ category: "conflict",
701
+ phase: "rollback",
702
+ outcome: "not_applied",
703
+ retryable: false,
704
+ actionHint: "Inspect the file and session journal before retrying undo.",
705
+ }),
706
+ ok: false,
707
+ action: "undo",
708
+ dryRun,
709
+ reason: res.reason,
710
+ },
575
711
  };
576
712
  }
577
713
  const items = res.entries ?? [{ entry: res.entry, action: res.action }];
@@ -596,9 +732,9 @@ export function createMcpDispatcher(defaultCwd, scope = createReadScope()) {
596
732
  },
597
733
  };
598
734
  }
599
- return { text: `[INVALID_INPUT; not_applied] Unknown action "${action}".`, isError: true };
735
+ return failTool(`[INVALID_INPUT; not_applied] Unknown action "${action}".`, { code: "INVALID_INPUT", category: "input", phase: "validate", outcome: "not_applied", retryable: false, actionHint: "Use action: normalize_eol, convert, auto_fix_eol, or undo." }, "fix");
600
736
  }
601
- return { text: `Unknown tool: ${name}`, isError: true };
737
+ return failTool(`[INVALID_INPUT; not_applied] Unknown tool: ${name}`, { code: "INVALID_INPUT", category: "input", phase: "validate", outcome: "not_applied", retryable: false, actionHint: "Call tools/list to inspect available tool names." }, "unknown");
602
738
  }
603
739
  async function handleRequest(rawReq, signal) {
604
740
  const validated = validateRpcEnvelope(rawReq);
@@ -611,6 +747,10 @@ export function createMcpDispatcher(defaultCwd, scope = createReadScope()) {
611
747
  return null;
612
748
  }
613
749
  if (req.method === "initialize") {
750
+ if (!opts?.client) {
751
+ const clientInfo = req.params?.clientInfo;
752
+ activeClient = mapClientName(clientInfo?.name);
753
+ }
614
754
  const requested = typeof req.params?.protocolVersion === "string" ? req.params.protocolVersion : "2024-11-05";
615
755
  const protocolVersion = SUPPORTED_PROTOCOLS.has(requested) ? requested : "2024-11-05";
616
756
  return {
@@ -664,7 +804,9 @@ export function createMcpDispatcher(defaultCwd, scope = createReadScope()) {
664
804
  };
665
805
  }
666
806
  catch (err) {
667
- const msg = err instanceof EditError || err instanceof InputValidationError || err instanceof Error ? err.message : String(err);
807
+ const fault = faultFromCaught(err);
808
+ recordFault(fault, toolToOperation(toolName));
809
+ const msg = err instanceof EditError || err instanceof CharsetFault || err instanceof Error ? err.message : String(err);
668
810
  return isNotification
669
811
  ? null
670
812
  : {
@@ -672,6 +814,7 @@ export function createMcpDispatcher(defaultCwd, scope = createReadScope()) {
672
814
  id: id ?? null,
673
815
  result: {
674
816
  content: [{ type: "text", text: msg }],
817
+ structuredContent: toMcpErrorEnvelope(fault),
675
818
  isError: true,
676
819
  },
677
820
  };
@@ -687,13 +830,33 @@ export function createMcpDispatcher(defaultCwd, scope = createReadScope()) {
687
830
  }
688
831
  return { handleRequest, scope };
689
832
  }
690
- /** Run the MCP server over stdin/stdout (supports newline-delimited JSON-RPC and Content-Length framing, backpressure drain, cancellation, and error isolation). */
691
- export function startMcpStdioServer(defaultCwd = process.cwd()) {
692
- const { handleRequest } = createMcpDispatcher(defaultCwd);
833
+ function isConcurrentReadOnlyMessage(parsed) {
834
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
835
+ return false;
836
+ const req = parsed;
837
+ const method = req.method;
838
+ if (method === "ping" || method === "tools/list" || method === "resources/list" || method === "resources/templates/list" || method === "prompts/list") {
839
+ return true;
840
+ }
841
+ if (method === "tools/call") {
842
+ const params = req.params;
843
+ return typeof params?.name === "string" && READ_ONLY_TOOLS.has(params.name);
844
+ }
845
+ return false;
846
+ }
847
+ /** Run the MCP server over stdin/stdout (supports newline-delimited JSON-RPC and Content-Length framing, concurrent read-only dispatch, backpressure drain, cancellation, and error isolation). */
848
+ export function startMcpStdioServer(defaultCwd = process.cwd(), opts) {
849
+ const { handleRequest } = createMcpDispatcher(defaultCwd, createReadScope(), { client: opts?.client });
693
850
  let buf = Buffer.alloc(0);
694
851
  let useContentLength = false;
695
- let chain = Promise.resolve();
852
+ let sendChain = Promise.resolve();
853
+ let mutatingChain = Promise.resolve();
854
+ let initBarrier = Promise.resolve();
696
855
  let pendingCount = 0;
856
+ let activeReads = 0;
857
+ const readWaiters = [];
858
+ const activeReadPromises = new Set();
859
+ const activeTasks = new Set();
697
860
  const inFlight = new Map();
698
861
  let stdoutClosed = false;
699
862
  process.stdout.on("error", (err) => {
@@ -702,24 +865,47 @@ export function startMcpStdioServer(defaultCwd = process.cwd()) {
702
865
  process.exitCode = 0;
703
866
  }
704
867
  });
705
- const send = async (payload) => {
706
- if (stdoutClosed || process.stdout.destroyed)
707
- return;
708
- const json = JSON.stringify(payload);
709
- const frame = useContentLength
710
- ? `Content-Length: ${Buffer.byteLength(json, "utf8")}\r\n\r\n${json}`
711
- : `${json}\n`;
712
- if (!process.stdout.write(frame)) {
713
- await once(process.stdout, "drain").catch(() => undefined);
714
- }
868
+ const send = (payload) => {
869
+ sendChain = sendChain.then(async () => {
870
+ if (stdoutClosed || process.stdout.destroyed)
871
+ return;
872
+ const json = JSON.stringify(payload);
873
+ const frame = useContentLength
874
+ ? `Content-Length: ${Buffer.byteLength(json, "utf8")}\r\n\r\n${json}`
875
+ : `${json}\n`;
876
+ if (!process.stdout.write(frame)) {
877
+ await once(process.stdout, "drain").catch(() => undefined);
878
+ }
879
+ });
880
+ return sendChain;
715
881
  };
716
882
  const flushStdout = async () => {
883
+ await sendChain;
717
884
  if (stdoutClosed || process.stdout.destroyed)
718
885
  return;
719
886
  await new Promise((resolve) => {
720
887
  process.stdout.write("", () => resolve());
721
888
  });
722
889
  };
890
+ const acquireReadSlot = async () => {
891
+ if (activeReads < MAX_CONCURRENT_READS) {
892
+ activeReads++;
893
+ return;
894
+ }
895
+ await new Promise((resolve) => readWaiters.push(resolve));
896
+ activeReads++;
897
+ };
898
+ const releaseReadSlot = () => {
899
+ activeReads--;
900
+ const next = readWaiters.shift();
901
+ if (next)
902
+ next();
903
+ };
904
+ const trackTask = (p) => {
905
+ activeTasks.add(p);
906
+ p.finally(() => activeTasks.delete(p));
907
+ return p;
908
+ };
723
909
  const cancelIfNotification = (parsed) => {
724
910
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
725
911
  return false;
@@ -762,7 +948,7 @@ export function startMcpStdioServer(defaultCwd = process.cwd()) {
762
948
  parsed = JSON.parse(raw);
763
949
  }
764
950
  catch (e) {
765
- chain = chain.then(() => send({ jsonrpc: "2.0", id: null, error: { code: -32700, message: `Parse error: ${e.message}` } }));
951
+ void trackTask(send({ jsonrpc: "2.0", id: null, error: { code: -32700, message: `Parse error: ${e.message}` } }));
766
952
  return;
767
953
  }
768
954
  // Handle cancellation notifications immediately out-of-band so they can abort an in-flight call.
@@ -773,12 +959,50 @@ export function startMcpStdioServer(defaultCwd = process.cwd()) {
773
959
  (typeof parsed.id === "string" || typeof parsed.id === "number")
774
960
  ? parsed.id
775
961
  : null;
776
- chain = chain.then(() => send({ jsonrpc: "2.0", id: idVal, error: { code: -32000, message: `Server busy: queue limit (${MAX_PENDING_REQUESTS}) exceeded.` } }));
962
+ void trackTask(send({ jsonrpc: "2.0", id: idVal, error: { code: -32000, message: `Server busy: queue limit (${MAX_PENDING_REQUESTS}) exceeded.` } }));
777
963
  return;
778
964
  }
779
965
  pendingCount++;
780
- chain = chain.then(async () => {
966
+ // Run read-only tool calls & metadata queries concurrently (after initialize and any prior mutations) so multi-file
967
+ // reads/greps do not head-of-line block each other and can be cancelled out-of-band immediately.
968
+ if (isConcurrentReadOnlyMessage(parsed)) {
969
+ const waitForMutations = mutatingChain;
970
+ const waitForInit = initBarrier;
971
+ const readPromise = (async () => {
972
+ try {
973
+ await waitForInit;
974
+ await waitForMutations;
975
+ await acquireReadSlot();
976
+ try {
977
+ const res = await runSingle(parsed);
978
+ if (res)
979
+ await send(res);
980
+ }
981
+ finally {
982
+ releaseReadSlot();
983
+ }
984
+ }
985
+ catch (err) {
986
+ await send({ jsonrpc: "2.0", id: null, error: { code: -32603, message: `Internal error: ${err instanceof Error ? err.message : String(err)}` } });
987
+ }
988
+ finally {
989
+ pendingCount--;
990
+ }
991
+ })();
992
+ activeReadPromises.add(readPromise);
993
+ readPromise.finally(() => activeReadPromises.delete(readPromise));
994
+ void trackTask(readPromise);
995
+ return;
996
+ }
997
+ const isInit = !Array.isArray(parsed) && parsed !== null && typeof parsed === "object" && parsed.method === "initialize";
998
+ const waitForInit = initBarrier;
999
+ const waitForReads = [...activeReadPromises];
1000
+ const task = mutatingChain.then(async () => {
781
1001
  try {
1002
+ if (!isInit)
1003
+ await waitForInit;
1004
+ if (waitForReads.length > 0)
1005
+ await Promise.allSettled(waitForReads);
782
1006
  if (Array.isArray(parsed)) {
783
1007
  if (parsed.length === 0) {
784
1008
  await send({ jsonrpc: "2.0", id: null, error: { code: -32600, message: "Invalid Request: empty batch." } });
@@ -807,6 +1031,10 @@ export function startMcpStdioServer(defaultCwd = process.cwd()) {
807
1031
  pendingCount--;
808
1032
  }
809
1033
  });
1034
+ mutatingChain = task;
1035
+ if (isInit)
1036
+ initBarrier = task;
1037
+ void trackTask(task);
810
1038
  };
811
1039
  const drain = () => {
812
1040
  while (buf.length > 0) {
@@ -818,7 +1046,7 @@ export function startMcpStdioServer(defaultCwd = process.cwd()) {
818
1046
  if (buf.length === 0)
819
1047
  break;
820
1048
  const head = buf.subarray(0, Math.min(buf.length, 32)).toString("ascii");
821
- if (/^content-length:/i.test(head)) {
1049
+ if (/^(?:content-length|content-type):/i.test(head)) {
822
1050
  useContentLength = true;
823
1051
  const sep = buf.indexOf("\r\n\r\n");
824
1052
  const sepAlt = sep === -1 ? buf.indexOf("\n\n") : -1;
@@ -830,9 +1058,15 @@ export function startMcpStdioServer(defaultCwd = process.cwd()) {
830
1058
  const m = /content-length:\s*(\d+)/i.exec(headerText);
831
1059
  if (!m) {
832
1060
  buf = buf.subarray(headerEnd + sepLen);
1061
+ void trackTask(send({ jsonrpc: "2.0", id: null, error: { code: -32600, message: "Invalid Request: missing Content-Length header." } }));
833
1062
  continue;
834
1063
  }
835
1064
  const bodyLen = Number(m[1]);
1065
+ if (!Number.isSafeInteger(bodyLen) || bodyLen < 0 || bodyLen > MAX_FRAME_BYTES) {
1066
+ buf = Buffer.alloc(0);
1067
+ void trackTask(send({ jsonrpc: "2.0", id: null, error: { code: -32600, message: `Invalid Request: Content-Length (${m[1]}) out of allowed bounds.` } }));
1068
+ break;
1069
+ }
836
1070
  const bodyStart = headerEnd + sepLen;
837
1071
  if (buf.length < bodyStart + bodyLen)
838
1072
  break;
@@ -858,9 +1092,13 @@ export function startMcpStdioServer(defaultCwd = process.cwd()) {
858
1092
  const rest = buf.toString("utf8").trim();
859
1093
  if (rest)
860
1094
  dispatchRaw(rest);
861
- void chain.finally(async () => {
1095
+ void (async () => {
1096
+ while (activeTasks.size > 0) {
1097
+ await Promise.allSettled([...activeTasks]);
1098
+ }
1099
+ await getIncidentRecorder(mapClientName(opts?.client)).flush(500).catch(() => undefined);
862
1100
  await flushStdout();
863
1101
  process.exitCode = 0;
864
- });
1102
+ })();
865
1103
  });
866
1104
  }