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.
package/src/mcp/server.ts CHANGED
@@ -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";
8
+ import { getIncidentRecorder, type IncidentRecorder } from "../diagnostics/incidents";
9
9
  import { containsNul } from "../encoding/classify";
10
10
  import { detectSupportedImageMimeType } from "../encoding/mime";
11
11
  import { compactRangeDiff, executeApplyPatch } from "../edit/apply-patch-core";
12
12
  import { EditError } from "../edit/diagnostics";
13
+ import { CharsetFault, isCharsetFault, REPORTABLE_FAULT_CODES, toMcpErrorEnvelope, type FaultMetadata } from "../faults";
13
14
  import { formatUpdatedHashlines, planHashlineEdits, type HashlineOp } from "../edit/hashline";
14
15
  import { planPatchEdits } from "../edit/patch";
15
16
  import { resolveEditPath, resolveReadPathCompat } from "../edit/paths";
@@ -41,19 +42,79 @@ const SUPPORTED_PROTOCOLS = new Set(["2025-06-18", "2025-03-26", "2024-11-05"]);
41
42
  const DEFAULT_READ_LIMIT = 2000;
42
43
  const MAX_READ_BYTES = 50 * 1024;
43
44
  const MAX_PENDING_REQUESTS = 64;
45
+ const MAX_CONCURRENT_READS = 8;
46
+ const MAX_FRAME_BYTES = 32 * 1024 * 1024;
47
+ const READ_ONLY_TOOLS = new Set(["charset_read", "charset_grep", "charset_check"]);
44
48
  const MCP_INSTRUCTIONS =
45
49
  "pi-charset-mcp works out-of-the-box with zero configuration (no .pi-charset.json needed). " +
46
50
  "Use charset_read, charset_edit, charset_apply_patch, charset_write, charset_grep, charset_check, and charset_fix " +
47
51
  "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. " +
48
52
  "When multiple agents share a workspace, pass the `version` returned by charset_read as `expectedVersion` to charset_write/charset_edit.";
49
53
 
