codebase-snapshot 0.9.14 → 0.9.16

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,4 +1,4 @@
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-DUZK5VL2.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-6TRFLA7N.js';
2
2
  import * as fs from 'fs';
3
3
  import * as path from 'path';
4
4
 
@@ -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,557 +167,226 @@ 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;
170
+ // src/mcp/part.ts
171
+ var FILE_HEADING = "### FILE: ";
172
+ var CONTENT_MARKERS = /* @__PURE__ */ new Set(["#### Content", "#### Bounded Preview"]);
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: ";
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]);
181
184
  }
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;
185
+ function parsePartSections(partText) {
186
+ const lines = partText.split("\n");
187
+ const sections = [];
188
+ let index = 0;
189
+ while (index < lines.length) {
190
+ if (!lines[index].startsWith(FILE_HEADING)) {
191
+ index += 1;
192
+ continue;
197
193
  }
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}`);
194
+ const heading = lines[index].slice(FILE_HEADING.length);
195
+ const anchorMatch = index > 0 ? ANCHOR_LINE.exec(lines[index - 1]) : null;
196
+ let cursor = index + 1;
197
+ let inclusion = null;
198
+ let includedLines = null;
199
+ while (cursor < lines.length && !CONTENT_MARKERS.has(lines[cursor])) {
200
+ const line = lines[cursor];
201
+ if (line.startsWith(FILE_HEADING)) break;
202
+ if (line.startsWith(META_PREFIX)) {
203
+ const fields = line.slice(META_PREFIX.length).split("|");
204
+ for (const field of fields) {
205
+ const value = field.trim();
206
+ if (INCLUSION_MODES.has(value)) inclusion = value;
207
+ }
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());
213
+ includedLines = Number.isFinite(value) ? value : null;
212
214
  }
213
- return problems;
215
+ cursor += 1;
214
216
  }
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;
217
+ if (cursor >= lines.length || !CONTENT_MARKERS.has(lines[cursor])) {
218
+ index = cursor + 1;
219
+ continue;
225
220
  }
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;
221
+ let fenceLine = cursor + 1;
222
+ while (fenceLine < lines.length && lines[fenceLine].trim().length === 0) fenceLine += 1;
223
+ const fenceMatch = /^(`{4,})/.exec(lines[fenceLine] ?? "");
224
+ if (!fenceMatch) {
225
+ index = cursor + 1;
226
+ continue;
227
+ }
228
+ const fence = fenceMatch[1];
229
+ const body = [];
230
+ let bodyLine = fenceLine + 1;
231
+ while (bodyLine < lines.length && lines[bodyLine] !== fence) {
232
+ body.push(lines[bodyLine]);
233
+ bodyLine += 1;
237
234
  }
235
+ sections.push({ path: heading, anchor: anchorMatch?.[1] ?? null, body: body.join("\n"), inclusion, includedLines });
236
+ index = bodyLine + 1;
238
237
  }
239
- return out;
238
+ return sections;
240
239
  }
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;
240
+ function findSection(sections, relativePath) {
241
+ const anchor = anchorForPath(relativePath);
242
+ const byAnchor = sections.find((section) => section.anchor === anchor);
243
+ if (byAnchor) return byAnchor;
244
+ const rendered = displayPath(relativePath);
245
+ const samePath = (section) => section.path === relativePath || section.path === rendered;
246
+ const exact = sections.find(samePath);
247
+ if (exact) return exact;
248
+ const foldedPath = rendered.toLowerCase();
249
+ const folded = sections.filter((section) => {
250
+ const path4 = section.path.toLowerCase();
251
+ return path4 === relativePath.toLowerCase() || path4 === foldedPath;
252
+ });
253
+ return folded.length === 1 ? folded[0] : null;
252
254
  }
