codebase-snapshot 0.9.12 → 0.9.15

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.
@@ -1,6 +1,6 @@
1
- import { GENERATOR_VERSION, anchorForPath, displayPath, MIN_MAX_PART_BYTES, SCHEMA_VERSION, GENERATOR_NAME, ARTIFACT_NAMES, PRESETS, generateSnapshot, generateInWorker, validateSnapshot, buildImportResolver, resolveSpecifier, truncateToBytes, explainPath, renderExplainText, describeManifestShapeProblem, loadConfigFileDetailed, parseByteSize, resolveConfig } from './chunk-3H45YMBG.js';
1
+ import { GENERATOR_VERSION, anchorForPath, displayPath, MIN_MAX_PART_BYTES, SCHEMA_VERSION, GENERATOR_NAME, ARTIFACT_NAMES, PRESETS, generateSnapshot, generateInWorker, validateSnapshot, buildImportResolver, resolveSpecifier, truncateToBytes, explainPath, renderExplainText, describeManifestShapeProblem, loadConfigFileDetailed, parseByteSize, resolveConfig } from './chunk-JL4VDGXL.js';
2
2
  import * as fs from 'fs';
3
- import * as path2 from 'path';
3
+ import * as path from 'path';
4
4
 
5
5
  // src/mcp/protocol.ts
6
6
  var LEGACY_PROTOCOL_VERSIONS = ["2025-11-25", "2025-06-18"];
@@ -16,6 +16,16 @@ var ERROR_CODES = {
16
16
  methodNotFound: -32601,
17
17
  invalidParams: -32602,
18
18
  internalError: -32603,
19
+ /**
20
+ * A resource whose complete text is larger than one read may return.
21
+ *
22
+ * `-32000` is JSON-RPC's range for implementation-defined server errors, which is what this is:
23
+ * there is no standard code for "the document is too large", and answering with -32602 would tell
24
+ * a client its request was malformed when it was not. The message names the size, the limit and
25
+ * the tool to use instead, because a resource read that cannot return the whole resource must not
26
+ * invent a partial one.
27
+ */
28
+ resourceTooLarge: -32e3,
19
29
  unsupportedProtocolVersion: -32022
20
30
  };