50
- class InputValidationError extends Error {
54
+ class InputValidationError extends CharsetFault {
51
55
  constructor(message: string) {
52
- super(`[INVALID_INPUT; not_applied] ${message}`);
56
+ super(`[INVALID_INPUT; not_applied] ${message}`, {
57
+ code: "INVALID_INPUT",
58
+ category: "input",
59
+ phase: "validate",
60
+ outcome: "not_applied",
61
+ retryable: false,
62
+ actionHint: "Fix the tool input parameters and retry.",
63
+ });
53
64
  this.name = "InputValidationError";
54
65
  }
55
66
  }
56
67
 
68
+ function mapClientName(raw: unknown): string {
69
+ if (typeof raw !== "string") return "generic";
70
+ const s = raw.trim().toLowerCase();
71
+ if (s.includes("codex")) return "codex";
72
+ if (s.includes("antigravity-ide")) return "antigravity-ide";
73
+ if (s.includes("antigravity-app")) return "antigravity-app";
74
+ if (s.includes("antigravity") || s === "agy") return "agy";
75
+ if (s.includes("claude")) return "claude";
76
+ if (s.includes("cursor")) return "cursor";
77
+ if (s.includes("windsurf")) return "windsurf";
78
+ if (s === "pi") return "pi";
79
+ return "generic";
80
+ }
81
+
82
+ function toolToOperation(toolName: string): string {
83
+ switch (toolName) {
84
+ case "charset_read": return "read";
85
+ case "charset_write": return "write";
86
+ case "charset_edit": return "edit";
87
+ case "charset_apply_patch": return "apply_patch";
88
+ case "charset_grep": return "grep";
89
+ case "charset_check": return "check";
90
+ case "charset_fix": return "fix";
91
+ default: return "unknown";
92
+ }
93
+ }
94
+
95
+ function faultFromCaught(err: unknown): FaultMetadata {
96
+ if (isCharsetFault(err)) return err.fault;
97
+ if (err instanceof EditError) return err.toFaultMetadata();
98
+ const code = (err as NodeJS.ErrnoException | undefined)?.code;
99
+ if (code === "ENOENT") {
100
+ return { code: "NOT_FOUND", category: "io", phase: "detect", outcome: "not_applied", retryable: false, actionHint: "Check the file path and retry." };
101
+ }
102
+ if (code === "EACCES" || code === "EPERM") {
103
+ return { code: "PERMISSION_DENIED", category: "io", phase: "validate", outcome: "not_applied", retryable: false, actionHint: "Check file permissions and retry." };
104
+ }
105
+ if (code === "EBUSY") {
106
+ return { code: "LOCK_BUSY", category: "io", phase: "commit", retryable: true, outcome: "not_applied", actionHint: "Close external editors locking the file and retry." };
107
+ }
108
+ return {
109
+ code: "INTERNAL",
110
+ category: "engine",
111
+ phase: "unknown",
112
+ outcome: "unknown",
113
+ retryable: false,
114
+ actionHint: "Re-read the target file to verify on-disk state; run `pi-charset feedback list` to inspect sanitized local diagnostics.",
115
+ };
116
+ }
117
+
57
118
  function coercePathArg(args: Record<string, unknown>): string | undefined {
58
119
  const raw = typeof args.path === "string" ? args.path : typeof args.file_path === "string" ? args.file_path : undefined;
59
120
  return raw && raw.trim() ? raw : undefined;
@@ -136,6 +197,14 @@ export const MCP_TOOLS = [
136
197
  name: "charset_read",
137
198
  description:
138
199
  "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.",
200
+ annotations: {
201
+ title: "Read File (Encoding-Safe)",
202
+ readOnlyHint: true,
203
+ destructiveHint: false,
204
+ idempotentHint: true,
205
+ openWorldHint: false,
206
+ },
207
+ _meta: { "antigravity/alwaysLoad": true },
139
208
  inputSchema: {
140
209
  type: "object",
141
210
  additionalProperties: false,
@@ -159,6 +228,13 @@ export const MCP_TOOLS = [
159
228
  name: "charset_write",
160
229
  description:
161
230
  "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).",
231
+ annotations: {
232
+ title: "Write File (Encoding-Safe)",
233
+ readOnlyHint: false,
234
+ destructiveHint: false,
235
+ idempotentHint: true,
236
+ openWorldHint: false,
237
+ },
162
238
  inputSchema: {
163
239
  type: "object",
164
240
  additionalProperties: false,
@@ -179,6 +255,14 @@ export const MCP_TOOLS = [
179
255
  name: "charset_edit",
180
256
  description:
181
257
  "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.",
258
+ annotations: {
259
+ title: "Edit File (Encoding-Safe)",
260
+ readOnlyHint: false,
261
+ destructiveHint: false,
262
+ idempotentHint: false,
263
+ openWorldHint: false,
264
+ },
265
+ _meta: { "antigravity/alwaysLoad": true },
182
266
  inputSchema: {
183
267
  type: "object",
184
268
  additionalProperties: false,
@@ -214,6 +298,13 @@ export const MCP_TOOLS = [
214
298
  name: "charset_apply_patch",
215
299
  description:
216
300
  "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.",
301
+ annotations: {
302
+ title: "Apply Multi-File Patch (Encoding-Safe)",
303
+ readOnlyHint: false,
304
+ destructiveHint: true,
305
+ idempotentHint: false,
306
+ openWorldHint: false,
307
+ },
217
308
  inputSchema: {
218
309
  type: "object",
219
310
  additionalProperties: false,
@@ -228,6 +319,14 @@ export const MCP_TOOLS = [
228
319
  name: "charset_grep",
229
320
  description:
230
321
  "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.",
322
+ annotations: {
323
+ title: "Search Files (Multi-Encoding)",
324
+ readOnlyHint: true,
325
+ destructiveHint: false,
326
+ idempotentHint: true,
327
+ openWorldHint: false,
328
+ },
329
+ _meta: { "antigravity/alwaysLoad": true },
231
330
  inputSchema: {
232
331
  type: "object",
233
332
  additionalProperties: false,
@@ -251,6 +350,13 @@ export const MCP_TOOLS = [
251
350
  name: "charset_check",
252
351
  description:
253
352
  "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.",
353
+ annotations: {
354
+ title: "Check Encoding & Health",
355
+ readOnlyHint: true,
356
+ destructiveHint: false,
357
+ idempotentHint: true,
358
+ openWorldHint: false,
359
+ },
254
360
  inputSchema: {
255
361
  type: "object",
256
362
  additionalProperties: false,
@@ -265,6 +371,13 @@ export const MCP_TOOLS = [
265
371
  name: "charset_fix",
266
372
  description:
267
373
  "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).",
374
+ annotations: {
375
+ title: "Fix Encoding / EOL / Undo",
376
+ readOnlyHint: false,
377
+ destructiveHint: false,
378
+ idempotentHint: false,
379
+ openWorldHint: false,
380
+ },
268
381
  inputSchema: {
269
382
  type: "object",
270
383
  additionalProperties: false,
@@ -314,7 +427,35 @@ function validateRpcEnvelope(
314
427
  return { ok: true, req: obj as unknown as JsonRpcRequest };
315
428
  }
316
429
 
317
- export function createMcpDispatcher(defaultCwd: string, scope: ReadScope = createReadScope()) {
430
+ export function createMcpDispatcher(
431
+ defaultCwd: string,
432
+ scope: ReadScope = createReadScope(),
433
+ opts?: { client?: string; recorder?: IncidentRecorder },
434
+ ) {
435
+ let activeClient = mapClientName(opts?.client);
436
+ const recordFault = (fault: FaultMetadata, operation: string) => {
437
+ if (!REPORTABLE_FAULT_CODES.has(fault.code)) return;
438
+ const rec = opts?.recorder ?? getIncidentRecorder(activeClient);
439
+ rec.record({
440
+ code: fault.code,
441
+ operation,
442
+ phase: fault.phase,
443
+ outcome: fault.outcome,
444
+ encoding: fault.encoding,
445
+ eol: fault.eol,
446
+ fileBytes: fault.fileBytes,
447
+ });
448
+ };
449
+
450
+ const failTool = (message: string, fault: FaultMetadata, operation: string): ToolCallOutcome => {
451
+ recordFault(fault, operation);
452
+ return {
453
+ text: message,
454
+ isError: true,
455
+ structuredContent: toMcpErrorEnvelope(fault) as unknown as Record<string, unknown>,
456
+ };
457
+ };
458
+
318
459
  const resolveCwd = (args: Record<string, unknown>) => {
319
460
  const cwdArg = coerceOptionalString(args, "cwd");
320
461
  return cwdArg && cwdArg.trim() ? path.resolve(defaultCwd, cwdArg) : defaultCwd;
@@ -326,7 +467,11 @@ export function createMcpDispatcher(defaultCwd: string, scope: ReadScope = creat
326
467
  if (name === "charset_read") {
327
468
  const pathArg = coercePathArg(args);
328
469
  if (!pathArg) {
329
- return { text: "[INVALID_INPUT; not_applied] path is required.", isError: true };
470
+ return failTool(
471
+ "[INVALID_INPUT; not_applied] path is required.",
472
+ { code: "INVALID_INPUT", category: "input", phase: "validate", outcome: "not_applied", retryable: false, actionHint: "Pass path or file_path." },
473
+ "read",
474
+ );
330
475
  }
331
476
  const outlineArg = coerceOptionalBoolean(args, "outline") ?? false;
332
477
  const hashlinesOpt = coerceOptionalBoolean(args, "hashlines");
@@ -346,18 +491,18 @@ export function createMcpDispatcher(defaultCwd: string, scope: ReadScope = creat
346
491
  );
347
492
  const buf = await readOps.readFile(absPath);
348
493
  if (detectSupportedImageMimeType(buf)) {
349
- return {
350
- text: `[BINARY_IMAGE] ${absPath} (${buf.length}B) is an image file; use a binary/image reader.`,
351
- isError: true,
352
- structuredContent: { path: absPath, kind: "image", bytesOnDisk: buf.length },
353
- };
494
+ return failTool(
495
+ `[BINARY_IMAGE] ${absPath} (${buf.length}B) is an image file; use a binary/image reader.`,
496
+ { code: "BINARY_FILE", category: "policy", phase: "detect", outcome: "not_applied", retryable: false, actionHint: "Use an image/binary reader for image files.", fileBytes: buf.length },
497
+ "read",
498
+ );
354
499
  }
355
500
  if (containsNul(buf)) {
356
- return {
357
- text: `[BINARY_FILE] ${absPath} (${buf.length}B) contains NUL bytes and cannot be displayed as text.`,
358
- isError: true,
359
- structuredContent: { path: absPath, kind: "binary", bytesOnDisk: buf.length },
360
- };
501
+ return failTool(
502
+ `[BINARY_FILE] ${absPath} (${buf.length}B) contains NUL bytes and cannot be displayed as text.`,
503
+ { code: "BINARY_FILE", category: "policy", phase: "detect", outcome: "not_applied", retryable: false, actionHint: "Binary files are refused by text tools.", fileBytes: buf.length },
504
+ "read",
505
+ );
361
506
  }
362
507
  if (scope.epoch === epoch && observed) scope.baselines.set(observed.key, observed.version);
363
508
 
@@ -420,11 +565,15 @@ export function createMcpDispatcher(defaultCwd: string, scope: ReadScope = creat
420
565
  if (name === "charset_write") {
421
566
  const pathArg = coercePathArg(args);
422
567
  if (!pathArg || typeof args.content !== "string") {
423
- return { text: "[INVALID_INPUT; not_applied] path and content are required.", isError: true };
568
+ return failTool(
569
+ "[INVALID_INPUT; not_applied] path and content are required.",
570
+ { code: "INVALID_INPUT", category: "input", phase: "validate", outcome: "not_applied", retryable: false, actionHint: "Pass path (or file_path) and content." },
571
+ "write",
572
+ );
424
573
  }
425
574
  const expectedVersion = coerceOptionalString(args, "expectedVersion");
426
575
  const absPath = resolveEditPath(pathArg, baseCwd);
427
- await mkdir(path.dirname(absPath), { recursive: true });
576
+ // Parent directory creation happens inside writeFileDetailed ONLY after expectedVersion + Gate 1/3 pass.
428
577
  const outcome = await writeFileDetailed(absPath, args.content, scope, expectedVersion);
429
578
  const suffix = notesToSuffix(drainEncodingNotes(absPath));
430
579
  return {
@@ -436,7 +585,11 @@ export function createMcpDispatcher(defaultCwd: string, scope: ReadScope = creat
436
585
  if (name === "charset_edit") {
437
586
  const pathArg = coercePathArg(args);
438
587
  if (!pathArg) {
439
- return { text: "[INVALID_INPUT; not_applied] path is required.", isError: true };
588
+ return failTool(
589
+ "[INVALID_INPUT; not_applied] path is required.",
590
+ { code: "INVALID_INPUT", category: "input", phase: "validate", outcome: "not_applied", retryable: false, actionHint: "Pass path or file_path." },
591
+ "edit",
592
+ );
440
593
  }
441
594
  const expectedVersion = coerceOptionalString(args, "expectedVersion");
442
595
  const presentModes = [
@@ -446,10 +599,11 @@ export function createMcpDispatcher(defaultCwd: string, scope: ReadScope = creat
446
599
  args.wholeFile !== undefined ? "wholeFile" : null,
447
600
  ].filter((m): m is "edits" | "hashlines" | "patch" | "wholeFile" => m !== null);
448
601
  if (presentModes.length !== 1) {
449
- return {
450
- text: "[INVALID_INPUT; not_applied] Supply exactly one of: edits, hashlines, patch, or wholeFile.",
451
- isError: true,
452
- };
602
+ return failTool(
603
+ "[INVALID_INPUT; not_applied] Supply exactly one of: edits, hashlines, patch, or wholeFile.",
604
+ { code: "INVALID_INPUT", category: "input", phase: "validate", outcome: "not_applied", retryable: false, actionHint: "Pass exactly one edit payload: edits, hashlines, patch, or wholeFile." },
605
+ "edit",
606
+ );
453
607
  }
454
608
  const mode = presentModes[0];
455
609
  const editsArg = mode === "edits" ? coerceArrayArg<EditReplacement>(args.edits, "edits", true) : undefined;
@@ -494,7 +648,11 @@ export function createMcpDispatcher(defaultCwd: string, scope: ReadScope = creat
494
648
 
495
649
  if (name === "charset_apply_patch") {
496
650
  if (typeof args.patch !== "string" || !args.patch.trim()) {
497
- return { text: "[INVALID_INPUT; not_applied] patch is required.", isError: true };
651
+ return failTool(
652
+ "[INVALID_INPUT; not_applied] patch is required.",
653
+ { code: "INVALID_INPUT", category: "input", phase: "validate", outcome: "not_applied", retryable: false, actionHint: "Pass a non-empty patch string." },
654
+ "apply_patch",
655
+ );
498
656
  }
499
657
  const res = await executeApplyPatch(baseCwd, args.patch, scope, signal);
500
658
  return {
@@ -513,7 +671,11 @@ export function createMcpDispatcher(defaultCwd: string, scope: ReadScope = creat
513
671
 
514
672
  if (name === "charset_grep") {
515
673
  if (typeof args.pattern !== "string" || !args.pattern) {
516
- return { text: "[INVALID_INPUT; not_applied] pattern is required.", isError: true };
674
+ return failTool(
675
+ "[INVALID_INPUT; not_applied] pattern is required.",
676
+ { code: "INVALID_INPUT", category: "input", phase: "validate", outcome: "not_applied", retryable: false, actionHint: "Pass a non-empty search pattern." },
677
+ "grep",
678
+ );
517
679
  }
518
680
  const ignoreCase = coerceOptionalBoolean(args, "ignoreCase") ?? false;
519
681
  const literal = coerceOptionalBoolean(args, "literal") ?? false;
@@ -539,23 +701,21 @@ export function createMcpDispatcher(defaultCwd: string, scope: ReadScope = creat
539
701
  signal,
540
702
  );
541
703
  if (!res) {
542
- return {
543
- text: "[GREP_UNAVAILABLE] ripgrep (rg) was not found or search path is invalid.",
544
- isError: true,
545
- structuredContent: { status: "failed", error: "ripgrep unavailable or invalid path" },
546
- };
704
+ return failTool(
705
+ "[GREP_UNAVAILABLE] ripgrep (rg) was not found or search path is invalid.",
706
+ { 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." },
707
+ "grep",
708
+ );
547
709
  }
548
710
  if (res.status === "failed") {
549
- return {
550
- text: res.text,
551
- isError: true,
552
- structuredContent: {
553
- status: "failed",
554
- error: res.error,
555
- searchedWith: res.searchedWith,
556
- failedPasses: res.failedPasses,
557
- },
558
- };
711
+ const isSyntax = /regex parse error/i.test(res.error ?? "");
712
+ return failTool(
713
+ res.text,
714
+ isSyntax
715
+ ? { code: "INVALID_INPUT", category: "input", phase: "search", outcome: "not_applied", retryable: false, actionHint: "Fix the regular expression or pass literal=true." }
716
+ : { code: "SEARCH_ENGINE_FAILED", category: "compatibility", phase: "search", outcome: "not_applied", retryable: true, actionHint: "Check search pattern and ripgrep status via `pi-charset doctor`." },
717
+ "grep",
718
+ );
559
719
  }
560
720
  return {
561
721
  text: res.text,
@@ -598,7 +758,11 @@ export function createMcpDispatcher(defaultCwd: string, scope: ReadScope = creat
598
758
  if (action === "normalize_eol") {
599
759
  const to = (toArg ?? "").toUpperCase();
600
760
  if (!pathArg || (to !== "CRLF" && to !== "LF")) {
601
- return { text: "[INVALID_INPUT; not_applied] normalize_eol requires path and to='CRLF'|'LF'.", isError: true };
761
+ return failTool(
762
+ "[INVALID_INPUT; not_applied] normalize_eol requires path and to='CRLF'|'LF'.",
763
+ { code: "INVALID_INPUT", category: "input", phase: "validate", outcome: "not_applied", retryable: false, actionHint: "Pass path and to='CRLF' or to='LF'." },
764
+ "fix",
765
+ );
602
766
  }
603
767
  const absPath = resolveEditPath(pathArg, baseCwd);
604
768
  const res = await normalizeFileLineEndings(absPath, to, scope, dryRun);
@@ -610,7 +774,11 @@ export function createMcpDispatcher(defaultCwd: string, scope: ReadScope = creat
610
774
  }
611
775
  if (action === "convert") {
612
776
  if (!pathArg || !toArg || !toArg.trim()) {
613
- return { text: "[INVALID_INPUT; not_applied] convert requires path and to='<encoding>'.", isError: true };
777
+ return failTool(
778
+ "[INVALID_INPUT; not_applied] convert requires path and to='<encoding>'.",
779
+ { code: "INVALID_INPUT", category: "input", phase: "validate", outcome: "not_applied", retryable: false, actionHint: "Pass path and target encoding in to." },
780
+ "fix",
781
+ );
614
782
  }
615
783
  const absPath = resolveEditPath(pathArg, baseCwd);
616
784
  const res = await convertFileEncoding(absPath, toArg, scope, { bom, dryRun });
@@ -636,7 +804,20 @@ export function createMcpDispatcher(defaultCwd: string, scope: ReadScope = creat
636
804
  return {
637
805
  text: res.reason,
638
806
  isError: true,
639
- structuredContent: { ok: false, action: "undo", dryRun, applied: false, reason: res.reason },
807
+ structuredContent: {
808
+ ...toMcpErrorEnvelope({
809
+ code: "CONFLICT",
810
+ category: "conflict",
811
+ phase: "rollback",
812
+ outcome: "not_applied",
813
+ retryable: false,
814
+ actionHint: "Inspect the file and session journal before retrying undo.",
815
+ }),
816
+ ok: false,
817
+ action: "undo",
818
+ dryRun,
819
+ reason: res.reason,
820
+ },
640
821
  };
641
822
  }
642
823
  const items = res.entries ?? [{ entry: res.entry, action: res.action }];
@@ -663,10 +844,18 @@ export function createMcpDispatcher(defaultCwd: string, scope: ReadScope = creat
663
844
  },
664
845
  };
665
846
  }
666
- return { text: `[INVALID_INPUT; not_applied] Unknown action "${action}".`, isError: true };
847
+ return failTool(
848
+ `[INVALID_INPUT; not_applied] Unknown action "${action}".`,
849
+ { code: "INVALID_INPUT", category: "input", phase: "validate", outcome: "not_applied", retryable: false, actionHint: "Use action: normalize_eol, convert, auto_fix_eol, or undo." },
850
+ "fix",
851
+ );
667
852
  }
668
853
 
669
- return { text: `Unknown tool: ${name}`, isError: true };
854
+ return failTool(
855
+ `[INVALID_INPUT; not_applied] Unknown tool: ${name}`,
856
+ { code: "INVALID_INPUT", category: "input", phase: "validate", outcome: "not_applied", retryable: false, actionHint: "Call tools/list to inspect available tool names." },
857
+ "unknown",
858
+ );
670
859
  }
671
860
 
672
861
  async function handleRequest(rawReq: unknown, signal?: AbortSignal): Promise<JsonRpcResponse | null> {
@@ -680,6 +869,10 @@ export function createMcpDispatcher(defaultCwd: string, scope: ReadScope = creat
680
869
  return null;
681
870
  }
682
871
  if (req.method === "initialize") {
872
+ if (!opts?.client) {
873
+ const clientInfo = req.params?.clientInfo as Record<string, unknown> | undefined;
874
+ activeClient = mapClientName(clientInfo?.name);
875
+ }
683
876
  const requested = typeof req.params?.protocolVersion === "string" ? req.params.protocolVersion : "2024-11-05";
684
877
  const protocolVersion = SUPPORTED_PROTOCOLS.has(requested) ? requested : "2024-11-05";
685
878
  return {
@@ -732,7 +925,9 @@ export function createMcpDispatcher(defaultCwd: string, scope: ReadScope = creat
732
925
  },
733
926
  };
734
927
  } catch (err) {
735
- const msg = err instanceof EditError || err instanceof InputValidationError || err instanceof Error ? err.message : String(err);
928
+ const fault = faultFromCaught(err);
929
+ recordFault(fault, toolToOperation(toolName));
930
+ const msg = err instanceof EditError || err instanceof CharsetFault || err instanceof Error ? err.message : String(err);
736
931
  return isNotification
737
932
  ? null
738
933
  : {
@@ -740,6 +935,7 @@ export function createMcpDispatcher(defaultCwd: string, scope: ReadScope = creat
740
935
  id: id ?? null,
741
936
  result: {
742
937
  content: [{ type: "text", text: msg }],
938
+ structuredContent: toMcpErrorEnvelope(fault),
743
939
  isError: true,
744
940
  },
745
941
  };
@@ -756,13 +952,33 @@ export function createMcpDispatcher(defaultCwd: string, scope: ReadScope = creat
756
952
  return { handleRequest, scope };
757
953
  }
758
954
 
759
- /** Run the MCP server over stdin/stdout (supports newline-delimited JSON-RPC and Content-Length framing, backpressure drain, cancellation, and error isolation). */
760
- export function startMcpStdioServer(defaultCwd = process.cwd()): void {
761
- const { handleRequest } = createMcpDispatcher(defaultCwd);
955
+ function isConcurrentReadOnlyMessage(parsed: unknown): boolean {
956
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return false;
957
+ const req = parsed as Record<string, unknown>;
958
+ const method = req.method;
959
+ if (method === "ping" || method === "tools/list" || method === "resources/list" || method === "resources/templates/list" || method === "prompts/list") {
960
+ return true;
961
+ }
962
+ if (method === "tools/call") {
963
+ const params = req.params as Record<string, unknown> | undefined;
964
+ return typeof params?.name === "string" && READ_ONLY_TOOLS.has(params.name);
965
+ }
966
+ return false;
967
+ }
968
+
969
+ /** 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). */
970
+ export function startMcpStdioServer(defaultCwd = process.cwd(), opts?: { client?: string }): void {
971
+ const { handleRequest } = createMcpDispatcher(defaultCwd, createReadScope(), { client: opts?.client });
762
972
  let buf: Buffer = Buffer.alloc(0);
763
973
  let useContentLength = false;
764
- let chain = Promise.resolve();
974
+ let sendChain = Promise.resolve();
975
+ let mutatingChain = Promise.resolve();
976
+ let initBarrier = Promise.resolve();
765
977
  let pendingCount = 0;
978
+ let activeReads = 0;
979
+ const readWaiters: Array<() => void> = [];
980
+ const activeReadPromises = new Set<Promise<void>>();
981
+ const activeTasks = new Set<Promise<void>>();
766
982
  const inFlight = new Map<string, AbortController>();
767
983
 
768
984
  let stdoutClosed = false;
@@ -773,24 +989,49 @@ export function startMcpStdioServer(defaultCwd = process.cwd()): void {
773
989
  }
774
990
  });
775
991
 
776
- const send = async (payload: JsonRpcResponse | JsonRpcResponse[]): Promise<void> => {
777
- if (stdoutClosed || process.stdout.destroyed) return;
778
- const json = JSON.stringify(payload);
779
- const frame = useContentLength
780
- ? `Content-Length: ${Buffer.byteLength(json, "utf8")}\r\n\r\n${json}`
781
- : `${json}\n`;
782
- if (!process.stdout.write(frame)) {
783
- await once(process.stdout, "drain").catch(() => undefined);
784
- }
992
+ const send = (payload: JsonRpcResponse | JsonRpcResponse[]): Promise<void> => {
993
+ sendChain = sendChain.then(async () => {
994
+ if (stdoutClosed || process.stdout.destroyed) return;
995
+ const json = JSON.stringify(payload);
996
+ const frame = useContentLength
997
+ ? `Content-Length: ${Buffer.byteLength(json, "utf8")}\r\n\r\n${json}`
998
+ : `${json}\n`;
999
+ if (!process.stdout.write(frame)) {
1000
+ await once(process.stdout, "drain").catch(() => undefined);
1001
+ }
1002
+ });
1003
+ return sendChain;
785
1004
  };
786
1005
 
787
1006
  const flushStdout = async (): Promise<void> => {
1007
+ await sendChain;
788
1008
  if (stdoutClosed || process.stdout.destroyed) return;
789
1009
  await new Promise<void>((resolve) => {
790
1010
  process.stdout.write("", () => resolve());
791
1011
  });
792
1012
  };
793
1013
 
1014
+ const acquireReadSlot = async (): Promise<void> => {
1015
+ if (activeReads < MAX_CONCURRENT_READS) {
1016
+ activeReads++;
1017
+ return;
1018
+ }
1019
+ await new Promise<void>((resolve) => readWaiters.push(resolve));
1020
+ activeReads++;
1021
+ };
1022
+
1023
+ const releaseReadSlot = (): void => {
1024
+ activeReads--;
1025
+ const next = readWaiters.shift();
1026
+ if (next) next();
1027
+ };
1028
+
1029
+ const trackTask = (p: Promise<void>): Promise<void> => {
1030
+ activeTasks.add(p);
1031
+ p.finally(() => activeTasks.delete(p));
1032
+ return p;
1033
+ };
1034
+
794
1035
  const cancelIfNotification = (parsed: unknown): boolean => {
795
1036
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return false;
796
1037
  const obj = parsed as Record<string, unknown>;
@@ -830,7 +1071,7 @@ export function startMcpStdioServer(defaultCwd = process.cwd()): void {
830
1071
  try {
831
1072
  parsed = JSON.parse(raw);
832
1073
  } catch (e) {
833
- chain = chain.then(() => send({ jsonrpc: "2.0", id: null, error: { code: -32700, message: `Parse error: ${(e as Error).message}` } }));
1074
+ void trackTask(send({ jsonrpc: "2.0", id: null, error: { code: -32700, message: `Parse error: ${(e as Error).message}` } }));
834
1075
  return;
835
1076
  }
836
1077
  // Handle cancellation notifications immediately out-of-band so they can abort an in-flight call.
@@ -842,13 +1083,47 @@ export function startMcpStdioServer(defaultCwd = process.cwd()): void {
842
1083
  (typeof (parsed as Record<string, unknown>).id === "string" || typeof (parsed as Record<string, unknown>).id === "number")
843
1084
  ? ((parsed as Record<string, unknown>).id as string | number)
844
1085
  : null;
845
- chain = chain.then(() => send({ jsonrpc: "2.0", id: idVal, error: { code: -32000, message: `Server busy: queue limit (${MAX_PENDING_REQUESTS}) exceeded.` } }));
1086
+ void trackTask(send({ jsonrpc: "2.0", id: idVal, error: { code: -32000, message: `Server busy: queue limit (${MAX_PENDING_REQUESTS}) exceeded.` } }));
846
1087
  return;
847
1088
  }
848
1089
 
849
1090
  pendingCount++;
850
- chain = chain.then(async () => {
1091
+
1092
+ // Run read-only tool calls & metadata queries concurrently (after initialize and any prior mutations) so multi-file
1093
+ // reads/greps do not head-of-line block each other and can be cancelled out-of-band immediately.
1094
+ if (isConcurrentReadOnlyMessage(parsed)) {
1095
+ const waitForMutations = mutatingChain;
1096
+ const waitForInit = initBarrier;
1097
+ const readPromise = (async () => {
1098
+ try {
1099
+ await waitForInit;
1100
+ await waitForMutations;
1101
+ await acquireReadSlot();
1102
+ try {
1103
+ const res = await runSingle(parsed);
1104
+ if (res) await send(res);
1105
+ } finally {
1106
+ releaseReadSlot();
1107
+ }
1108
+ } catch (err) {
1109
+ await send({ jsonrpc: "2.0", id: null, error: { code: -32603, message: `Internal error: ${err instanceof Error ? err.message : String(err)}` } });
1110
+ } finally {
1111
+ pendingCount--;
1112
+ }
1113
+ })();
1114
+ activeReadPromises.add(readPromise);
1115
+ readPromise.finally(() => activeReadPromises.delete(readPromise));
1116
+ void trackTask(readPromise);
1117
+ return;
1118
+ }
1119
+
1120
+ const isInit = !Array.isArray(parsed) && parsed !== null && typeof parsed === "object" && (parsed as Record<string, unknown>).method === "initialize";
1121
+ const waitForInit = initBarrier;
1122
+ const waitForReads = [...activeReadPromises];
1123
+ const task = mutatingChain.then(async () => {
851
1124
  try {
1125
+ if (!isInit) await waitForInit;
1126
+ if (waitForReads.length > 0) await Promise.allSettled(waitForReads);
852
1127
  if (Array.isArray(parsed)) {
853
1128
  if (parsed.length === 0) {
854
1129
  await send({ jsonrpc: "2.0", id: null, error: { code: -32600, message: "Invalid Request: empty batch." } });
@@ -871,6 +1146,9 @@ export function startMcpStdioServer(defaultCwd = process.cwd()): void {
871
1146
  pendingCount--;
872
1147
  }
873
1148
  });
1149
+ mutatingChain = task;
1150
+ if (isInit) initBarrier = task;
1151
+ void trackTask(task);
874
1152
  };
875
1153
 
876
1154
  const drain = () => {
@@ -881,7 +1159,7 @@ export function startMcpStdioServer(defaultCwd = process.cwd()): void {
881
1159
  if (buf.length === 0) break;
882
1160
 
883
1161
  const head = buf.subarray(0, Math.min(buf.length, 32)).toString("ascii");
884
- if (/^content-length:/i.test(head)) {
1162
+ if (/^(?:content-length|content-type):/i.test(head)) {
885
1163
  useContentLength = true;
886
1164
  const sep = buf.indexOf("\r\n\r\n");
887
1165
  const sepAlt = sep === -1 ? buf.indexOf("\n\n") : -1;
@@ -890,8 +1168,17 @@ export function startMcpStdioServer(defaultCwd = process.cwd()): void {
890
1168
  if (headerEnd === -1) break;
891
1169
  const headerText = buf.subarray(0, headerEnd).toString("ascii");
892
1170
  const m = /content-length:\s*(\d+)/i.exec(headerText);
893
- if (!m) { buf = buf.subarray(headerEnd + sepLen); continue; }
1171
+ if (!m) {
1172
+ buf = buf.subarray(headerEnd + sepLen);
1173
+ void trackTask(send({ jsonrpc: "2.0", id: null, error: { code: -32600, message: "Invalid Request: missing Content-Length header." } }));
1174
+ continue;
1175
+ }
894
1176
  const bodyLen = Number(m[1]);
1177
+ if (!Number.isSafeInteger(bodyLen) || bodyLen < 0 || bodyLen > MAX_FRAME_BYTES) {
1178
+ buf = Buffer.alloc(0);
1179
+ void trackTask(send({ jsonrpc: "2.0", id: null, error: { code: -32600, message: `Invalid Request: Content-Length (${m[1]}) out of allowed bounds.` } }));
1180
+ break;
1181
+ }
895
1182
  const bodyStart = headerEnd + sepLen;
896
1183
  if (buf.length < bodyStart + bodyLen) break;
897
1184
  const body = buf.subarray(bodyStart, bodyStart + bodyLen).toString("utf8");
@@ -915,9 +1202,13 @@ export function startMcpStdioServer(defaultCwd = process.cwd()): void {
915
1202
  process.stdin.on("end", () => {
916
1203
  const rest = buf.toString("utf8").trim();
917
1204
  if (rest) dispatchRaw(rest);
918
- void chain.finally(async () => {
1205
+ void (async () => {
1206
+ while (activeTasks.size > 0) {
1207
+ await Promise.allSettled([...activeTasks]);
1208
+ }
1209
+ await getIncidentRecorder(mapClientName(opts?.client)).flush(500).catch(() => undefined);
919
1210
  await flushStdout();
920
1211
  process.exitCode = 0;
921
- });
1212
+ })();
922
1213
  });
923
1214
  }