253
-
254
- // src/mcp/server.ts
255
- function capabilities() {
255
+ function windowText(body, fromLine, lineCount) {
256
+ const lines = body.split("\n");
257
+ const total = body.length === 0 ? 0 : lines.length;
258
+ const requested = Math.max(1, Math.trunc(fromLine));
259
+ const pastEnd = total > 0 && requested > total;
260
+ const start = pastEnd ? requested : Math.min(requested, Math.max(1, total));
261
+ const end = Math.min(total, start + Math.max(1, Math.trunc(lineCount)) - 1);
262
+ const slice = pastEnd ? [] : lines.slice(start - 1, Math.max(start - 1, end));
256
263
  return {
257
- tools: { listChanged: false },
258
- resources: { subscribe: false, listChanged: false },
259
- prompts: { listChanged: false }
264
+ text: slice.join("\n"),
265
+ fromLine: start,
266
+ returnedLines: slice.length,
267
+ totalLines: total,
268
+ truncated: !pastEnd && end < total,
269
+ nextFromLine: !pastEnd && end < total ? end + 1 : null,
270
+ pastEnd
260
271
  };
261
272
  }
262
- function requestIdOf(message) {
263
- const raw = message.id;
264
- return typeof raw === "string" || typeof raw === "number" ? raw : null;
273
+ function foldForComparison(value) {
274
+ return process.platform === "win32" || process.platform === "darwin" ? value.toLowerCase() : value;
265
275
  }
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;
276
+ function canonicalPath(value) {
277
+ const absolute = path.resolve(value);
278
+ try {
279
+ return fs.realpathSync(absolute);
280
+ } catch {
281
+ return absolute;
279
282
  }
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
- };
283
+ }
284
+ function isInside(parent, child) {
285
+ const foldedParent = foldForComparison(parent);
286
+ const foldedChild = foldForComparison(child);
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;
298
297
  }
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
- );
298
+ const resolved = canonicalPath(existing);
299
+ return missing.length === 0 ? resolved : path.join(resolved, ...missing);
300
+ }
301
+ function resolveRoot(requested, context) {
302
+ if (requested !== void 0 && (typeof requested !== "string" || requested.trim().length === 0)) {
303
+ return { ok: false, message: '"root" must be a non-empty string when provided.' };
315
304
  }
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);
305
+ const wanted = typeof requested === "string" ? requested.trim() : context.cwd;
306
+ const absolute = path.resolve(context.cwd, wanted);
307
+ let stats;
308
+ try {
309
+ stats = fs.statSync(absolute);
310
+ } catch {
311
+ return { ok: false, message: `"${wanted}" does not exist, so it cannot be a repository root.` };
326
312
  }
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);
313
+ if (!stats.isDirectory()) {
314
+ return { ok: false, message: `"${wanted}" is not a directory.` };
380
315
  }
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);
316
+ const resolved = canonicalPath(absolute);
317
+ for (const allowed of context.roots) {
318
+ if (isInside(canonicalPath(allowed), resolved)) return { ok: true, root: resolved };
391
319
  }
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);
320
+ const shown = context.roots.join(", ");
321
+ return {
322
+ ok: false,
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.`
324
+ };
325
+ }
326
+ async function openWorkspace(root, overrides = {}, allowedRoots) {
327
+ const loaded = await loadConfigFileDetailed(root);
328
+ if (loaded.errors.length > 0) {
329
+ return {
330
+ ok: false,
331
+ message: `The config file could not be read: ${loaded.errors.join("; ")} Fix it, or delete it to use the defaults \u2014 this server will not silently ignore it.`
332
+ };
400
333
  }
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.');
334
+ const cliOptions = { cwd: root };
335
+ if (overrides.maxPartBytes !== void 0) {
336
+ const parsed = parseByteSize(overrides.maxPartBytes);
337
+ if (parsed === void 0) {
338
+ return {
339
+ ok: false,
340
+ message: '"maxPartBytes" must be a byte count, for example 307200 or "300k".'
341
+ };
414
342
  }
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);
343
+ cliOptions.maxPartBytes = parsed;
421
344
  }
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}".`);
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
+ };
463
352
  }
353
+ cliOptions.maxPartTokens = parsed;
464
354
  }
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);
355
+ if (overrides.outDir !== void 0) {
356
+ if (typeof overrides.outDir !== "string" || overrides.outDir.trim().length === 0) {
357
+ return { ok: false, message: '"outDir" must be a non-empty string.' };
498
358
  }
499
- if (session.era === null) {
500
- session.era = decision.era;
501
- session.protocolVersion = decision.version;
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
+ };
502
368
  }
