loremfile 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -22,6 +22,7 @@ correctly by default: every file is verified, and a file that fails is not writt
22
22
  | `loremfile get --format svg --format pdf` | The same for every published file of a format. |
23
23
  | `loremfile list [--format F] [--tag T] [--max-bytes N]` | What is published, without downloading. |
24
24
  | `loremfile verify [PATH…]` | Check files already on disk against the manifest. |
25
+ | `loremfile mcp` | Serve the same lookups to an agent over MCP; see below. |
25
26
 
26
27
  Every command takes `--json` for scripts, `--quiet`, and `--catalog-version X.Y.Z` to
27
28
  refuse to run if loremfile.dev has moved on. `get` also takes `--force` (overwrite) and
@@ -30,6 +31,28 @@ refuse to run if loremfile.dev has moved on. `get` also takes `--force` (overwri
30
31
  Exit codes: `0` fine, `1` a file failed verification or is missing, `2` the request was
31
32
  wrong, `3` loremfile.dev could not be read.
32
33
 
34
+ ## MCP server
35
+
36
+ `loremfile mcp` runs a [Model Context Protocol](https://modelcontextprotocol.io) server over
37
+ stdio, so an agent can find a fixture, read its URL and metadata, and check a file it already
38
+ has. It returns URLs and metadata, never file bytes: the agent, or your test, fetches the URL.
39
+
40
+ ```json
41
+ { "mcpServers": { "loremfile": { "command": "npx", "args": ["-y", "loremfile", "mcp"] } } }
42
+ ```
43
+
44
+ It speaks protocol `2026-07-28` (per-request metadata, `server/discover`) and `2025-11-25`
45
+ (the `initialize` handshake), so clients of either era work. All three tools are read-only.
46
+
47
+ | Tool | Arguments | Returns |
48
+ |---|---|---|
49
+ | `list_fixtures` | `format`, `tag`, `max_bytes`, `limit`, `offset` | One page of published fixtures, each with `path`, `url`, `format`, `mime`, `bytes`, `tags` and `description`, plus `total` and `next_offset`. `format` and `tag` are lists matched as any of; `limit` defaults to 50, at most 250. |
50
+ | `describe_fixture` | `path` (required) | One fixture's manifest entry: `url`, `mime`, `bytes`, `sha256`, `size_class`, `tags`, `description`, `props` and `added_in`. |
51
+ | `verify_file` | `path` (required), `file` (required) | Whether the local `file` is the published `path`: `status` is `ok`, `changed` or `missing`, with both hashes and sizes. The file is read to hash it and goes nowhere. |
52
+
53
+ The manifest is read once per server process from loremfile.dev, under the same rules as the
54
+ commands above.
55
+
33
56
  ## What it will not do
34
57
 
35
58
  - **Write a file it could not verify.** Bytes go to a hidden temporary file beside the
@@ -66,7 +89,7 @@ support because it needs `sha256sum`.
66
89
  ## One name, two clients
67
90
 
68
91
  The Python client, `pip install loremfile`, installs a command with the same name and the
69
- same three commands. On a machine with both, `loremfile` runs whichever comes first on
92
+ same `get`, `list` and `verify`. On a machine with both, `loremfile` runs whichever comes first on
70
93
  `PATH` — and where the two install into the same directory, whichever was installed last.
71
94
  Either one checks every byte the same way.
72
95
 
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "loremfile",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Download CC0 sample files from loremfile.dev and verify every byte",
5
- "keywords": ["fixtures", "test-data", "sample-files", "cc0", "download"],
5
+ "keywords": ["fixtures", "test-data", "sample-files", "cc0", "download", "mcp"],
6
6
  "homepage": "https://loremfile.dev",
7
7
  "bugs": {
8
8
  "url": "https://github.com/kumarprabhashanand/loremfile/issues"
@@ -13,6 +13,7 @@
13
13
  "directory": "client-js"
14
14
  },
15
15
  "license": "MIT",
16
+ "mcpName": "io.github.kumarprabhashanand/loremfile",
16
17
  "author": "the loremfile.dev contributors",
17
18
  "type": "module",
18
19
  "bin": {
package/src/api.js CHANGED
@@ -354,7 +354,8 @@ export async function download(entry, dest, { force = false } = {}) {
354
354
  return new Result(entry.path, "written", `${grouped(written)} bytes`);
355
355
  }
356
356
 
357
- async function hashFile(file) {
357
+ /** The SHA-256 of a file on disk, read a chunk at a time. */
358
+ export async function hashFile(file) {
358
359
  const digest = createHash("sha256");
359
360
  for await (const chunk of createReadStream(file)) {
360
361
  digest.update(chunk);
@@ -362,7 +363,8 @@ async function hashFile(file) {
362
363
  return digest.digest("hex");
363
364
  }
364
365
 
365
- async function fileInfo(file) {
366
+ /** A regular file's stat, or null for anything that is not one. */
367
+ export async function fileInfo(file) {
366
368
  try {
367
369
  const info = await stat(file);
368
370
  return info.isFile() ? info : null;
package/src/cli.js CHANGED
@@ -1,13 +1,15 @@
1
- // `loremfile get | list | verify`, the same three commands as the Python client.
1
+ // `loremfile get | list | verify`, the same three commands as the Python client, and
2
+ // `loremfile mcp`, the same tools served to an agent (src/mcp.js).
2
3
  //
3
4
  // node:util's parseArgs rather than a framework, because the package has no dependencies and
4
- // this is three subcommands. Exit codes are the contract: 0 fine, 1 a file failed
5
+ // this is four subcommands. Exit codes are the contract: 0 fine, 1 a file failed
5
6
  // verification or is missing, 2 the request was wrong, 3 loremfile.dev could not be read.
6
7
 
7
8
  import { readFileSync } from "node:fs";
8
9
  import { parseArgs } from "node:util";
9
10
 
10
11
  import * as api from "./api.js";
12
+ import * as mcp from "./mcp.js";
11
13
 
12
14
  export const OK = 0;
13
15
  export const FAILED = 1;
@@ -64,6 +66,11 @@ export const COMMANDS = {
64
66
  ...SHARED,
65
67
  },
66
68
  },
69
+ mcp: {
70
+ summary: "Serve list, describe and verify to an agent over MCP on stdio.",
71
+ positionals: null,
72
+ options: { help: SHARED.help },
73
+ },
67
74
  };
68
75
 
69
76
  class Usage extends Error {}
@@ -73,7 +80,7 @@ function usage() {
73
80
  `loremfile ${VERSION}`,
74
81
  "Download CC0 sample files from loremfile.dev and check every byte.",
75
82
  "",
76
- "usage: loremfile {get,list,verify} [options]",
83
+ "usage: loremfile {get,list,verify,mcp} [options]",
77
84
  ...Object.entries(COMMANDS).map(([name, command]) => ` ${name.padEnd(8)}${command.summary}`),
78
85
  "",
79
86
  "`loremfile COMMAND --help` lists a command's options.",
@@ -97,7 +104,7 @@ function commandHelp(name) {
97
104
  function parse(argv) {
98
105
  const [name, ...rest] = argv;
99
106
  if (name === undefined) {
100
- throw new Usage("name a command: get, list or verify");
107
+ throw new Usage("name a command: get, list, verify or mcp");
101
108
  }
102
109
  if (!Object.hasOwn(COMMANDS, name)) {
103
110
  throw new Usage(`no such command: ${name}`);
@@ -229,9 +236,16 @@ async function runVerify(args, io) {
229
236
  return failing.length > 0 ? FAILED : OK;
230
237
  }
231
238
 
232
- const RUNNERS = { get: runGet, list: runList, verify: runVerify };
239
+ // stdout carries protocol messages only, so this writes nothing of its own there.
240
+ async function runMcp(_args, io) {
241
+ await mcp.serve({ input: io.in, write: io.out });
242
+ return OK;
243
+ }
244
+
245
+ const RUNNERS = { get: runGet, list: runList, verify: runVerify, mcp: runMcp };
233
246
 
234
247
  const STDIO = {
248
+ in: process.stdin,
235
249
  out: (text) => process.stdout.write(text),
236
250
  err: (text) => process.stderr.write(text),
237
251
  };
package/src/mcp.js ADDED
@@ -0,0 +1,549 @@
1
+ // `loremfile mcp`: a Model Context Protocol server on stdio (modelcontextprotocol.io).
2
+ //
3
+ // Dual-era, as the 2026-07-28 specification permits. A request that carries
4
+ // `io.modelcontextprotocol/protocolVersion` in `_meta` is served on its own, with no session;
5
+ // an `initialize` request opens the 2025-11-25 session older clients expect. One message per
6
+ // line in each direction, and nothing else is ever written to stdout.
7
+ //
8
+ // Node built-ins only, like the rest of the package: no SDK. The tools return URLs and
9
+ // metadata and never a file's bytes — the agent, or the test it is writing, fetches the URL.
10
+
11
+ import { readFileSync } from "node:fs";
12
+ import path from "node:path";
13
+ import { createInterface } from "node:readline";
14
+
15
+ import * as api from "./api.js";
16
+
17
+ export const MODERN = "2026-07-28";
18
+ export const LEGACY = "2025-11-25";
19
+ /** Newest first: what `server/discover` and a version error advertise. */
20
+ export const SUPPORTED = [MODERN, LEGACY];
21
+
22
+ const META = "io.modelcontextprotocol/";
23
+ export const DEFAULT_LIMIT = 50;
24
+ export const MAX_LIMIT = 250;
25
+
26
+ /** JSON-RPC codes, and the one MCP code this server uses. */
27
+ export const CODES = {
28
+ PARSE: -32700,
29
+ INVALID_REQUEST: -32600,
30
+ METHOD_NOT_FOUND: -32601,
31
+ INVALID_PARAMS: -32602,
32
+ INTERNAL: -32603,
33
+ UNSUPPORTED_VERSION: -32022,
34
+ };
35
+
36
+ export const SERVER_INFO = {
37
+ name: "loremfile",
38
+ version: JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version,
39
+ };
40
+
41
+ const INSTRUCTIONS =
42
+ "CC0 sample files and test fixtures from loremfile.dev, each at a stable URL. Use " +
43
+ "list_fixtures to find one, describe_fixture for its size, hash and measured properties, " +
44
+ "and verify_file to check a copy on disk. The tools return URLs, never file contents.";
45
+
46
+ const READ_ONLY = {
47
+ readOnlyHint: true,
48
+ destructiveHint: false,
49
+ idempotentHint: true,
50
+ // One host and one published list, not an open world.
51
+ openWorldHint: false,
52
+ };
53
+
54
+ const STRINGS = {
55
+ anyOf: [{ type: "string" }, { type: "array", items: { type: "string" } }],
56
+ };
57
+ const NULLABLE_STRING = { type: ["string", "null"] };
58
+ const NULLABLE_INTEGER = { type: ["integer", "null"] };
59
+
60
+ const LISTED = {
61
+ type: "object",
62
+ properties: {
63
+ path: { type: "string" },
64
+ url: { type: "string" },
65
+ format: { type: "string" },
66
+ mime: { type: "string" },
67
+ bytes: { type: "integer" },
68
+ tags: { type: "array", items: { type: "string" } },
69
+ description: { type: "string" },
70
+ },
71
+ required: ["path", "url", "format", "mime", "bytes", "tags", "description"],
72
+ };
73
+
74
+ /** The tool surface. client-js/README.md documents it, and a test holds the two together. */
75
+ export const TOOLS = [
76
+ {
77
+ name: "list_fixtures",
78
+ title: "List loremfile.dev fixtures",
79
+ description:
80
+ "One page of the published sample files, filtered by format, tag and size. Each comes " +
81
+ "with its URL and a description of what it is for. `total` counts every match and " +
82
+ "`next_offset` fetches the next page; it is null on the last.",
83
+ inputSchema: {
84
+ type: "object",
85
+ properties: {
86
+ format: { ...STRINGS, description: 'Formats to include, any of, e.g. ["pdf", "png"].' },
87
+ tag: { ...STRINGS, description: 'Tags to include, any of, e.g. ["encrypted"].' },
88
+ max_bytes: { type: "integer", minimum: 0, description: "Only files of at most this size." },
89
+ limit: {
90
+ type: "integer",
91
+ minimum: 1,
92
+ maximum: MAX_LIMIT,
93
+ default: DEFAULT_LIMIT,
94
+ description: `Fixtures per page, ${DEFAULT_LIMIT} unless set, at most ${MAX_LIMIT}.`,
95
+ },
96
+ offset: { type: "integer", minimum: 0, default: 0, description: "Matches to skip." },
97
+ },
98
+ additionalProperties: false,
99
+ },
100
+ outputSchema: {
101
+ type: "object",
102
+ properties: {
103
+ catalog_version: { type: "string" },
104
+ total: { type: "integer" },
105
+ offset: { type: "integer" },
106
+ limit: { type: "integer" },
107
+ count: { type: "integer" },
108
+ next_offset: NULLABLE_INTEGER,
109
+ fixtures: { type: "array", items: LISTED },
110
+ },
111
+ required: ["catalog_version", "total", "offset", "limit", "count", "next_offset", "fixtures"],
112
+ },
113
+ annotations: READ_ONLY,
114
+ },
115
+ {
116
+ name: "describe_fixture",
117
+ title: "Describe one loremfile.dev fixture",
118
+ description:
119
+ "The published manifest entry for one fixture: its URL, MIME type, size, SHA-256, tags, " +
120
+ "description and measured properties. Metadata only; fetch the URL for the file.",
121
+ inputSchema: {
122
+ type: "object",
123
+ properties: {
124
+ path: { type: "string", description: 'A fixture path, e.g. "pdf/minimal.pdf".' },
125
+ },
126
+ required: ["path"],
127
+ additionalProperties: false,
128
+ },
129
+ outputSchema: {
130
+ type: "object",
131
+ properties: {
132
+ catalog_version: { type: "string" },
133
+ path: { type: "string" },
134
+ url: { type: "string" },
135
+ format: { type: "string" },
136
+ mime: { type: "string" },
137
+ bytes: { type: "integer" },
138
+ sha256: { type: "string" },
139
+ size_class: NULLABLE_STRING,
140
+ tags: { type: "array", items: { type: "string" } },
141
+ description: { type: "string" },
142
+ props: { type: ["object", "null"] },
143
+ added_in: NULLABLE_STRING,
144
+ },
145
+ required: [
146
+ "catalog_version",
147
+ "path",
148
+ "url",
149
+ "format",
150
+ "mime",
151
+ "bytes",
152
+ "sha256",
153
+ "size_class",
154
+ "tags",
155
+ "description",
156
+ "props",
157
+ "added_in",
158
+ ],
159
+ },
160
+ annotations: READ_ONLY,
161
+ },
162
+ {
163
+ name: "verify_file",
164
+ title: "Verify a local copy of a loremfile.dev fixture",
165
+ description:
166
+ "Hash a file on this machine and compare it with the published SHA-256 and size of a " +
167
+ "fixture. `status` is ok, changed or missing. The file is read only to hash it.",
168
+ inputSchema: {
169
+ type: "object",
170
+ properties: {
171
+ path: { type: "string", description: 'The fixture path, e.g. "pdf/minimal.pdf".' },
172
+ file: {
173
+ type: "string",
174
+ description: "The local file: absolute, or relative to where the server was started.",
175
+ },
176
+ },
177
+ required: ["path", "file"],
178
+ additionalProperties: false,
179
+ },
180
+ outputSchema: {
181
+ type: "object",
182
+ properties: {
183
+ path: { type: "string" },
184
+ file: { type: "string" },
185
+ status: { type: "string", enum: ["ok", "changed", "missing"] },
186
+ expected_sha256: { type: "string" },
187
+ actual_sha256: NULLABLE_STRING,
188
+ expected_bytes: { type: "integer" },
189
+ actual_bytes: NULLABLE_INTEGER,
190
+ },
191
+ required: [
192
+ "path",
193
+ "file",
194
+ "status",
195
+ "expected_sha256",
196
+ "actual_sha256",
197
+ "expected_bytes",
198
+ "actual_bytes",
199
+ ],
200
+ },
201
+ annotations: READ_ONLY,
202
+ },
203
+ ];
204
+
205
+ /** A failure the model can act on: a tool result with `isError`, not a protocol error. */
206
+ export class ToolError extends Error {}
207
+
208
+ class ProtocolError extends Error {
209
+ constructor(code, message, data) {
210
+ super(message);
211
+ this.code = code;
212
+ this.data = data;
213
+ }
214
+ }
215
+
216
+ // --- arguments ----------------------------------------------------------------------------
217
+
218
+ function only(args, allowed) {
219
+ if (args === null || typeof args !== "object" || Array.isArray(args)) {
220
+ throw new ToolError("arguments must be an object");
221
+ }
222
+ const unknown = Object.keys(args).filter((key) => !allowed.includes(key));
223
+ if (unknown.length > 0) {
224
+ throw new ToolError(
225
+ `unknown argument ${unknown.join(", ")}; this tool takes ${allowed.join(", ")}`,
226
+ );
227
+ }
228
+ return args;
229
+ }
230
+
231
+ function strings(value, name) {
232
+ if (value === undefined) {
233
+ return [];
234
+ }
235
+ const list = typeof value === "string" ? [value] : value;
236
+ if (!Array.isArray(list) || !list.every((item) => typeof item === "string")) {
237
+ throw new ToolError(`${name} must be a list of strings`);
238
+ }
239
+ return list;
240
+ }
241
+
242
+ function integer(value, name, { min, max, fallback }) {
243
+ if (value === undefined) {
244
+ return fallback;
245
+ }
246
+ if (!Number.isInteger(value) || value < min || (max !== undefined && value > max)) {
247
+ const range = max === undefined ? `at least ${min}` : `from ${min} to ${max}`;
248
+ throw new ToolError(`${name} must be a whole number ${range}, not ${JSON.stringify(value)}`);
249
+ }
250
+ return value;
251
+ }
252
+
253
+ function text(value, name) {
254
+ if (typeof value !== "string" || value.trim() === "") {
255
+ throw new ToolError(`${name} is required and must be a non-empty string`);
256
+ }
257
+ return value;
258
+ }
259
+
260
+ // --- the tools ----------------------------------------------------------------------------
261
+
262
+ function url(entry) {
263
+ return `${api.baseUrl()}${entry.path}`;
264
+ }
265
+
266
+ function byPath(document, fixturePath) {
267
+ const entry = api.active(document).find((candidate) => candidate.path === fixturePath);
268
+ if (entry === undefined) {
269
+ throw new ToolError(
270
+ `no published fixture at ${JSON.stringify(fixturePath)}; ` +
271
+ "list_fixtures shows what is published",
272
+ );
273
+ }
274
+ return entry;
275
+ }
276
+
277
+ async function listFixtures(document, args) {
278
+ only(args, ["format", "tag", "max_bytes", "limit", "offset"]);
279
+ const formats = strings(args.format, "format");
280
+ const tags = strings(args.tag, "tag");
281
+ const maxBytes = integer(args.max_bytes, "max_bytes", { min: 0, fallback: null });
282
+ const limit = integer(args.limit, "limit", { min: 1, max: MAX_LIMIT, fallback: DEFAULT_LIMIT });
283
+ const offset = integer(args.offset, "offset", { min: 0, fallback: 0 });
284
+ // The same filters as `loremfile list`: any of the formats, any of the tags, all three kinds.
285
+ const matches = api
286
+ .active(document)
287
+ .filter((e) => formats.length === 0 || formats.includes(e.format))
288
+ .filter((e) => tags.length === 0 || (e.tags ?? []).some((tag) => tags.includes(tag)))
289
+ .filter((e) => maxBytes === null || e.bytes <= maxBytes)
290
+ .sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
291
+ const page = matches.slice(offset, offset + limit);
292
+ return {
293
+ catalog_version: String(document.catalog_version ?? ""),
294
+ total: matches.length,
295
+ offset,
296
+ limit,
297
+ count: page.length,
298
+ next_offset: offset + limit < matches.length ? offset + limit : null,
299
+ fixtures: page.map((e) => ({
300
+ path: e.path,
301
+ url: url(e),
302
+ format: e.format,
303
+ mime: e.mime,
304
+ bytes: e.bytes,
305
+ tags: e.tags ?? [],
306
+ description: e.description ?? "",
307
+ })),
308
+ };
309
+ }
310
+
311
+ async function describeFixture(document, args) {
312
+ only(args, ["path"]);
313
+ const entry = byPath(document, text(args.path, "path"));
314
+ return {
315
+ catalog_version: String(document.catalog_version ?? ""),
316
+ path: entry.path,
317
+ url: url(entry),
318
+ format: entry.format,
319
+ mime: entry.mime,
320
+ bytes: entry.bytes,
321
+ sha256: entry.sha256,
322
+ size_class: entry.size_class ?? null,
323
+ tags: entry.tags ?? [],
324
+ description: entry.description ?? "",
325
+ props: entry.props ?? null,
326
+ added_in: entry.added_in ?? null,
327
+ };
328
+ }
329
+
330
+ async function verifyFile(document, args) {
331
+ only(args, ["path", "file"]);
332
+ const entry = byPath(document, text(args.path, "path"));
333
+ const file = path.resolve(text(args.file, "file"));
334
+ const info = await api.fileInfo(file);
335
+ const actual = info === null ? null : await api.hashFile(file);
336
+ return {
337
+ path: entry.path,
338
+ file,
339
+ status: info === null ? "missing" : actual === entry.sha256 ? "ok" : "changed",
340
+ expected_sha256: entry.sha256,
341
+ actual_sha256: actual,
342
+ expected_bytes: entry.bytes,
343
+ actual_bytes: info === null ? null : info.size,
344
+ };
345
+ }
346
+
347
+ const HANDLERS = {
348
+ list_fixtures: listFixtures,
349
+ describe_fixture: describeFixture,
350
+ verify_file: verifyFile,
351
+ };
352
+
353
+ // --- the protocol -------------------------------------------------------------------------
354
+
355
+ /**
356
+ * One server's state: the manifest, read once, and the legacy session if a client opened one.
357
+ * `load` exists so tests can count reads; it defaults to the client's own manifest fetch.
358
+ */
359
+ export function createServer({ load = () => api.manifest() } = {}) {
360
+ let manifest = null;
361
+ let session = null; // the negotiated legacy version, once `initialize` arrives
362
+
363
+ function published() {
364
+ // Kept for the process; dropped on failure, so a later call can try again.
365
+ manifest ??= load().catch((error) => {
366
+ manifest = null;
367
+ throw error;
368
+ });
369
+ return manifest;
370
+ }
371
+
372
+ async function callTool(params) {
373
+ if (params === null || typeof params !== "object" || typeof params.name !== "string") {
374
+ throw new ProtocolError(CODES.INVALID_PARAMS, "tools/call needs a tool name");
375
+ }
376
+ const handler = HANDLERS[params.name];
377
+ if (handler === undefined) {
378
+ throw new ProtocolError(CODES.INVALID_PARAMS, `Unknown tool: ${params.name}`);
379
+ }
380
+ try {
381
+ const structured = await handler(await published(), params.arguments ?? {});
382
+ return {
383
+ content: [{ type: "text", text: JSON.stringify(structured) }],
384
+ structuredContent: structured,
385
+ };
386
+ } catch (error) {
387
+ if (
388
+ error instanceof ToolError ||
389
+ error instanceof api.Refused ||
390
+ error instanceof api.Unreachable
391
+ ) {
392
+ const prefix = error instanceof api.Unreachable ? "loremfile.dev could not be read: " : "";
393
+ return { content: [{ type: "text", text: `${prefix}${error.message}` }], isError: true };
394
+ }
395
+ throw error;
396
+ }
397
+ }
398
+
399
+ async function dispatch(method, params, modern) {
400
+ if (method === "tools/list") {
401
+ return modern ? { tools: TOOLS, ttlMs: 3_600_000, cacheScope: "public" } : { tools: TOOLS };
402
+ }
403
+ if (method === "tools/call") {
404
+ return callTool(params);
405
+ }
406
+ if (method === "server/discover" && modern) {
407
+ return {
408
+ supportedVersions: SUPPORTED,
409
+ capabilities: { tools: {} },
410
+ instructions: INSTRUCTIONS,
411
+ ttlMs: 3_600_000,
412
+ cacheScope: "public",
413
+ };
414
+ }
415
+ if (method === "ping" && !modern) {
416
+ return {};
417
+ }
418
+ throw new ProtocolError(CODES.METHOD_NOT_FOUND, `Method not found: ${method}`);
419
+ }
420
+
421
+ async function request(method, params) {
422
+ if (method === "initialize") {
423
+ // 2025-11-25 negotiation: echo a version this server speaks, otherwise offer its own.
424
+ const asked = params?.protocolVersion;
425
+ session = asked === LEGACY ? asked : LEGACY;
426
+ return {
427
+ protocolVersion: session,
428
+ capabilities: { tools: {} },
429
+ serverInfo: SERVER_INFO,
430
+ instructions: INSTRUCTIONS,
431
+ };
432
+ }
433
+ const meta = params?._meta;
434
+ const version = meta?.[`${META}protocolVersion`];
435
+ if (version !== undefined) {
436
+ if (!SUPPORTED.includes(version)) {
437
+ throw new ProtocolError(CODES.UNSUPPORTED_VERSION, "Unsupported protocol version", {
438
+ supported: SUPPORTED,
439
+ requested: version,
440
+ });
441
+ }
442
+ const capabilities = meta[`${META}clientCapabilities`];
443
+ if (
444
+ capabilities === null ||
445
+ typeof capabilities !== "object" ||
446
+ Array.isArray(capabilities)
447
+ ) {
448
+ throw new ProtocolError(
449
+ CODES.INVALID_PARAMS,
450
+ `_meta lacks the required ${META}clientCapabilities`,
451
+ );
452
+ }
453
+ const result = await dispatch(method, params, version === MODERN);
454
+ if (version !== MODERN) {
455
+ return result;
456
+ }
457
+ return { resultType: "complete", ...result, _meta: { [`${META}serverInfo`]: SERVER_INFO } };
458
+ }
459
+ if (session !== null || method === "ping") {
460
+ return dispatch(method, params, false);
461
+ }
462
+ throw new ProtocolError(
463
+ CODES.INVALID_PARAMS,
464
+ `_meta lacks the required ${META}protocolVersion; send it on every request ` +
465
+ `(protocol ${MODERN}) or open a session with initialize (protocol ${LEGACY})`,
466
+ );
467
+ }
468
+
469
+ /** The reply to one parsed message, or null when there is nothing to send. */
470
+ async function handle(message) {
471
+ if (message === null || typeof message !== "object" || Array.isArray(message)) {
472
+ return {
473
+ jsonrpc: "2.0",
474
+ error: { code: CODES.INVALID_REQUEST, message: "not a JSON-RPC object" },
475
+ };
476
+ }
477
+ const hasId = Object.hasOwn(message, "id");
478
+ if (!hasId) {
479
+ return null; // a notification: initialized, cancelled; nothing to answer
480
+ }
481
+ const { id } = message;
482
+ if (
483
+ message.jsonrpc !== "2.0" ||
484
+ typeof message.method !== "string" ||
485
+ !(typeof id === "string" || Number.isInteger(id))
486
+ ) {
487
+ return {
488
+ jsonrpc: "2.0",
489
+ id,
490
+ error: { code: CODES.INVALID_REQUEST, message: "not a JSON-RPC 2.0 request" },
491
+ };
492
+ }
493
+ try {
494
+ return { jsonrpc: "2.0", id, result: await request(message.method, message.params) };
495
+ } catch (error) {
496
+ if (error instanceof ProtocolError) {
497
+ const body = { code: error.code, message: error.message };
498
+ return {
499
+ jsonrpc: "2.0",
500
+ id,
501
+ error: error.data === undefined ? body : { ...body, data: error.data },
502
+ };
503
+ }
504
+ return {
505
+ jsonrpc: "2.0",
506
+ id,
507
+ error: { code: CODES.INTERNAL, message: String(error?.message ?? error) },
508
+ };
509
+ }
510
+ }
511
+
512
+ /** The reply to one line of input, or null. */
513
+ async function line(raw) {
514
+ if (raw.trim() === "") {
515
+ return null;
516
+ }
517
+ let message;
518
+ try {
519
+ message = JSON.parse(raw);
520
+ } catch {
521
+ return { jsonrpc: "2.0", error: { code: CODES.PARSE, message: "Parse error" } };
522
+ }
523
+ return handle(message);
524
+ }
525
+
526
+ return { handle, line };
527
+ }
528
+
529
+ /**
530
+ * Serve until the input ends: one message per line in, one per line out, in order.
531
+ * Resolves once every reply has been written, so the process can exit cleanly.
532
+ */
533
+ export async function serve({
534
+ input = process.stdin,
535
+ write = (text) => process.stdout.write(text),
536
+ server = createServer(),
537
+ } = {}) {
538
+ const lines = createInterface({ input, crlfDelay: Infinity });
539
+ let pending = Promise.resolve();
540
+ for await (const raw of lines) {
541
+ pending = pending.then(async () => {
542
+ const reply = await server.line(raw);
543
+ if (reply !== null) {
544
+ write(`${JSON.stringify(reply)}\n`);
545
+ }
546
+ });
547
+ }
548
+ await pending;
549
+ }