21
31
  var METHOD = {
@@ -157,371 +167,21 @@ function negotiateLegacyVersion(requested) {
157
167
  return { version: DEFAULT_LEGACY_PROTOCOL_VERSION, matched: false };
158
168
  }
159
169
 
160
- // src/mcp/schema.ts
161
- function validateArguments(schema, value) {
162
- if (value === void 0) value = {};
163
- if (!isJsonObject(value)) return ["arguments must be a JSON object"];
164
- const problems = [];
165
- const known = new Set(Object.keys(schema.properties));
166
- for (const key of Object.keys(value)) {
167
- if (!known.has(key) && schema.additionalProperties !== true) {
168
- const allowed = [...known].sort().join(", ");
169
- problems.push(`unknown argument "${key}" (accepted: ${allowed || "none"})`);
170
- }
171
- }
172
- for (const required of schema.required ?? []) {
173
- if (value[required] === void 0) problems.push(`missing required argument "${required}"`);
174
- }
175
- for (const [key, propertySchema] of Object.entries(schema.properties)) {
176
- const argument = value[key];
177
- if (argument === void 0) continue;
178
- problems.push(...checkValue(key, propertySchema, argument));
179
- }
180
- return problems;
181
- }
182
- function checkValue(path4, schema, value) {
183
- if (schema.enum && !schema.enum.includes(value)) {
184
- return [`"${path4}" must be one of: ${schema.enum.join(", ")}`];
185
- }
186
- switch (schema.type) {
187
- case "string": {
188
- if (typeof value !== "string") return [`"${path4}" must be a string`];
189
- const problems = [];
190
- if (schema.minLength !== void 0 && value.length < schema.minLength) {
191
- problems.push(`"${path4}" must be at least ${schema.minLength} character(s)`);
192
- }
193
- if (schema.maxLength !== void 0 && value.length > schema.maxLength) {
194
- problems.push(`"${path4}" must be at most ${schema.maxLength} character(s)`);
195
- }
196
- return problems;
197
- }
198
- case "number":
199
- case "integer": {
200
- if (typeof value !== "number" || Number.isNaN(value)) {
201
- return [`"${path4}" must be a number`];
202
- }
203
- if (schema.type === "integer" && !Number.isInteger(value)) {
204
- return [`"${path4}" must be an integer`];
205
- }
206
- const problems = [];
207
- if (schema.minimum !== void 0 && value < schema.minimum) {
208
- problems.push(`"${path4}" must be >= ${schema.minimum}`);
209
- }
210
- if (schema.maximum !== void 0 && value > schema.maximum) {
211
- problems.push(`"${path4}" must be <= ${schema.maximum}`);
212
- }
213
- return problems;
214
- }
215
- case "boolean":
216
- return typeof value === "boolean" ? [] : [`"${path4}" must be a boolean`];
217
- case "array": {
218
- if (!Array.isArray(value)) return [`"${path4}" must be an array`];
219
- if (!schema.items) return [];
220
- const problems = [];
221
- value.forEach((item, index) => {
222
- problems.push(...checkValue(`${path4}[${index}]`, schema.items, item));
223
- });
224
- return problems;
225
- }
226
- case "object":
227
- return isJsonObject(value) ? [] : [`"${path4}" must be an object`];
228
- default:
229
- return [];
230
- }
231
- }
232
- function applyDefaults(schema, value) {
233
- const out = { ...value };
234
- for (const [key, propertySchema] of Object.entries(schema.properties)) {
235
- if (out[key] === void 0 && propertySchema.default !== void 0) {
236
- out[key] = propertySchema.default;
237
- }
238
- }
239
- return out;
240
- }
241
- function coerceNumericStrings(schema, value) {
242
- const out = { ...value };
243
- for (const [key, propertySchema] of Object.entries(schema.properties)) {
244
- const raw = out[key];
245
- if (typeof raw !== "string") continue;
246
- if (propertySchema.type !== "number" && propertySchema.type !== "integer") continue;
247
- if (raw.trim().length === 0) continue;
248
- const parsed = Number(raw);
249
- if (Number.isFinite(parsed)) out[key] = parsed;
250
- }
251
- return out;
252
- }
253
-
254
- // src/mcp/server.ts
255
- function capabilities() {
256
- return {
257
- tools: { listChanged: false },
258
- resources: { subscribe: false, listChanged: false },
259
- prompts: { listChanged: false }
260
- };
261
- }
262
- function requestIdOf(message) {
263
- const raw = message.id;
264
- return typeof raw === "string" || typeof raw === "number" ? raw : null;
265
- }
266
- function createMcpServer(options) {
267
- const session = createSession();
268
- const toolsByName = new Map(options.tools.map((tool) => [tool.name, tool]));
269
- const promptsByName = new Map(options.prompts.map((prompt) => [prompt.name, prompt]));
270
- const identity = () => ({
271
- name: options.info.name,
272
- title: options.info.title,
273
- version: options.info.version,
274
- websiteUrl: options.info.websiteUrl
275
- });
276
- const ok = (id, result, modern) => successResponse(id, result, modern, options.info);
277
- function handleNotification(method) {
278
- if (method === METHOD.initialized && session.era === "legacy") session.ready = true;
279
- }
280
- function initialize(id, params) {
281
- const negotiation = negotiateLegacyVersion(params?.protocolVersion);
282
- session.era = "legacy";
283
- session.protocolVersion = negotiation.version;
284
- session.ready = true;
285
- options.context.log(
286
- negotiation.matched ? `mcp: client initialized with protocol ${negotiation.version}` : `mcp: client asked for an unsupported version and was offered ${negotiation.version}`
287
- );
288
- return {
289
- jsonrpc: "2.0",
290
- id,
291
- result: {
292
- protocolVersion: negotiation.version,
293
- capabilities: capabilities(),
294
- serverInfo: identity(),
295
- instructions: options.instructions
296
- }
297
- };
298
- }
299
- function discover(id) {
300
- session.era = "modern";
301
- session.ready = true;
302
- return ok(
303
- id,
304
- {
305
- supportedVersions: [...SUPPORTED_PROTOCOL_VERSIONS],
306
- capabilities: capabilities(),
307
- instructions: options.instructions,
308
- // The capability set depends on which repository the server was started for, so the answer
309
- // may be cached only by the client that asked, and not at all after this response.
310
- cacheScope: "private",
311
- ttlMs: 0
312
- },
313
- true
314
- );
315
- }
316
- function listTools(id, modern) {
317
- const tools = options.tools.map((tool) => ({
318
- name: tool.name,
319
- title: tool.title,
320
- description: tool.description,
321
- inputSchema: tool.inputSchema,
322
- ...tool.outputSchema ? { outputSchema: tool.outputSchema } : {},
323
- annotations: tool.annotations
324
- }));
325
- return ok(id, { tools }, modern);
326
- }
327
- async function callTool(id, modern, params) {
328
- const name = params?.name;
329
- if (typeof name !== "string") {
330
- return errorResponse(id, ERROR_CODES.invalidParams, 'tools/call requires a "name" string.');
331
- }
332
- const tool = toolsByName.get(name);
333
- if (!tool) {
334
- const known = [...toolsByName.keys()].sort().join(", ");
335
- return errorResponse(id, ERROR_CODES.invalidParams, `Unknown tool "${name}". Available: ${known}.`);
336
- }
337
- const rawArguments = params?.arguments ?? {};
338
- if (!isJsonObject(rawArguments)) {
339
- return errorResponse(id, ERROR_CODES.invalidParams, '"arguments" must be a JSON object.');
340
- }
341
- const supplied = coerceNumericStrings(tool.inputSchema, rawArguments);
342
- const problems = validateArguments(tool.inputSchema, supplied);
343
- if (problems.length > 0) {
344
- return ok(
345
- id,
346
- {
347
- content: [{ type: "text", text: `Invalid arguments for ${tool.name}:
348
- - ${problems.join("\n- ")}` }],
349
- isError: true
350
- },
351
- modern
352
- );
353
- }
354
- const args = applyDefaults(tool.inputSchema, supplied);
355
- let outcome;
356
- try {
357
- outcome = await tool.handler(args, options.context);
358
- } catch (error) {
359
- const detail = error instanceof Error ? error.message : String(error);
360
- options.context.log(`mcp: tool ${tool.name} failed: ${detail}`);
361
- return ok(
362
- id,
363
- { content: [{ type: "text", text: `${tool.name} failed: ${detail}` }], isError: true },
364
- modern
365
- );
366
- }
367
- return ok(
368
- id,
369
- {
370
- content: [{ type: "text", text: outcome.text }],
371
- ...outcome.structured ? { structuredContent: outcome.structured } : {},
372
- ...outcome.isError ? { isError: true } : {}
373
- },
374
- modern
375
- );
376
- }
377
- async function listResources(id, modern) {
378
- const resources = await options.resources.list(options.context);
379
- return ok(id, { resources }, modern);
380
- }
381
- async function readResource(id, modern, params) {
382
- const uri = params?.uri;
383
- if (typeof uri !== "string") {
384
- return errorResponse(id, ERROR_CODES.invalidParams, 'resources/read requires a "uri" string.');
385
- }
386
- const contents = await options.resources.read(uri, options.context);
387
- if (!contents) {
388
- return errorResponse(id, ERROR_CODES.invalidParams, `Unknown resource "${uri}".`);
389
- }
390
- return ok(id, { contents: [contents] }, modern);
391
- }
392
- function listPrompts(id, modern) {
393
- const prompts = options.prompts.map((prompt) => ({
394
- name: prompt.name,
395
- ...prompt.title ? { title: prompt.title } : {},
396
- description: prompt.description,
397
- arguments: prompt.arguments
398
- }));
399
- return ok(id, { prompts }, modern);
400
- }
401
- function getPrompt(id, modern, params) {
402
- const name = params?.name;
403
- if (typeof name !== "string") {
404
- return errorResponse(id, ERROR_CODES.invalidParams, 'prompts/get requires a "name" string.');
405
- }
406
- const prompt = promptsByName.get(name);
407
- if (!prompt) {
408
- const known = [...promptsByName.keys()].sort().join(", ");
409
- return errorResponse(id, ERROR_CODES.invalidParams, `Unknown prompt "${name}". Available: ${known}.`);
410
- }
411
- const rawArguments = params?.arguments ?? {};
412
- if (!isJsonObject(rawArguments)) {
413
- return errorResponse(id, ERROR_CODES.invalidParams, '"arguments" must be a JSON object.');
414
- }
415
- const built = prompt.build(rawArguments);
416
- const messages = built.messages.map((message) => ({
417
- role: message.role,
418
- content: { type: "text", text: message.content.text }
419
- }));
420
- return ok(id, { description: built.description, messages }, modern);
421
- }
422
- async function route(name, id, modern, params) {
423
- switch (name) {
424
- case METHOD.initialize:
425
- return modern ? errorResponse(
426
- id,
427
- ERROR_CODES.methodNotFound,
428
- '"initialize" does not exist in this protocol revision; call "server/discover".'
429
- ) : initialize(id, params);
430
- case METHOD.discover:
431
- return discover(id);
432
- case METHOD.ping:
433
- return modern ? errorResponse(
434
- id,
435
- ERROR_CODES.methodNotFound,
436
- '"ping" was removed in this protocol revision; call "server/discover".'
437
- ) : ok(id, {}, modern);
438
- }
439
- if (!session.ready) {
440
- return errorResponse(
441
- id,
442
- ERROR_CODES.invalidRequest,
443
- 'This connection has not been initialized. Send "initialize" first.'
444
- );
445
- }
446
- switch (name) {
447
- case METHOD.toolsList:
448
- return listTools(id, modern);
449
- case METHOD.toolsCall:
450
- return callTool(id, modern, params);
451
- case METHOD.resourcesList:
452
- return listResources(id, modern);
453
- case METHOD.resourcesRead:
454
- return readResource(id, modern, params);
455
- case METHOD.resourceTemplatesList:
456
- return ok(id, { resourceTemplates: options.resources.templates() }, modern);
457
- case METHOD.promptsList:
458
- return listPrompts(id, modern);
459
- case METHOD.promptsGet:
460
- return getPrompt(id, modern, params);
461
- default:
462
- return errorResponse(id, ERROR_CODES.methodNotFound, `Unknown method "${name}".`);
463
- }
464
- }
465
- async function dispatch(message) {
466
- if (!isJsonObject(message)) {
467
- return errorResponse(null, ERROR_CODES.parseError, "Message is not a JSON object.");
468
- }
469
- const isRequest = Object.prototype.hasOwnProperty.call(message, "id");
470
- const method = message.method;
471
- const params = message.params;
472
- if (message.jsonrpc !== "2.0" && isRequest) {
473
- return errorResponse(requestIdOf(message), ERROR_CODES.invalidRequest, 'Message must carry "jsonrpc": "2.0".');
474
- }
475
- if (typeof method !== "string" || method.length === 0) {
476
- return isRequest ? errorResponse(requestIdOf(message), ERROR_CODES.invalidRequest, 'Message must carry a "method" string.') : null;
477
- }
478
- if (params !== void 0 && !isJsonObject(params)) {
479
- return isRequest ? errorResponse(requestIdOf(message), ERROR_CODES.invalidRequest, '"params" must be a JSON object when present.') : null;
480
- }
481
- const named = params;
482
- const decision = classifyRequest(method, named, session);
483
- const modern = decision.kind === "era" ? decision.era === "modern" : session.era === "modern";
484
- if (!isRequest) {
485
- if (decision.kind === "era" && session.era === null) {
486
- session.era = decision.era;
487
- session.protocolVersion = decision.version;
488
- }
489
- handleNotification(method);
490
- return null;
491
- }
492
- const id = requestIdOf(message);
493
- if (id === null) {
494
- return errorResponse(null, ERROR_CODES.invalidRequest, 'A request "id" must be a string or a number.');
495
- }
496
- if (decision.kind === "error") {
497
- return errorResponse(id, decision.code, decision.message, decision.data);
498
- }
499
- if (session.era === null) {
500
- session.era = decision.era;
501
- session.protocolVersion = decision.version;
502
- }
503
- return route(method, id, modern, named);
504
- }
505
- return {
506
- session,
507
- async handle(message) {
508
- try {
509
- return await dispatch(message);
510
- } catch (error) {
511
- const detail = error instanceof Error ? error.message : String(error);
512
- options.context.log(`mcp: internal error: ${detail}`);
513
- const id = isJsonObject(message) ? requestIdOf(message) : null;
514
- return errorResponse(id, ERROR_CODES.internalError, "Internal server error.");
515
- }
516
- }
517
- };
518
- }
519
-
520
170
  // src/mcp/part.ts
521
171
  var FILE_HEADING = "### FILE: ";
522
172
  var CONTENT_MARKERS = /* @__PURE__ */ new Set(["#### Content", "#### Bounded Preview"]);
523
173
  var ANCHOR_LINE = /^<a id="([^"]+)"><\/a>$/;
174
+ var META_PREFIX = "- Meta: ";
175
+ var LEGACY_INCLUSION_PREFIX = "- Inclusion: ";
176
+ var LEGACY_INCLUDED_LINES_PREFIX = "- Included Lines: ";
524
177
  var INCLUSION_MODES = /* @__PURE__ */ new Set(["full", "preview", "signatures"]);