503
- return route(method, id, modern, named);
369
+ cliOptions.outDir = requested;
504
370
  }
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
- }
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
+ };
516
377
  }
517
- };
518
- }
519
-
520
- // src/mcp/part.ts
521
- var FILE_HEADING = "### FILE: ";
522
- var CONTENT_MARKERS = /* @__PURE__ */ new Set(["#### Content", "#### Bounded Preview"]);
523
- var ANCHOR_LINE = /^<a id="([^"]+)"><\/a>$/;
524
- var INCLUSION_MODES = /* @__PURE__ */ new Set(["full", "preview", "signatures"]);
525
- function parsePartSections(partText) {
526
- const lines = partText.split("\n");
527
- const sections = [];
528
- let index = 0;
529
- while (index < lines.length) {
530
- if (!lines[index].startsWith(FILE_HEADING)) {
531
- index += 1;
532
- continue;
533
- }
534
- const heading = lines[index].slice(FILE_HEADING.length);
535
- const anchorMatch = index > 0 ? ANCHOR_LINE.exec(lines[index - 1]) : null;
536
- let cursor = index + 1;
537
- let inclusion = null;
538
- let includedLines = null;
539
- while (cursor < lines.length && !CONTENT_MARKERS.has(lines[cursor])) {
540
- const line = lines[cursor];
541
- if (line.startsWith(FILE_HEADING)) break;
542
- if (line.startsWith("- Meta: ")) {
543
- for (const field of line.slice("- Meta: ".length).split("|")) {
544
- const value = field.trim();
545
- if (INCLUSION_MODES.has(value)) inclusion = value;
546
- }
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());
556
- includedLines = Number.isFinite(value) ? value : null;
557
- }
558
- cursor += 1;
559
- }
560
- if (cursor >= lines.length || !CONTENT_MARKERS.has(lines[cursor])) {
561
- index = cursor + 1;
562
- continue;
563
- }
564
- let fenceLine = cursor + 1;
565
- while (fenceLine < lines.length && lines[fenceLine].trim().length === 0) fenceLine += 1;
566
- const fenceMatch = /^(`{4,})/.exec(lines[fenceLine] ?? "");
567
- if (!fenceMatch) {
568
- index = cursor + 1;
569
- continue;
570
- }
571
- const fence = fenceMatch[1];
572
- const body = [];
573
- let bodyLine = fenceLine + 1;
574
- while (bodyLine < lines.length && lines[bodyLine] !== fence) {
575
- body.push(lines[bodyLine]);
576
- bodyLine += 1;
577
- }
578
- sections.push({ path: heading, anchor: anchorMatch?.[1] ?? null, body: body.join("\n"), inclusion, includedLines });
579
- index = bodyLine + 1;
580
- }
581
- return sections;
582
- }
583
- function findSection(sections, relativePath) {
584
- const anchor = anchorForPath(relativePath);
585
- const byAnchor = sections.find((section) => section.anchor === anchor);
586
- if (byAnchor) return byAnchor;
587
- const rendered = displayPath(relativePath);
588
- const samePath = (section) => section.path === relativePath || section.path === rendered;
589
- const exact = sections.find(samePath);
590
- if (exact) return exact;
591
- const foldedPath = rendered.toLowerCase();
592
- const folded = sections.filter((section) => {
593
- const path4 = section.path.toLowerCase();
594
- return path4 === relativePath.toLowerCase() || path4 === foldedPath;
595
- });
596
- return folded.length === 1 ? folded[0] : null;
597
- }
598
- function windowText(body, fromLine, lineCount) {
599
- const lines = body.split("\n");
600
- const total = body.length === 0 ? 0 : lines.length;
601
- const requested = Math.max(1, Math.trunc(fromLine));
602
- const pastEnd = total > 0 && requested > total;
603
- const start = pastEnd ? requested : Math.min(requested, Math.max(1, total));
604
- const end = Math.min(total, start + Math.max(1, Math.trunc(lineCount)) - 1);
605
- const slice = pastEnd ? [] : lines.slice(start - 1, Math.max(start - 1, end));
606
- return {
607
- text: slice.join("\n"),
608
- fromLine: start,
609
- returnedLines: slice.length,
610
- totalLines: total,
611
- truncated: !pastEnd && end < total,
612
- nextFromLine: !pastEnd && end < total ? end + 1 : null,
613
- pastEnd
614
- };
615
- }
616
- function foldForComparison(value) {
617
- return process.platform === "win32" || process.platform === "darwin" ? value.toLowerCase() : value;
618
- }
619
- function canonicalPath(value) {
620
- const absolute = path.resolve(value);
621
- try {
622
- return fs.realpathSync(absolute);
623
- } catch {
624
- return absolute;
625
- }
626
- }
627
- function isInside(parent, child) {
628
- const foldedParent = foldForComparison(parent);
629
- const foldedChild = foldForComparison(child);
630
- return foldedChild === foldedParent || foldedChild.startsWith(`${foldedParent}${path.sep}`);
631
- }
632
- function resolveRoot(requested, context) {
633
- if (requested !== void 0 && (typeof requested !== "string" || requested.trim().length === 0)) {
634
- return { ok: false, message: '"root" must be a non-empty string when provided.' };
635
- }
636
- const wanted = typeof requested === "string" ? requested.trim() : context.cwd;
637
- const absolute = path.resolve(context.cwd, wanted);
638
- let stats;
639
- try {
640
- stats = fs.statSync(absolute);
641
- } catch {
642
- return { ok: false, message: `"${wanted}" does not exist, so it cannot be a repository root.` };
643
- }
644
- if (!stats.isDirectory()) {
645
- return { ok: false, message: `"${wanted}" is not a directory.` };
646
- }
647
- const resolved = canonicalPath(absolute);
648
- for (const allowed of context.roots) {
649
- if (isInside(canonicalPath(allowed), resolved)) return { ok: true, root: resolved };
650
- }
651
- const shown = context.roots.join(", ");
652
- return {
653
- ok: false,
654
- message: `"${wanted}" resolves outside the directories this server may read (${shown}). Restart it with --root <path> to add a repository.`
655
- };
656
- }
657
- async function openWorkspace(root, overrides = {}) {
658
- const loaded = await loadConfigFileDetailed(root);
659
- if (loaded.errors.length > 0) {
660
- return {
661
- ok: false,
662
- message: `The config file could not be read: ${loaded.errors.join("; ")} Fix it, or delete it to use the defaults \u2014 this server will not silently ignore it.`
663
- };
664
- }
665
- const cliOptions = { cwd: root };
666
- if (overrides.maxPartBytes !== void 0) {
667
- const parsed = parseByteSize(overrides.maxPartBytes);
668
- if (parsed === void 0) {
669
- return {
670
- ok: false,
671
- message: '"maxPartBytes" must be a byte count, for example 307200 or "300k".'
672
- };
673
- }
674
- cliOptions.maxPartBytes = parsed;
675
- }
676
- if (overrides.maxPartTokens !== void 0) {
677
- const parsed = parseByteSize(overrides.maxPartTokens);
678
- if (parsed === void 0) {
679
- return {
680
- ok: false,
681
- message: '"maxPartTokens" must be a token count, for example 32000 or "32k".'
682
- };
683
- }
684
- cliOptions.maxPartTokens = parsed;
685
- }
686
- if (overrides.outDir !== void 0) {
687
- if (typeof overrides.outDir !== "string" || overrides.outDir.trim().length === 0) {
688
- return { ok: false, message: '"outDir" must be a non-empty string.' };
689
- }
690
- cliOptions.outDir = overrides.outDir.trim();
691
- }
692
- if (overrides.changedSince !== void 0) {
693
- if (typeof overrides.changedSince !== "string" || overrides.changedSince.trim().length === 0) {
694
- return {
695
- ok: false,
696
- message: '"changedSince" must be a git ref such as "main" or "HEAD~3".'
697
- };
698
- }
699
- cliOptions.changedSince = overrides.changedSince.trim();
700
- }
701
- if (overrides.skeleton === true) cliOptions.skeleton = true;
702
- if (overrides.sarif === true) cliOptions.sarif = true;
703
- if (overrides.staged === true) cliOptions.staged = true;
704
- if (overrides.withDependents === true) cliOptions.withDependents = true;
705
- try {
706
- const config = resolveConfig(loaded.config, cliOptions, root);
707
- return { ok: true, workspace: { root, config, configFile: loaded.file, cliOptions } };
708
- } catch (error) {
709
- return { ok: false, message: error instanceof Error ? error.message : String(error) };
710
- }
378
+ cliOptions.changedSince = overrides.changedSince.trim();
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;
384
+ try {
385
+ const config = resolveConfig(loaded.config, cliOptions, root);
386
+ return { ok: true, workspace: { root, config, configFile: loaded.file, cliOptions } };
387
+ } catch (error) {
388
+ return { ok: false, message: error instanceof Error ? error.message : String(error) };
389
+ }
711
390
  }
712
391
  var manifestCache = /* @__PURE__ */ new Map();
713
392
  function manifestPathFor(workspace) {
@@ -790,7 +469,7 @@ var ROOT_PROPERTY = {
790
469
  };
791
470
  var OUT_DIR_PROPERTY = {
792
471
  type: "string",
793
- 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."
794
473
  };
795
474
  var outDirOverride = (args) => ({ outDir: args.outDir });
796
475
  var SCOPE_PROPERTIES = {
@@ -909,7 +588,7 @@ function symbolsOf(entry) {
909
588
  async function prepare(args, context, overrides = {}) {
910
589
  const rootOutcome = resolveRoot(args.root, context);
911
590
  if (!rootOutcome.ok) return { ok: false, outcome: failure(rootOutcome.message) };
912
- const opened = await openWorkspace(rootOutcome.root, overrides);
591
+ const opened = await openWorkspace(rootOutcome.root, overrides, context.roots);
913
592
  if (!opened.ok) return { ok: false, outcome: failure(opened.message) };
914
593
  return { ok: true, workspace: opened.workspace };
915
594
  }
@@ -1758,16 +1437,14 @@ var COMMAND_OPTION_SCOPE = {
1758
1437
  "version"
1759
1438
  ],
1760
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.
1761
1445
  report: [
1762
1446
  "cwd",
1763
1447
  "out-dir",
1764
- "max-part-bytes",
1765
- "large-file-bytes",
1766
- "max-monolith-bytes",
1767
- "include-monolith",
1768
- "include-sensitive-files",
1769
- "skip-artifacts",
1770
- "only-artifacts",
1771
1448
  "no-config",
1772
1449
  "no-update-check",
1773
1450
  "format",
@@ -2238,7 +1915,7 @@ function buildAgentContract() {
2238
1915
  type: "string",
2239
1916
  default: "generate",
2240
1917
  appliesTo: optionAppliesTo("mode"),
2241
- 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)."
2242
1919
  },
2243
1920
  {
2244
1921
  flag: "--cwd",
@@ -2637,6 +2314,34 @@ from an earlier session.
2637
2314
 
2638
2315
  // src/mcp/resources.ts
2639
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.";
2640
2345
  var PART_URI = /^snapshot:\/\/parts\/(\d+)$/;
2641
2346
  var REPORT_URIS = /* @__PURE__ */ new Map([
2642
2347
  ["snapshot://reports/audit", { file: "audit.md", title: "Secret audit and risk findings" }],
@@ -2648,18 +2353,6 @@ function formatBytes2(bytes) {
2648
2353
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} kB`;
2649
2354
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
2650
2355
  }
2651
- function truncationMarker(originalBytes) {
2652
- return `
2653
-
2654
- [truncated: ${formatBytes2(originalBytes)} total. Use the snapshot_read tool for a line window.]
2655
- `;
2656
- }
2657
- function capUtf8(text, limit) {
2658
- const size = Buffer.byteLength(text, "utf8");
2659
- if (size <= limit) return { text, truncated: false };
2660
- const cut = Buffer.from(text, "utf8").subarray(0, limit).toString("utf8").replace(/\uFFFD+$/, "");
2661
- return { text: `${cut}${truncationMarker(size)}`, truncated: true };
2662
- }
2663
2356
  async function workspaceFor(context) {
2664
2357
  const root = resolveRoot(void 0, context);
2665
2358
  if (!root.ok) return { error: root.message };
@@ -2682,7 +2375,7 @@ function buildResourceProvider() {
2682
2375
  uri: "snapshot://manifest",
2683
2376
  name: "manifest",
2684
2377
  title: "Snapshot manifest",
2685
- 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.",
2686
2379
  mimeType: "application/json"
2687
2380
  },
2688
2381
  {
@@ -2705,7 +2398,7 @@ function buildResourceProvider() {
2705
2398
  uri,
2706
2399
  name: report.file.replace(/\.md$/, ""),
2707
2400
  title: report.title,
2708
- 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.`,
2709
2402
  mimeType: "text/markdown"
2710
2403
  });
2711
2404
  }
@@ -2714,11 +2407,12 @@ function buildResourceProvider() {
2714
2407
  const read = readManifest(workspace);
2715
2408
  if (!read.ok) return resources;
2716
2409
  for (const part of read.manifest.parts) {
2410
+ const readable = part.byteSize <= MAX_RESOURCE_BYTES;
2717
2411
  resources.push({
2718
2412
  uri: `snapshot://parts/${part.index}`,
2719
2413
  name: `part-${String(part.index).padStart(3, "0")}`,
2720
2414
  title: `Part ${part.index} (${part.fileCount} files, ${formatBytes2(part.byteSize)})`,
2721
- 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.`),
2722
2416
  mimeType: "text/markdown"
2723
2417
  });
2724
2418
  }
@@ -2738,10 +2432,26 @@ function buildResourceProvider() {
2738
2432
  async read(uri, context) {
2739
2433
  if (uri === "snapshot://contract") {
2740
2434
  const contract = buildAgentContract();
2741
- 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
+ };
2742
2444
  }
2743
2445
  if (uri === "snapshot://skill") {
2744
- 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
+ };
2745
2455
  }
2746
2456
  const workspace = await workspaceFor(context);
2747
2457
  if ("error" in workspace) return null;
@@ -2751,13 +2461,13 @@ function buildResourceProvider() {
2751
2461
  path.resolve(workspace.root, workspace.config.outDir, "reports", report.file)
2752
2462
  );
2753
2463
  if (text === null) return null;
2754
- return { uri, mimeType: "text/markdown", text: capUtf8(text, MAX_RESOURCE_BYTES).text };
2464
+ return { uri, mimeType: "text/markdown", text: ensureSingleRead(uri, text, REPORT_ADVICE) };
2755
2465
  }
2756
2466
  if (uri === "snapshot://manifest") {
2757
2467
  const read = readManifest(workspace);
2758
2468
  if (!read.ok) return null;
2759
2469
  const text = readFileIfPresent(read.file) ?? JSON.stringify(read.manifest, null, 2);
2760
- return { uri, mimeType: "application/json", text: capUtf8(text, MAX_RESOURCE_BYTES).text };
2470
+ return { uri, mimeType: "application/json", text: ensureSingleRead(uri, text, MANIFEST_ADVICE) };
2761
2471
  }
2762
2472
  const partMatch = PART_URI.exec(uri);
2763
2473
  if (partMatch) {
@@ -2768,15 +2478,401 @@ function buildResourceProvider() {
2768
2478
  if (!part) return null;
2769
2479
  const partPath = partPathFor(workspace, part.filename);
2770
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);
2771
2488
  const text = readFileIfPresent(partPath);
2772
2489
  if (text === null) return null;
2773
- return { uri, mimeType: "text/markdown", text: capUtf8(text, MAX_RESOURCE_BYTES).text };
2490
+ return { uri, mimeType: "text/markdown", text: ensureSingleRead(uri, text, PART_ADVICE) };
2774
2491
  }
2775
2492
  return null;
2776
2493
  }
2777
2494
  };
2778
2495
  }
2779
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
2633
+ }
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`
2730
+ );
2731
+ return errorResponse(id, ERROR_CODES.resourceTooLarge, error.message, {
2732
+ uri: error.uri,
2733
+ bytes: error.bytes,
2734
+ limit: error.limit
2735
+ });
2736
+ }
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;
2844
+ }
2845
+ handleNotification(method);
2846
+ return null;
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
+ }
2873
+ };
2874
+ }
2875
+
2780
2876
  // src/mcp/instructions.ts
2781
2877
  var SERVER_INSTRUCTIONS = [
2782
2878
  "codebase-snapshot serves this repository as a size-budgeted snapshot, not as a directory walk.",