178
+ var COMPACT_COUNTS = /^(\d+)\s+lines?(?:\s+of\s+\d+\s+lines?)?/;
179
+ function readIncludedLines(fields) {
180
+ const last = fields[fields.length - 1];
181
+ if (last === void 0) return null;
182
+ const counts = COMPACT_COUNTS.exec(last.trim());
183
+ return counts === null ? null : Number(counts[1]);
184
+ }
525
185
  function parsePartSections(partText) {
526
186
  const lines = partText.split("\n");
527
187
  const sections = [];
@@ -539,20 +199,17 @@ function parsePartSections(partText) {
539
199
  while (cursor < lines.length && !CONTENT_MARKERS.has(lines[cursor])) {
540
200
  const line = lines[cursor];
541
201
  if (line.startsWith(FILE_HEADING)) break;
542
- if (line.startsWith("- Meta: ")) {
543
- for (const field of line.slice("- Meta: ".length).split("|")) {
202
+ if (line.startsWith(META_PREFIX)) {
203
+ const fields = line.slice(META_PREFIX.length).split("|");
204
+ for (const field of fields) {
544
205
  const value = field.trim();
545
206
  if (INCLUSION_MODES.has(value)) inclusion = value;
546
207
  }
547
- const counts = /(-?\d+) of (-?\d+) lines|(\d+) lines/.exec(line);
548
- if (counts) {
549
- const emitted = counts[1] ?? counts[3];
550
- includedLines = Number.isFinite(Number(emitted)) ? Number(emitted) : null;
551
- }
552
- } else if (line.startsWith("- Inclusion: ")) {
553
- inclusion = line.slice("- Inclusion: ".length).trim();
554
- } else if (line.startsWith("- Included Lines: ")) {
555
- const value = Number(line.slice("- Included Lines: ".length).trim());
208
+ includedLines = readIncludedLines(fields);
209
+ } else if (line.startsWith(LEGACY_INCLUSION_PREFIX)) {
210
+ inclusion = line.slice(LEGACY_INCLUSION_PREFIX.length).trim();
211
+ } else if (line.startsWith(LEGACY_INCLUDED_LINES_PREFIX)) {
212
+ const value = Number(line.slice(LEGACY_INCLUDED_LINES_PREFIX.length).trim());
556
213
  includedLines = Number.isFinite(value) ? value : null;
557
214
  }
558
215
  cursor += 1;
@@ -617,7 +274,7 @@ function foldForComparison(value) {
617
274
  return process.platform === "win32" || process.platform === "darwin" ? value.toLowerCase() : value;
618
275
  }
619
276
  function canonicalPath(value) {
620
- const absolute = path2.resolve(value);
277
+ const absolute = path.resolve(value);
621
278
  try {
622
279
  return fs.realpathSync(absolute);
623
280
  } catch {
@@ -627,14 +284,26 @@ function canonicalPath(value) {
627
284
  function isInside(parent, child) {
628
285
  const foldedParent = foldForComparison(parent);
629
286
  const foldedChild = foldForComparison(child);
630
- return foldedChild === foldedParent || foldedChild.startsWith(`${foldedParent}${path2.sep}`);
287
+ return foldedChild === foldedParent || foldedChild.startsWith(`${foldedParent}${path.sep}`);
288
+ }
289
+ function resolveThroughExistingAncestor(target) {
290
+ let existing = target;
291
+ const missing = [];
292
+ while (!fs.existsSync(existing)) {
293
+ missing.unshift(path.basename(existing));
294
+ const parent = path.dirname(existing);
295
+ if (parent === existing) break;
296
+ existing = parent;
297
+ }
298
+ const resolved = canonicalPath(existing);
299
+ return missing.length === 0 ? resolved : path.join(resolved, ...missing);
631
300
  }
632
301
  function resolveRoot(requested, context) {
633
302
  if (requested !== void 0 && (typeof requested !== "string" || requested.trim().length === 0)) {
634
303
  return { ok: false, message: '"root" must be a non-empty string when provided.' };
635
304
  }
636
305
  const wanted = typeof requested === "string" ? requested.trim() : context.cwd;
637
- const absolute = path2.resolve(context.cwd, wanted);
306
+ const absolute = path.resolve(context.cwd, wanted);
638
307
  let stats;
639
308
  try {
640
309
  stats = fs.statSync(absolute);
@@ -651,10 +320,10 @@ function resolveRoot(requested, context) {
651
320
  const shown = context.roots.join(", ");
652
321
  return {
653
322
  ok: false,
654
- message: `"${wanted}" resolves outside the directories this server may read (${shown}). Restart it with --root <path> to add a repository.`
323
+ message: `"${wanted}" resolves outside the directories this server may read (${shown}). The server reads the directory it was started for; restart it with --cwd <directory> to serve a different repository.`
655
324
  };
656
325
  }
657
- async function openWorkspace(root, overrides = {}) {
326
+ async function openWorkspace(root, overrides = {}, allowedRoots) {
658
327
  const loaded = await loadConfigFileDetailed(root);
659
328
  if (loaded.errors.length > 0) {
660
329
  return {
@@ -673,12 +342,45 @@ async function openWorkspace(root, overrides = {}) {
673
342
  }
674
343
  cliOptions.maxPartBytes = parsed;
675
344
  }
345
+ if (overrides.maxPartTokens !== void 0) {
346
+ const parsed = parseByteSize(overrides.maxPartTokens);
347
+ if (parsed === void 0) {
348
+ return {
349
+ ok: false,
350
+ message: '"maxPartTokens" must be a token count, for example 32000 or "32k".'
351
+ };
352
+ }
353
+ cliOptions.maxPartTokens = parsed;
354
+ }
676
355
  if (overrides.outDir !== void 0) {
677
356
  if (typeof overrides.outDir !== "string" || overrides.outDir.trim().length === 0) {
678
357
  return { ok: false, message: '"outDir" must be a non-empty string.' };
679
358
  }
680
- cliOptions.outDir = overrides.outDir.trim();
359
+ const requested = overrides.outDir.trim();
360
+ const permitted = allowedRoots !== void 0 && allowedRoots.length > 0 ? allowedRoots : [root];
361
+ const resolved = resolveThroughExistingAncestor(path.resolve(root, requested));
362
+ if (!permitted.some((allowed) => isInside(canonicalPath(allowed), resolved))) {
363
+ const shown = permitted.map((allowed) => canonicalPath(allowed)).join(", ");
364
+ return {
365
+ ok: false,
366
+ message: `"outDir" must resolve inside the repository this server serves (${shown}). A tool argument may not place the snapshot outside it; pass a directory inside the root, or restart the server with --cwd pointing at the repository you want to write.`
367
+ };
368
+ }
369
+ cliOptions.outDir = requested;
370
+ }
371
+ if (overrides.changedSince !== void 0) {
372
+ if (typeof overrides.changedSince !== "string" || overrides.changedSince.trim().length === 0) {
373
+ return {
374
+ ok: false,
375
+ message: '"changedSince" must be a git ref such as "main" or "HEAD~3".'
376
+ };
377
+ }
378
+ cliOptions.changedSince = overrides.changedSince.trim();
681
379
  }
380
+ if (overrides.skeleton === true) cliOptions.skeleton = true;
381
+ if (overrides.sarif === true) cliOptions.sarif = true;
382
+ if (overrides.staged === true) cliOptions.staged = true;
383
+ if (overrides.withDependents === true) cliOptions.withDependents = true;
682
384
  try {
683
385
  const config = resolveConfig(loaded.config, cliOptions, root);
684
386
  return { ok: true, workspace: { root, config, configFile: loaded.file, cliOptions } };
@@ -688,11 +390,21 @@ async function openWorkspace(root, overrides = {}) {
688
390
  }
689
391
  var manifestCache = /* @__PURE__ */ new Map();
690
392
  function manifestPathFor(workspace) {
691
- return path2.resolve(workspace.root, workspace.config.outDir, "manifest.json");
393
+ return path.resolve(workspace.root, workspace.config.outDir, "manifest.json");
394
+ }
395
+ function partPathFor(workspace, filename) {
396
+ if (filename.length === 0 || filename.includes("\0")) return null;
397
+ const partsDir = path.resolve(workspace.root, workspace.config.outDir, "parts");
398
+ const resolved = path.resolve(partsDir, filename);
399
+ const relative3 = path.relative(partsDir, resolved);
400
+ if (relative3.length === 0 || relative3.includes(path.sep) || relative3.includes("/") || relative3.includes("\\") || path.isAbsolute(relative3)) {
401
+ return null;
402
+ }
403
+ return resolved;
692
404
  }
693
405
  function readManifest(workspace) {
694
406
  const file = manifestPathFor(workspace);
695
- const shown = path2.relative(workspace.root, file).split(path2.sep).join("/") || file;
407
+ const shown = path.relative(workspace.root, file).split(path.sep).join("/") || file;
696
408
  let stats;
697
409
  try {
698
410
  stats = fs.statSync(file);
@@ -757,9 +469,47 @@ var ROOT_PROPERTY = {
757
469
  };
758
470
  var OUT_DIR_PROPERTY = {
759
471
  type: "string",
760
- description: "Snapshot directory, relative to the root. Defaults to the project configuration's outDir."
472
+ description: "Snapshot directory, relative to the root, and it must resolve inside the served repository. Defaults to the project configuration's outDir."
761
473
  };
762
474
  var outDirOverride = (args) => ({ outDir: args.outDir });
475
+ var SCOPE_PROPERTIES = {
476
+ maxPartTokens: {
477
+ type: "string",
478
+ description: 'Token ceiling per part, for example 32000 or "32k". Narrower than maxPartBytes; it converts at four bytes per token.'
479
+ },
480
+ skeleton: {
481
+ type: "boolean",
482
+ description: "Replace every function body with `{ /* ... */ }`, keeping signatures, imports and exports. Applies to TypeScript, JavaScript and JSX."
483
+ },
484
+ sarif: {
485
+ type: "boolean",
486
+ description: "Also write reports/audit.sarif beside reports/audit.md, for CI code scanning."
487
+ },
488
+ changedSince: {
489
+ type: "string",
490
+ description: 'Only files changed since this git ref, for example "main" or "HEAD~3".'
491
+ },
492
+ staged: {
493
+ type: "boolean",
494
+ description: "Only files staged in the git index."
495
+ },
496
+ withDependents: {
497
+ type: "boolean",
498
+ description: "With staged or changedSince, also include the files that import the changed ones (one hop)."
499
+ }
500
+ };
501
+ function workspaceOverrides(args) {
502
+ return {
503
+ outDir: args.outDir,
504
+ maxPartBytes: args.maxPartBytes,
505
+ maxPartTokens: args.maxPartTokens,
506
+ skeleton: args.skeleton,
507
+ sarif: args.sarif,
508
+ changedSince: args.changedSince,
509
+ staged: args.staged,
510
+ withDependents: args.withDependents
511
+ };
512
+ }
763
513
  function failure(message) {
764
514
  return { text: message, isError: true };
765
515
  }
@@ -772,7 +522,7 @@ function formatBytes(bytes) {
772
522
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
773
523
  }
774
524
  function relativeFor(workspace, absolute) {
775
- return path2.relative(workspace.root, absolute).split(path2.sep).join("/");
525
+ return path.relative(workspace.root, absolute).split(path.sep).join("/");
776
526
  }
777
527
  function capped(values, limit = 20) {
778
528
  return { count: values.length, sample: values.slice(0, limit) };
@@ -790,13 +540,14 @@ function summarizeDrift(drift) {
790
540
  }
791
541
  function toRelativePath(root, value) {
792
542
  const cleaned = value.trim();
793
- if (cleaned.length === 0) return null;
794
- if (!path2.isAbsolute(cleaned)) {
795
- return cleaned.replace(/\\/g, "/").replace(/^\.\//, "");
543
+ if (cleaned.length === 0 || cleaned.includes("\0")) return null;
544
+ const resolvedRoot = path.resolve(root);
545
+ const absolute = path.resolve(resolvedRoot, cleaned);
546
+ const relative3 = path.relative(resolvedRoot, absolute);
547
+ if (relative3 === "" || relative3 === ".." || relative3.startsWith(`..${path.sep}`) || path.isAbsolute(relative3)) {
548
+ return null;
796
549
  }
797
- const relative3 = path2.relative(root, cleaned);
798
- if (relative3.startsWith("..") || path2.isAbsolute(relative3)) return null;
799
- return relative3.split(path2.sep).join("/");
550
+ return relative3.split(path.sep).join("/");
800
551
  }
801
552
  function symbolsOf(entry) {
802
553
  const summary = entry.summary;
@@ -837,7 +588,7 @@ function symbolsOf(entry) {
837
588
  async function prepare(args, context, overrides = {}) {
838
589
  const rootOutcome = resolveRoot(args.root, context);
839
590
  if (!rootOutcome.ok) return { ok: false, outcome: failure(rootOutcome.message) };
840
- const opened = await openWorkspace(rootOutcome.root, overrides);
591
+ const opened = await openWorkspace(rootOutcome.root, overrides, context.roots);
841
592
  if (!opened.ok) return { ok: false, outcome: failure(opened.message) };
842
593
  return { ok: true, workspace: opened.workspace };
843
594
  }
@@ -931,7 +682,8 @@ var planTool = {
931
682
  maxPartBytes: {
932
683
  type: "string",
933
684
  description: 'Byte budget per part, for example 307200 or "300k". Defaults to the project configuration.'
934
- }
685
+ },
686
+ ...SCOPE_PROPERTIES
935
687
  },
936
688
  additionalProperties: false
937
689
  },
@@ -948,7 +700,7 @@ var planTool = {
948
700
  },
949
701
  annotations: READ_ONLY,
950
702
  async handler(args, context) {
951
- const prepared = await prepare(args, context, { maxPartBytes: args.maxPartBytes, outDir: args.outDir });
703
+ const prepared = await prepare(args, context, workspaceOverrides(args));
952
704
  if (!prepared.ok) return prepared.outcome;
953
705
  const workspace = prepared.workspace;
954
706
  let manifest;
@@ -1006,7 +758,8 @@ var generateTool = {
1006
758
  maxPartBytes: {
1007
759
  type: "string",
1008
760
  description: 'Byte budget per part, for example 307200 or "300k". Defaults to the project configuration.'
1009
- }
761
+ },
762
+ ...SCOPE_PROPERTIES
1010
763
  },
1011
764
  additionalProperties: false
1012
765
  },
@@ -1022,17 +775,14 @@ var generateTool = {
1022
775
  },
1023
776
  annotations: WRITES,
1024
777
  async handler(args, context) {
1025
- const prepared = await prepare(args, context, {
1026
- maxPartBytes: args.maxPartBytes,
1027
- outDir: args.outDir
1028
- });
778
+ const prepared = await prepare(args, context, workspaceOverrides(args));
1029
779
  if (!prepared.ok) return prepared.outcome;
1030
780
  const workspace = prepared.workspace;
1031
781
  const result = await generateInWorker(workspace.root, workspace.cliOptions);
1032
782
  if (!result.ok) return failure(result.message);
1033
783
  const summary = result.summary;
1034
784
  forgetManifest(manifestPathFor(workspace));
1035
- const written = relativeFor(workspace, path2.resolve(workspace.root, workspace.config.outDir));
785
+ const written = relativeFor(workspace, path.resolve(workspace.root, workspace.config.outDir));
1036
786
  const lines = [
1037
787
  `Wrote ${written}/`,
1038
788
  `Files: ${summary.totalFiles} included, ${summary.skippedCount} skipped, ${plural(summary.partsCount, "part")}`,
@@ -1064,7 +814,7 @@ var validateTool = {
1064
814
  description: "Re-read the repository and report whether the snapshot on disk still matches it. Use it before trusting context that came from an earlier session, or after changing the config.",
1065
815
  inputSchema: {
1066
816
  type: "object",
1067
- properties: { root: ROOT_PROPERTY, outDir: OUT_DIR_PROPERTY },
817
+ properties: { root: ROOT_PROPERTY, outDir: OUT_DIR_PROPERTY, ...SCOPE_PROPERTIES },
1068
818
  additionalProperties: false
1069
819
  },
1070
820
  outputSchema: {
@@ -1076,7 +826,7 @@ var validateTool = {
1076
826
  },
1077
827
  annotations: READ_ONLY,
1078
828
  async handler(args, context) {
1079
- const prepared = await prepare(args, context, outDirOverride(args));
829
+ const prepared = await prepare(args, context, workspaceOverrides(args));
1080
830
  if (!prepared.ok) return prepared.outcome;
1081
831
  const workspace = prepared.workspace;
1082
832
  let result;
@@ -1421,7 +1171,12 @@ var readTool = {
1421
1171
  `${relativePath} is not in the snapshot. Call snapshot_locate to find the path, or snapshot_explain to learn why it was excluded.`
1422
1172
  );
1423
1173
  }
1424
- const partPath = path2.resolve(workspace.root, workspace.config.outDir, "parts", entry.part);
1174
+ const partPath = partPathFor(workspace, entry.part);
1175
+ if (partPath === null) {
1176
+ return failure(
1177
+ `${entry.part} is not a part of this snapshot: its name leaves ${workspace.config.outDir}/parts. Run snapshot_generate to rebuild it.`
1178
+ );
1179
+ }
1425
1180
  let partText;
1426
1181
  try {
1427
1182
  partText = fs.readFileSync(partPath, "utf8");
@@ -1501,7 +1256,8 @@ var explainTool = {
1501
1256
  description: "Path relative to the repository root. Directories are explained as a whole."
1502
1257
  },
1503
1258
  root: ROOT_PROPERTY,
1504
- outDir: OUT_DIR_PROPERTY
1259
+ outDir: OUT_DIR_PROPERTY,
1260
+ ...SCOPE_PROPERTIES
1505
1261
  },
1506
1262
  required: ["path"],
1507
1263
  additionalProperties: false
@@ -1516,7 +1272,7 @@ var explainTool = {
1516
1272
  },
1517
1273
  annotations: READ_ONLY,
1518
1274
  async handler(args, context) {
1519
- const prepared = await prepare(args, context, outDirOverride(args));
1275
+ const prepared = await prepare(args, context, workspaceOverrides(args));
1520
1276
  if (!prepared.ok) return prepared.outcome;
1521
1277
  const workspace = prepared.workspace;
1522
1278
  if (typeof args.path !== "string") return failure('"path" must be a string.');
@@ -1681,16 +1437,14 @@ var COMMAND_OPTION_SCOPE = {
1681
1437
  "version"
1682
1438
  ],
1683
1439
  validate: VALIDATE_OPTIONS,
1440
+ // `report` reads `manifest.json` and prints what is there; a generation setting would change
1441
+ // nothing. The seven generation flags used to be listed here and were accepted as silent no-ops
1442
+ // — the exact "flag that parses but changes nothing" this table exists to prevent — while
1443
+ // `--discovery` was already rejected. Both the parser and `describe`'s `appliesTo` read this
1444
+ // list, so removing them narrows the two together.
1684
1445
  report: [
1685
1446
  "cwd",
1686
1447
  "out-dir",
1687
- "max-part-bytes",
1688
- "large-file-bytes",
1689
- "max-monolith-bytes",
1690
- "include-monolith",
1691
- "include-sensitive-files",
1692
- "skip-artifacts",
1693
- "only-artifacts",
1694
1448
  "no-config",
1695
1449
  "no-update-check",
1696
1450
  "format",
@@ -2161,7 +1915,7 @@ function buildAgentContract() {
2161
1915
  type: "string",
2162
1916
  default: "generate",
2163
1917
  appliesTo: optionAppliesTo("mode"),
2164
- summary: "Select the command when no command word is given. Values: generate, validate, check, report, init, setup, explain, diff, describe, skill. A command word and --mode must name the same command; a contradiction is a usage error (exit 2)."
1918
+ summary: "Select the command when no command word is given. Values: generate, validate, check, report, init, setup, explain, diff, describe, skill, mcp. A command word and --mode must name the same command; a contradiction is a usage error (exit 2)."
2165
1919
  },
2166
1920
  {
2167
1921
  flag: "--cwd",
@@ -2298,7 +2052,7 @@ function buildAgentContract() {
2298
2052
  { key: "preset", type: "string", default: "detected", summary: "Force a preset. Unknown names are an error." },
2299
2053
  { key: "maxPartBytes", type: "number | string", default: 307200, summary: "Per-part byte budget." },
2300
2054
  { key: "maxPartTokens", type: "number | string | null", default: null, summary: "Per-part token ceiling; narrows maxPartBytes. Minimum 1024." },
2301
- { key: "skeleton", type: "boolean", default: false, summary: "Collapse function bodies to `{ /* ... */ }` in TypeScript files." },
2055
+ { key: "skeleton", type: "boolean", default: false, summary: "Collapse function bodies to `{ /* ... */ }` in TS, JS, TSX and JSX files." },
2302
2056
  { key: "sarif", type: "boolean", default: false, summary: "Also write reports/audit.sarif." },
2303
2057
  { key: "changedSince", type: "string | null", default: null, summary: "Snapshot only files that differ from this git ref." },
2304
2058
  { key: "staged", type: "boolean", default: false, summary: "Snapshot only files staged in the index." },
@@ -2560,6 +2314,34 @@ from an earlier session.
2560
2314
 
2561
2315
  // src/mcp/resources.ts
2562
2316
  var MAX_RESOURCE_BYTES = 512 * 1024;
2317
+ var ResourceTooLargeError = class extends Error {
2318
+ constructor(uri, bytes, limit, message) {
2319
+ super(message);
2320
+ this.uri = uri;
2321
+ this.bytes = bytes;
2322
+ this.limit = limit;
2323
+ this.name = "ResourceTooLargeError";
2324
+ }
2325
+ uri;
2326
+ bytes;
2327
+ limit;
2328
+ };
2329
+ function refuseTooLarge(uri, bytes, advice) {
2330
+ throw new ResourceTooLargeError(
2331
+ uri,
2332
+ bytes,
2333
+ MAX_RESOURCE_BYTES,
2334
+ `${uri} is ${formatBytes2(bytes)}, above the ${formatBytes2(MAX_RESOURCE_BYTES)} single-read limit, so it was not returned. ${advice}`
2335
+ );
2336
+ }
2337
+ function ensureSingleRead(uri, text, advice) {
2338
+ const bytes = Buffer.byteLength(text, "utf8");
2339
+ if (bytes > MAX_RESOURCE_BYTES) refuseTooLarge(uri, bytes, advice);
2340
+ return text;
2341
+ }
2342
+ var MANIFEST_ADVICE = "Cutting a JSON document at the limit leaves invalid JSON, so this resource is never truncated. Use the snapshot_locate, snapshot_read and snapshot_status tools instead \u2014 they read the manifest directly \u2014 or read manifest.json from the snapshot directory.";
2343
+ var PART_ADVICE = "A part cut at the limit is a fragment of a file, not the file. Use snapshot_locate to find the file inside this part that you need, then snapshot_read for a bounded window of it.";
2344
+ var REPORT_ADVICE = "A report cut at the limit would look complete and would not be. Read it from the snapshot directory instead: the file on disk is complete.";
2563
2345
  var PART_URI = /^snapshot:\/\/parts\/(\d+)$/;
2564
2346
  var REPORT_URIS = /* @__PURE__ */ new Map([
2565
2347
  ["snapshot://reports/audit", { file: "audit.md", title: "Secret audit and risk findings" }],
@@ -2571,18 +2353,6 @@ function formatBytes2(bytes) {
2571
2353
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} kB`;
2572
2354
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
2573
2355
  }
2574
- function truncationMarker(originalBytes) {
2575
- return `
2576
-
2577
- [truncated: ${formatBytes2(originalBytes)} total. Use the snapshot_read tool for a line window.]
2578
- `;
2579
- }
2580
- function capUtf8(text, limit) {
2581
- const size = Buffer.byteLength(text, "utf8");
2582
- if (size <= limit) return { text, truncated: false };
2583
- const cut = Buffer.from(text, "utf8").subarray(0, limit).toString("utf8").replace(/\uFFFD+$/, "");
2584
- return { text: `${cut}${truncationMarker(size)}`, truncated: true };
2585
- }
2586
2356
  async function workspaceFor(context) {
2587
2357
  const root = resolveRoot(void 0, context);
2588
2358
  if (!root.ok) return { error: root.message };
@@ -2605,7 +2375,7 @@ function buildResourceProvider() {
2605
2375
  uri: "snapshot://manifest",
2606
2376
  name: "manifest",
2607
2377
  title: "Snapshot manifest",
2608
- description: "Every file in the snapshot with its layer, kind, language, part and hash, plus the reason each excluded file was excluded.",
2378
+ description: "Every file in the snapshot with its layer, kind, language, part and hash, plus the reason each excluded file was excluded. A manifest larger than 512 kB is refused with its size instead of truncated: cut JSON does not parse. Use snapshot_locate, snapshot_read and snapshot_status for a large repository.",
2609
2379
  mimeType: "application/json"
2610
2380
  },
2611
2381
  {
@@ -2628,7 +2398,7 @@ function buildResourceProvider() {
2628
2398
  uri,
2629
2399
  name: report.file.replace(/\.md$/, ""),
2630
2400
  title: report.title,
2631
- description: `${report.title} from the most recent snapshot.`,
2401
+ description: `${report.title} from the most recent snapshot. A report larger than 512 kB is refused rather than truncated; read the file from the snapshot directory.`,
2632
2402
  mimeType: "text/markdown"
2633
2403
  });
2634
2404
  }
@@ -2637,11 +2407,12 @@ function buildResourceProvider() {
2637
2407
  const read = readManifest(workspace);
2638
2408
  if (!read.ok) return resources;
2639
2409
  for (const part of read.manifest.parts) {
2410
+ const readable = part.byteSize <= MAX_RESOURCE_BYTES;
2640
2411
  resources.push({
2641
2412
  uri: `snapshot://parts/${part.index}`,
2642
2413
  name: `part-${String(part.index).padStart(3, "0")}`,
2643
2414
  title: `Part ${part.index} (${part.fileCount} files, ${formatBytes2(part.byteSize)})`,
2644
- description: `Part ${part.index} of ${read.manifest.parts.length}: ${part.fileCount} file(s), ${part.lines} line(s), ${formatBytes2(part.byteSize)}.`,
2415
+ description: `Part ${part.index} of ${read.manifest.parts.length}: ${part.fileCount} file(s), ${part.lines} line(s), ${formatBytes2(part.byteSize)}.` + (readable ? "" : ` Above the ${formatBytes2(MAX_RESOURCE_BYTES)} single-read limit, so this resource is refused rather than truncated; use snapshot_locate and snapshot_read.`),
2645
2416
  mimeType: "text/markdown"
2646
2417
  });
2647
2418
  }
@@ -2661,42 +2432,444 @@ function buildResourceProvider() {
2661
2432
  async read(uri, context) {
2662
2433
  if (uri === "snapshot://contract") {
2663
2434
  const contract = buildAgentContract();
2664
- return { uri, mimeType: "application/json", text: JSON.stringify(contract, null, 2) };
2435
+ return {
2436
+ uri,
2437
+ mimeType: "application/json",
2438
+ text: ensureSingleRead(
2439
+ uri,
2440
+ JSON.stringify(contract, null, 2),
2441
+ "Run 'codebase-snapshot describe --format json' for the complete contract."
2442
+ )
2443
+ };
2665
2444
  }
2666
2445
  if (uri === "snapshot://skill") {
2667
- return { uri, mimeType: "text/markdown", text: renderSkill() };
2446
+ return {
2447
+ uri,
2448
+ mimeType: "text/markdown",
2449
+ text: ensureSingleRead(
2450
+ uri,
2451
+ renderSkill(),
2452
+ "Print it with 'codebase-snapshot skill'."
2453
+ )
2454
+ };
2455
+ }
2456
+ const workspace = await workspaceFor(context);
2457
+ if ("error" in workspace) return null;
2458
+ const report = REPORT_URIS.get(uri);
2459
+ if (report) {
2460
+ const text = readFileIfPresent(
2461
+ path.resolve(workspace.root, workspace.config.outDir, "reports", report.file)
2462
+ );
2463
+ if (text === null) return null;
2464
+ return { uri, mimeType: "text/markdown", text: ensureSingleRead(uri, text, REPORT_ADVICE) };
2465
+ }
2466
+ if (uri === "snapshot://manifest") {
2467
+ const read = readManifest(workspace);
2468
+ if (!read.ok) return null;
2469
+ const text = readFileIfPresent(read.file) ?? JSON.stringify(read.manifest, null, 2);
2470
+ return { uri, mimeType: "application/json", text: ensureSingleRead(uri, text, MANIFEST_ADVICE) };
2471
+ }
2472
+ const partMatch = PART_URI.exec(uri);
2473
+ if (partMatch) {
2474
+ const read = readManifest(workspace);
2475
+ if (!read.ok) return null;
2476
+ const index = Number(partMatch[1]);
2477
+ const part = read.manifest.parts.find((candidate) => candidate.index === index);
2478
+ if (!part) return null;
2479
+ const partPath = partPathFor(workspace, part.filename);
2480
+ if (partPath === null) return null;
2481
+ let partBytes;
2482
+ try {
2483
+ partBytes = fs.statSync(partPath).size;
2484
+ } catch {
2485
+ return null;
2486
+ }
2487
+ if (partBytes > MAX_RESOURCE_BYTES) refuseTooLarge(uri, partBytes, PART_ADVICE);
2488
+ const text = readFileIfPresent(partPath);
2489
+ if (text === null) return null;
2490
+ return { uri, mimeType: "text/markdown", text: ensureSingleRead(uri, text, PART_ADVICE) };
2491
+ }
2492
+ return null;
2493
+ }
2494
+ };
2495
+ }
2496
+
2497
+ // src/mcp/schema.ts
2498
+ function validateArguments(schema, value) {
2499
+ if (value === void 0) value = {};
2500
+ if (!isJsonObject(value)) return ["arguments must be a JSON object"];
2501
+ const problems = [];
2502
+ const known = new Set(Object.keys(schema.properties));
2503
+ for (const key of Object.keys(value)) {
2504
+ if (!known.has(key) && schema.additionalProperties !== true) {
2505
+ const allowed = [...known].sort().join(", ");
2506
+ problems.push(`unknown argument "${key}" (accepted: ${allowed || "none"})`);
2507
+ }
2508
+ }
2509
+ for (const required of schema.required ?? []) {
2510
+ if (value[required] === void 0) problems.push(`missing required argument "${required}"`);
2511
+ }
2512
+ for (const [key, propertySchema] of Object.entries(schema.properties)) {
2513
+ const argument = value[key];
2514
+ if (argument === void 0) continue;
2515
+ problems.push(...checkValue(key, propertySchema, argument));
2516
+ }
2517
+ return problems;
2518
+ }
2519
+ function checkValue(path4, schema, value) {
2520
+ if (schema.enum && !schema.enum.includes(value)) {
2521
+ return [`"${path4}" must be one of: ${schema.enum.join(", ")}`];
2522
+ }
2523
+ switch (schema.type) {
2524
+ case "string": {
2525
+ if (typeof value !== "string") return [`"${path4}" must be a string`];
2526
+ const problems = [];
2527
+ if (schema.minLength !== void 0 && value.length < schema.minLength) {
2528
+ problems.push(`"${path4}" must be at least ${schema.minLength} character(s)`);
2529
+ }
2530
+ if (schema.maxLength !== void 0 && value.length > schema.maxLength) {
2531
+ problems.push(`"${path4}" must be at most ${schema.maxLength} character(s)`);
2532
+ }
2533
+ return problems;
2534
+ }
2535
+ case "number":
2536
+ case "integer": {
2537
+ if (typeof value !== "number" || Number.isNaN(value)) {
2538
+ return [`"${path4}" must be a number`];
2539
+ }
2540
+ if (schema.type === "integer" && !Number.isInteger(value)) {
2541
+ return [`"${path4}" must be an integer`];
2542
+ }
2543
+ const problems = [];
2544
+ if (schema.minimum !== void 0 && value < schema.minimum) {
2545
+ problems.push(`"${path4}" must be >= ${schema.minimum}`);
2546
+ }
2547
+ if (schema.maximum !== void 0 && value > schema.maximum) {
2548
+ problems.push(`"${path4}" must be <= ${schema.maximum}`);
2549
+ }
2550
+ return problems;
2551
+ }
2552
+ case "boolean":
2553
+ return typeof value === "boolean" ? [] : [`"${path4}" must be a boolean`];
2554
+ case "array": {
2555
+ if (!Array.isArray(value)) return [`"${path4}" must be an array`];
2556
+ if (!schema.items) return [];
2557
+ const problems = [];
2558
+ value.forEach((item, index) => {
2559
+ problems.push(...checkValue(`${path4}[${index}]`, schema.items, item));
2560
+ });
2561
+ return problems;
2562
+ }
2563
+ case "object":
2564
+ return isJsonObject(value) ? [] : [`"${path4}" must be an object`];
2565
+ default:
2566
+ return [];
2567
+ }
2568
+ }
2569
+ function applyDefaults(schema, value) {
2570
+ const out = { ...value };
2571
+ for (const [key, propertySchema] of Object.entries(schema.properties)) {
2572
+ if (out[key] === void 0 && propertySchema.default !== void 0) {
2573
+ out[key] = propertySchema.default;
2574
+ }
2575
+ }
2576
+ return out;
2577
+ }
2578
+ function coerceNumericStrings(schema, value) {
2579
+ const out = { ...value };
2580
+ for (const [key, propertySchema] of Object.entries(schema.properties)) {
2581
+ const raw = out[key];
2582
+ if (typeof raw !== "string") continue;
2583
+ if (propertySchema.type !== "number" && propertySchema.type !== "integer") continue;
2584
+ if (raw.trim().length === 0) continue;
2585
+ const parsed = Number(raw);
2586
+ if (Number.isFinite(parsed)) out[key] = parsed;
2587
+ }
2588
+ return out;
2589
+ }
2590
+
2591
+ // src/mcp/server.ts
2592
+ function capabilities() {
2593
+ return {
2594
+ tools: { listChanged: false },
2595
+ resources: { subscribe: false, listChanged: false },
2596
+ prompts: { listChanged: false }
2597
+ };
2598
+ }
2599
+ function requestIdOf(message) {
2600
+ const raw = message.id;
2601
+ return typeof raw === "string" || typeof raw === "number" ? raw : null;
2602
+ }
2603
+ function createMcpServer(options) {
2604
+ const session = createSession();
2605
+ const toolsByName = new Map(options.tools.map((tool) => [tool.name, tool]));
2606
+ const promptsByName = new Map(options.prompts.map((prompt) => [prompt.name, prompt]));
2607
+ const identity = () => ({
2608
+ name: options.info.name,
2609
+ title: options.info.title,
2610
+ version: options.info.version,
2611
+ websiteUrl: options.info.websiteUrl
2612
+ });
2613
+ const ok = (id, result, modern) => successResponse(id, result, modern, options.info);
2614
+ function handleNotification(method) {
2615
+ if (method === METHOD.initialized && session.era === "legacy") session.ready = true;
2616
+ }
2617
+ function initialize(id, params) {
2618
+ const negotiation = negotiateLegacyVersion(params?.protocolVersion);
2619
+ session.era = "legacy";
2620
+ session.protocolVersion = negotiation.version;
2621
+ session.ready = true;
2622
+ options.context.log(
2623
+ negotiation.matched ? `mcp: client initialized with protocol ${negotiation.version}` : `mcp: client asked for an unsupported version and was offered ${negotiation.version}`
2624
+ );
2625
+ return {
2626
+ jsonrpc: "2.0",
2627
+ id,
2628
+ result: {
2629
+ protocolVersion: negotiation.version,
2630
+ capabilities: capabilities(),
2631
+ serverInfo: identity(),
2632
+ instructions: options.instructions
2668
2633
  }
2669
- const workspace = await workspaceFor(context);
2670
- if ("error" in workspace) return null;
2671
- const report = REPORT_URIS.get(uri);
2672
- if (report) {
2673
- const text = readFileIfPresent(
2674
- path2.resolve(workspace.root, workspace.config.outDir, "reports", report.file)
2634
+ };
2635
+ }
2636
+ function discover(id) {
2637
+ session.era = "modern";
2638
+ session.ready = true;
2639
+ return ok(
2640
+ id,
2641
+ {
2642
+ supportedVersions: [...SUPPORTED_PROTOCOL_VERSIONS],
2643
+ capabilities: capabilities(),
2644
+ instructions: options.instructions,
2645
+ // The capability set depends on which repository the server was started for, so the answer
2646
+ // may be cached only by the client that asked, and not at all after this response.
2647
+ cacheScope: "private",
2648
+ ttlMs: 0
2649
+ },
2650
+ true
2651
+ );
2652
+ }
2653
+ function listTools(id, modern) {
2654
+ const tools = options.tools.map((tool) => ({
2655
+ name: tool.name,
2656
+ title: tool.title,
2657
+ description: tool.description,
2658
+ inputSchema: tool.inputSchema,
2659
+ ...tool.outputSchema ? { outputSchema: tool.outputSchema } : {},
2660
+ annotations: tool.annotations
2661
+ }));
2662
+ return ok(id, { tools }, modern);
2663
+ }
2664
+ async function callTool(id, modern, params) {
2665
+ const name = params?.name;
2666
+ if (typeof name !== "string") {
2667
+ return errorResponse(id, ERROR_CODES.invalidParams, 'tools/call requires a "name" string.');
2668
+ }
2669
+ const tool = toolsByName.get(name);
2670
+ if (!tool) {
2671
+ const known = [...toolsByName.keys()].sort().join(", ");
2672
+ return errorResponse(id, ERROR_CODES.invalidParams, `Unknown tool "${name}". Available: ${known}.`);
2673
+ }
2674
+ const rawArguments = params?.arguments ?? {};
2675
+ if (!isJsonObject(rawArguments)) {
2676
+ return errorResponse(id, ERROR_CODES.invalidParams, '"arguments" must be a JSON object.');
2677
+ }
2678
+ const supplied = coerceNumericStrings(tool.inputSchema, rawArguments);
2679
+ const problems = validateArguments(tool.inputSchema, supplied);
2680
+ if (problems.length > 0) {
2681
+ return ok(
2682
+ id,
2683
+ {
2684
+ content: [{ type: "text", text: `Invalid arguments for ${tool.name}:
2685
+ - ${problems.join("\n- ")}` }],
2686
+ isError: true
2687
+ },
2688
+ modern
2689
+ );
2690
+ }
2691
+ const args = applyDefaults(tool.inputSchema, supplied);
2692
+ let outcome;
2693
+ try {
2694
+ outcome = await tool.handler(args, options.context);
2695
+ } catch (error) {
2696
+ const detail = error instanceof Error ? error.message : String(error);
2697
+ options.context.log(`mcp: tool ${tool.name} failed: ${detail}`);
2698
+ return ok(
2699
+ id,
2700
+ { content: [{ type: "text", text: `${tool.name} failed: ${detail}` }], isError: true },
2701
+ modern
2702
+ );
2703
+ }
2704
+ return ok(
2705
+ id,
2706
+ {
2707
+ content: [{ type: "text", text: outcome.text }],
2708
+ ...outcome.structured ? { structuredContent: outcome.structured } : {},
2709
+ ...outcome.isError ? { isError: true } : {}
2710
+ },
2711
+ modern
2712
+ );
2713
+ }
2714
+ async function listResources(id, modern) {
2715
+ const resources = await options.resources.list(options.context);
2716
+ return ok(id, { resources }, modern);
2717
+ }
2718
+ async function readResource(id, modern, params) {
2719
+ const uri = params?.uri;
2720
+ if (typeof uri !== "string") {
2721
+ return errorResponse(id, ERROR_CODES.invalidParams, 'resources/read requires a "uri" string.');
2722
+ }
2723
+ let contents;
2724
+ try {
2725
+ contents = await options.resources.read(uri, options.context);
2726
+ } catch (error) {
2727
+ if (error instanceof ResourceTooLargeError) {
2728
+ options.context.log(
2729
+ `mcp: refused ${error.uri} (${error.bytes} bytes, limit ${error.limit}); returning it would truncate it`
2675
2730
  );
2676
- if (text === null) return null;
2677
- return { uri, mimeType: "text/markdown", text: capUtf8(text, MAX_RESOURCE_BYTES).text };
2678
- }
2679
- if (uri === "snapshot://manifest") {
2680
- const read = readManifest(workspace);
2681
- if (!read.ok) return null;
2682
- const text = readFileIfPresent(read.file) ?? JSON.stringify(read.manifest, null, 2);
2683
- return { uri, mimeType: "application/json", text: capUtf8(text, MAX_RESOURCE_BYTES).text };
2731
+ return errorResponse(id, ERROR_CODES.resourceTooLarge, error.message, {
2732
+ uri: error.uri,
2733
+ bytes: error.bytes,
2734
+ limit: error.limit
2735
+ });
2684
2736
  }
2685
- const partMatch = PART_URI.exec(uri);
2686
- if (partMatch) {
2687
- const read = readManifest(workspace);
2688
- if (!read.ok) return null;
2689
- const index = Number(partMatch[1]);
2690
- const part = read.manifest.parts.find((candidate) => candidate.index === index);
2691
- if (!part) return null;
2692
- const text = readFileIfPresent(
2693
- path2.resolve(workspace.root, workspace.config.outDir, "parts", part.filename)
2694
- );
2695
- if (text === null) return null;
2696
- return { uri, mimeType: "text/markdown", text: capUtf8(text, MAX_RESOURCE_BYTES).text };
2737
+ throw error;
2738
+ }
2739
+ if (!contents) {
2740
+ return errorResponse(id, ERROR_CODES.invalidParams, `Unknown resource "${uri}".`);
2741
+ }
2742
+ return ok(id, { contents: [contents] }, modern);
2743
+ }
2744
+ function listPrompts(id, modern) {
2745
+ const prompts = options.prompts.map((prompt) => ({
2746
+ name: prompt.name,
2747
+ ...prompt.title ? { title: prompt.title } : {},
2748
+ description: prompt.description,
2749
+ arguments: prompt.arguments
2750
+ }));
2751
+ return ok(id, { prompts }, modern);
2752
+ }
2753
+ function getPrompt(id, modern, params) {
2754
+ const name = params?.name;
2755
+ if (typeof name !== "string") {
2756
+ return errorResponse(id, ERROR_CODES.invalidParams, 'prompts/get requires a "name" string.');
2757
+ }
2758
+ const prompt = promptsByName.get(name);
2759
+ if (!prompt) {
2760
+ const known = [...promptsByName.keys()].sort().join(", ");
2761
+ return errorResponse(id, ERROR_CODES.invalidParams, `Unknown prompt "${name}". Available: ${known}.`);
2762
+ }
2763
+ const rawArguments = params?.arguments ?? {};
2764
+ if (!isJsonObject(rawArguments)) {
2765
+ return errorResponse(id, ERROR_CODES.invalidParams, '"arguments" must be a JSON object.');
2766
+ }
2767
+ const built = prompt.build(rawArguments);
2768
+ const messages = built.messages.map((message) => ({
2769
+ role: message.role,
2770
+ content: { type: "text", text: message.content.text }
2771
+ }));
2772
+ return ok(id, { description: built.description, messages }, modern);
2773
+ }
2774
+ async function route(name, id, modern, params) {
2775
+ switch (name) {
2776
+ case METHOD.initialize:
2777
+ return modern ? errorResponse(
2778
+ id,
2779
+ ERROR_CODES.methodNotFound,
2780
+ '"initialize" does not exist in this protocol revision; call "server/discover".'
2781
+ ) : initialize(id, params);
2782
+ case METHOD.discover:
2783
+ return discover(id);
2784
+ case METHOD.ping:
2785
+ return modern ? errorResponse(
2786
+ id,
2787
+ ERROR_CODES.methodNotFound,
2788
+ '"ping" was removed in this protocol revision; call "server/discover".'
2789
+ ) : ok(id, {}, modern);
2790
+ }
2791
+ if (!session.ready) {
2792
+ return errorResponse(
2793
+ id,
2794
+ ERROR_CODES.invalidRequest,
2795
+ 'This connection has not been initialized. Send "initialize" first.'
2796
+ );
2797
+ }
2798
+ switch (name) {
2799
+ case METHOD.toolsList:
2800
+ return listTools(id, modern);
2801
+ case METHOD.toolsCall:
2802
+ return callTool(id, modern, params);
2803
+ case METHOD.resourcesList:
2804
+ return listResources(id, modern);
2805
+ case METHOD.resourcesRead:
2806
+ return readResource(id, modern, params);
2807
+ case METHOD.resourceTemplatesList:
2808
+ return ok(id, { resourceTemplates: options.resources.templates() }, modern);
2809
+ case METHOD.promptsList:
2810
+ return listPrompts(id, modern);
2811
+ case METHOD.promptsGet:
2812
+ return getPrompt(id, modern, params);
2813
+ default:
2814
+ return errorResponse(id, ERROR_CODES.methodNotFound, `Unknown method "${name}".`);
2815
+ }
2816
+ }
2817
+ async function dispatch(message) {
2818
+ if (!isJsonObject(message)) {
2819
+ return errorResponse(
2820
+ null,
2821
+ ERROR_CODES.invalidRequest,
2822
+ Array.isArray(message) ? "Batch requests are not supported: send one JSON-RPC message per line." : "Message is not a JSON object."
2823
+ );
2824
+ }
2825
+ const isRequest = Object.prototype.hasOwnProperty.call(message, "id");
2826
+ const method = message.method;
2827
+ const params = message.params;
2828
+ if (message.jsonrpc !== "2.0" && isRequest) {
2829
+ return errorResponse(requestIdOf(message), ERROR_CODES.invalidRequest, 'Message must carry "jsonrpc": "2.0".');
2830
+ }
2831
+ if (typeof method !== "string" || method.length === 0) {
2832
+ return isRequest ? errorResponse(requestIdOf(message), ERROR_CODES.invalidRequest, 'Message must carry a "method" string.') : null;
2833
+ }
2834
+ if (params !== void 0 && !isJsonObject(params)) {
2835
+ return isRequest ? errorResponse(requestIdOf(message), ERROR_CODES.invalidRequest, '"params" must be a JSON object when present.') : null;
2836
+ }
2837
+ const named = params;
2838
+ const decision = classifyRequest(method, named, session);
2839
+ const modern = decision.kind === "era" ? decision.era === "modern" : session.era === "modern";
2840
+ if (!isRequest) {
2841
+ if (decision.kind === "era" && session.era === null) {
2842
+ session.era = decision.era;
2843
+ session.protocolVersion = decision.version;
2697
2844
  }
2845
+ handleNotification(method);
2698
2846
  return null;
2699
2847
  }
2848
+ const id = requestIdOf(message);
2849
+ if (id === null) {
2850
+ return errorResponse(null, ERROR_CODES.invalidRequest, 'A request "id" must be a string or a number.');
2851
+ }
2852
+ if (decision.kind === "error") {
2853
+ return errorResponse(id, decision.code, decision.message, decision.data);
2854
+ }
2855
+ if (session.era === null) {
2856
+ session.era = decision.era;
2857
+ session.protocolVersion = decision.version;
2858
+ }
2859
+ return route(method, id, modern, named);
2860
+ }
2861
+ return {
2862
+ session,
2863
+ async handle(message) {
2864
+ try {
2865
+ return await dispatch(message);
2866
+ } catch (error) {
2867
+ const detail = error instanceof Error ? error.message : String(error);
2868
+ options.context.log(`mcp: internal error: ${detail}`);
2869
+ const id = isJsonObject(message) ? requestIdOf(message) : null;
2870
+ return errorResponse(id, ERROR_CODES.internalError, "Internal server error.");
2871
+ }
2872
+ }
2700
2873
  };
2701
2874
  }
2702
2875
 
@@ -2735,6 +2908,7 @@ function createWriter(output) {
2735
2908
  }
2736
2909
  function createLineReader(input, options) {
2737
2910
  let buffer = "";
2911
+ let bufferBytes = 0;
2738
2912
  let discarding = false;
2739
2913
  let discardedBytes = 0;
2740
2914
  const deliver = (line) => {
@@ -2747,6 +2921,13 @@ function createLineReader(input, options) {
2747
2921
  if (trimmed.trim().length === 0) return;
2748
2922
  options.onLine(trimmed);
2749
2923
  };
2924
+ const discardBuffered = () => {
2925
+ discarding = true;
2926
+ discardedBytes += bufferBytes;
2927
+ buffer = "";
2928
+ bufferBytes = 0;
2929
+ options.onOverflow?.(discardedBytes);
2930
+ };
2750
2931
  const drain = () => {
2751
2932
  let index = buffer.indexOf("\n");
2752
2933
  while (index >= 0) {
@@ -2754,42 +2935,57 @@ function createLineReader(input, options) {
2754
2935
  buffer = buffer.slice(index + 1);
2755
2936
  if (discarding) {
2756
2937
  deliver(line);
2757
- } else if (line.length > MAX_LINE_BYTES) {
2758
- options.onOverflow?.(line.length);
2759
2938
  } else {
2760
- deliver(line);
2939
+ const lineBytes = Buffer.byteLength(line, "utf8");
2940
+ if (lineBytes > MAX_LINE_BYTES) options.onOverflow?.(lineBytes);
2941
+ else deliver(line);
2761
2942
  }
2762
2943
  index = buffer.indexOf("\n");
2763
2944
  }
2945
+ bufferBytes = Buffer.byteLength(buffer, "utf8");
2946
+ if (!discarding && bufferBytes > MAX_LINE_BYTES) discardBuffered();
2764
2947
  };
2765
2948
  const onData = (chunk) => {
2949
+ const chunkBytes = Buffer.byteLength(chunk, "utf8");
2766
2950
  if (discarding) {
2767
2951
  const index = chunk.indexOf("\n");
2768
2952
  if (index < 0) {
2769
- discardedBytes += chunk.length;
2953
+ discardedBytes += chunkBytes;
2770
2954
  return;
2771
2955
  }
2772
2956
  buffer = chunk.slice(index + 1);
2957
+ bufferBytes = Buffer.byteLength(buffer, "utf8");
2773
2958
  deliver("");
2774
2959
  drain();
2775
2960
  return;
2776
2961
  }
2777
- buffer += chunk;
2778
- drain();
2779
- if (buffer.length > MAX_LINE_BYTES) {
2962
+ if (chunk.indexOf("\n") < 0 && bufferBytes + chunkBytes > MAX_LINE_BYTES) {
2780
2963
  discarding = true;
2781
- discardedBytes = buffer.length;
2964
+ discardedBytes = bufferBytes + chunkBytes;
2782
2965
  buffer = "";
2966
+ bufferBytes = 0;
2783
2967
  options.onOverflow?.(discardedBytes);
2784
2968
  return;
2785
2969
  }
2970
+ buffer += chunk;
2971
+ drain();
2786
2972
  };
2787
2973
  const onEnd = () => {
2788
- if (buffer.length > 0) {
2789
- const rest = buffer;
2790
- buffer = "";
2791
- deliver(rest);
2974
+ const rest = buffer;
2975
+ const restBytes = bufferBytes || Buffer.byteLength(rest, "utf8");
2976
+ buffer = "";
2977
+ bufferBytes = 0;
2978
+ if (rest.length === 0) return;
2979
+ if (discarding) {
2980
+ discarding = false;
2981
+ discardedBytes = 0;
2982
+ return;
2983
+ }
2984
+ if (restBytes > MAX_LINE_BYTES) {
2985
+ options.onOverflow?.(restBytes);
2986
+ return;
2792
2987
  }
2988
+ deliver(rest);
2793
2989
  };
2794
2990
  input.setEncoding("utf8");
2795
2991
  input.on("data", onData);