guessit-js 5.1.0 → 5.3.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
@@ -14,6 +14,7 @@ Extract metadata (title, year, season, episode, codec, language, etc.) from medi
14
14
 
15
15
  - **Runs 2191 of the 2229 cases in Python guessit's own test suite** (upstream 4.5.1, its corpus *and* its per-rule files) — and is **more correct**: fixes for 32 historical upstream bugs, Python's still-open #877, and 114 of the 276 cross-parser cases Python admits failing (see [Differences from Python](#differences-from-python-guessit))
16
16
  - **Drop-in output**: results use Python guessit's own notation (`"language": "French"`, `"country": "UNITED STATES"`, `"date": "2024-03-15"`) in the library, CLI, REST API and WASM; guessit-js only *parses* better. Richer codes are opt-in with [`output: 'codes'`](#output-notation)
17
+ - **AI-agent ready**: an [MCP server](#ai-agents-mcp) (`npx -y guessit-js --mcp`, or the hosted `https://guessit.opensubtitles.com/mcp`) and an [`llms.txt`](https://opensubtitles.github.io/guessit-js/llms.txt)
17
18
  - **~2x faster** than Python per parse ([measured](#performance))
18
19
  - **56 properties** detected: title, year, season, episode, resolution, codec, language, ids, and more — with a [machine-readable schema](#output-schema)
19
20
  - **Batch parsing**: `guessitMany()` in-process, or one POST for up to 100 names
@@ -253,6 +254,58 @@ A name that fails to parse becomes an `error` entry — the request still answer
253
254
  `200`. The caps bound the shape of one request, not throughput: for 10k names,
254
255
  send 100 requests, or skip HTTP and call `guessitMany()` in-process.
255
256
 
257
+ ## AI agents (MCP)
258
+
259
+ guessit-js is a [Model Context Protocol](https://modelcontextprotocol.io) server,
260
+ so AI agents (Claude, Cursor, VS Code Copilot, any MCP client) can call it as a
261
+ tool. Three read-only tools:
262
+
263
+ | Tool | Input | Output |
264
+ |---|---|---|
265
+ | `guessit` | `{"filename": "...", "options": {...}}` | the result, same JSON as the library |
266
+ | `guessit_batch` | `{"filenames": [...], "options": {...}}` | `{"results": [{input_string, result} \| {input_string, error}]}` |
267
+ | `guessit_properties` | `{}` | every property with its possible values |
268
+
269
+ [![Install in VS Code](https://img.shields.io/badge/VS_Code-Install_guessit-0098FF?logo=visualstudiocode&logoColor=white)](https://insiders.vscode.dev/redirect/mcp/install?name=guessit&config=%7B%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22guessit-js%22%2C%22--mcp%22%5D%7D)
270
+ [![Install in Cursor](https://img.shields.io/badge/Cursor-Install_guessit-000000?logo=cursor&logoColor=white)](https://cursor.com/en/install-mcp?name=guessit&config=eyJjb21tYW5kIjoibnB4IiwiYXJncyI6WyIteSIsImd1ZXNzaXQtanMiLCItLW1jcCJdfQ==)
271
+ [![Claude Desktop extension](https://img.shields.io/badge/Claude_Desktop-guessit--js.mcpb-D97757?logo=claude&logoColor=white)](https://github.com/opensubtitles/guessit-js/releases/latest/download/guessit-js.mcpb)
272
+ [![MCP Registry](https://img.shields.io/badge/MCP_Registry-com.opensubtitles%2Fguessit--js-555)](https://registry.modelcontextprotocol.io/v0/servers?search=com.opensubtitles/guessit-js)
273
+
274
+ **Claude Desktop**: download [`guessit-js.mcpb`](https://github.com/opensubtitles/guessit-js/releases/latest/download/guessit-js.mcpb)
275
+ from the latest release and open it (Settings → Extensions). Runs locally, offline.
276
+
277
+ **Local (stdio)**, no server to run:
278
+
279
+ ```bash
280
+ claude mcp add guessit -- npx -y guessit-js --mcp # Claude Code
281
+ ```
282
+
283
+ ```json
284
+ { "mcpServers": { "guessit": { "command": "npx", "args": ["-y", "guessit-js", "--mcp"] } } }
285
+ ```
286
+
287
+ (Claude Desktop `claude_desktop_config.json`, Cursor `.cursor/mcp.json`, VS Code
288
+ `.vscode/mcp.json` with `"servers"` instead of `"mcpServers"`.)
289
+
290
+ Docker: `docker run -i --rm ghcr.io/opensubtitles/guessit-js node bin/cli.mjs --mcp`
291
+
292
+ **Remote (Streamable HTTP)**, nothing to install: `https://guessit.opensubtitles.com/mcp`
293
+ (demo tier, same limits as the hosted API), or `POST /mcp` on a self-hosted
294
+ `npm start` server.
295
+
296
+ ```bash
297
+ claude mcp add --transport http guessit https://guessit.opensubtitles.com/mcp
298
+ ```
299
+
300
+ Protocol: dual-era. Stateless MCP `2026-07-28` (`server/discover`, per-request
301
+ `_meta`, no handshake) and the `initialize` handshake of `2025-11-25` back to
302
+ `2024-11-05`, on both stdio and HTTP. Every tool has an `outputSchema` and
303
+ returns `structuredContent`. Listed in the [official MCP Registry](https://registry.modelcontextprotocol.io)
304
+ as `com.opensubtitles/guessit-js`.
305
+
306
+ For language models reading about the project: [`llms.txt`](https://opensubtitles.github.io/guessit-js/llms.txt)
307
+ (also at `/llms.txt` on the hosted API) and the [OpenAPI spec](https://opensubtitles.github.io/guessit-js/openapi.json).
308
+
256
309
  ## WASM
257
310
 
258
311
  For non-JS environments (Rust, Go, C++, edge compute). Uses [Javy](https://github.com/bytecodealliance/javy) (QuickJS → WASM).
package/bin/cli.mjs CHANGED
@@ -77,6 +77,9 @@ Information:
77
77
  --version Display the guessit-js version banner
78
78
 
79
79
  Extras (not in the Python CLI):
80
+ --mcp Run as an MCP server on stdio, so AI agents (Claude,
81
+ Cursor, VS Code, ...) can call guessit as a tool:
82
+ tools guessit, guessit_batch, guessit_properties
80
83
  --output-codes JSON with guessit-js codes instead of Python's names:
81
84
  languages as {"alpha3": ...} (keeps regions such as
82
85
  pt-BR), countries as ISO alpha-2, dates as ISO strings.
@@ -149,6 +152,7 @@ let serve = false;
149
152
  let servePort = 3847;
150
153
  let benchmark = 0;
151
154
  let completionShell = null;
155
+ let mcp = false;
152
156
 
153
157
  const needsValue = (a, i) => {
154
158
  if (i + 1 >= args.length) fail(`option ${a} requires a value`);
@@ -198,6 +202,7 @@ for (let i = 0; i < args.length; i++) {
198
202
  case '-p': case '--properties': listProperties = true; break;
199
203
  case '-V': case '--values': listValues = true; break;
200
204
  case '--output-codes': cliOptions.output = 'codes'; break;
205
+ case '--mcp': mcp = true; break;
201
206
  case '--serve':
202
207
  serve = true;
203
208
  if (args[i + 1] && /^\d+$/.test(args[i + 1])) { servePort = Number(args[++i]); }
@@ -364,7 +369,7 @@ if (listProperties || listValues) {
364
369
 
365
370
  // ---- shell completion -------------------------------------------------------
366
371
  if (completionShell) {
367
- const flags = '-t --type -n --name-only -Y --date-year-first -D --date-day-first -L --allowed-languages -C --allowed-countries -E --episode-prefer-number -T --expected-title -G --expected-group --includes --excludes -f --input-file -v --verbose -P --show-property -a --advanced -s --single-value -j --json --jsonl -y --yaml -i --output-input-string -c --config --no-user-config --no-default-config -p --properties -V --values --version --serve --benchmark --completion -h --help';
372
+ const flags = '-t --type -n --name-only -Y --date-year-first -D --date-day-first -L --allowed-languages -C --allowed-countries -E --episode-prefer-number -T --expected-title -G --expected-group --includes --excludes -f --input-file -v --verbose -P --show-property -a --advanced -s --single-value -j --json --jsonl -y --yaml -i --output-input-string -c --config --no-user-config --no-default-config -p --properties -V --values --version --serve --mcp --output-codes --benchmark --completion -h --help';
368
373
  if (completionShell === 'bash') {
369
374
  console.log(`_guessit_js() {
370
375
  local cur="\${COMP_WORDS[COMP_CWORD]}"
@@ -384,6 +389,12 @@ _arguments '*: :{ _alternative "flags:flag:(${flags})" "files:filename:_files" }
384
389
  process.exit(0);
385
390
  }
386
391
 
392
+ // ---- MCP server (AI agents) -------------------------------------------------
393
+ if (mcp) {
394
+ // Runs until stdin closes; nothing else may write to stdout.
395
+ const { runMcpServer } = await import('./mcp.mjs');
396
+ runMcpServer({ guessit, guessitMany, properties: apiProperties, version });
397
+ } else
387
398
  // ---- REST API server --------------------------------------------------------
388
399
  if (serve) {
389
400
  const { createServer } = await import('http');
@@ -0,0 +1,371 @@
1
+ // guessit-js MCP core: the Model Context Protocol tools and JSON-RPC handling,
2
+ // shared by the stdio server (bin/mcp.mjs, `guessit-js --mcp`), the hosted
3
+ // Cloudflare worker and server.ts (HTTP POST /mcp). No Node-only imports, no
4
+ // dependencies.
5
+
6
+ // Dual-era: "modern" revisions (2026-07-28+) are stateless and carry the
7
+ // protocol version in every request's _meta; "legacy" revisions open with an
8
+ // initialize handshake. The server itself keeps no state either way.
9
+ const MODERN_PROTOCOLS = ['2026-07-28'];
10
+ const LEGACY_PROTOCOLS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
11
+ const SUPPORTED_PROTOCOLS = [...MODERN_PROTOCOLS, ...LEGACY_PROTOCOLS];
12
+ const MAX_FILENAME_LENGTH = 4096;
13
+
14
+ const META = 'io.modelcontextprotocol/';
15
+ // The tool list only changes with a new release; clients and shared caches may keep it.
16
+ const CACHEABLE = { ttlMs: 3_600_000, cacheScope: 'public' };
17
+
18
+ const INSTRUCTIONS =
19
+ 'guessit-js extracts metadata (title, year, season, episode, resolution, codecs, '
20
+ + 'languages, release group, ...) from movie and TV filenames. Use guessit for one '
21
+ + 'name, guessit_batch for many. Output matches Python guessit; pass '
22
+ + 'options.output="codes" for ISO language codes with regions.';
23
+
24
+ const serverInfo = (api) => ({
25
+ name: 'guessit-js',
26
+ title: 'guessit-js',
27
+ version: api.version,
28
+ description: 'Parse movie and TV filenames: title, year, season, episode, codecs, languages, release group.',
29
+ websiteUrl: 'https://opensubtitles.github.io/guessit-js/',
30
+ });
31
+
32
+ // Error codes (2026-07-28 reserves -32020..-32099 for the MCP specification).
33
+ const HEADER_MISMATCH = -32020;
34
+ const UNSUPPORTED_PROTOCOL_VERSION = -32022;
35
+
36
+ const OPTIONS_SCHEMA = {
37
+ type: 'object',
38
+ description:
39
+ 'Optional guessit options, as in the library and Python guessit: type ("movie" | "episode"), '
40
+ + 'output ("python" default: language/country as names like "French"; "codes": {"alpha3": "fra"} '
41
+ + 'objects that keep regions such as pt-BR), expected_title, allowed_languages, allowed_countries, '
42
+ + 'name_only, date_day_first, date_year_first, excludes, includes.',
43
+ additionalProperties: true,
44
+ };
45
+
46
+ const TOOLS = [
47
+ {
48
+ name: 'guessit',
49
+ title: 'Parse a media filename',
50
+ description:
51
+ 'Extract metadata from one movie or TV episode filename or release name: title, year, '
52
+ + 'season, episode, episode_title, screen_size, source, video_codec, audio_codec, language, '
53
+ + 'subtitle_language, release_group, streaming_service, container, type (movie or episode) and '
54
+ + 'more (56 properties). Output matches Python guessit\'s JSON. Pass just the file name or a '
55
+ + 'full path; directory names help (e.g. "Show/Season 2/episode.mkv").',
56
+ inputSchema: {
57
+ type: 'object',
58
+ properties: {
59
+ filename: { type: 'string', description: 'Filename, path or release name, e.g. "The.Matrix.1999.1080p.BluRay.x264-GRP.mkv"' },
60
+ options: OPTIONS_SCHEMA,
61
+ },
62
+ required: ['filename'],
63
+ additionalProperties: false,
64
+ },
65
+ outputSchema: {
66
+ type: 'object',
67
+ description: 'Python guessit JSON: only the properties found; several values become an array. '
68
+ + 'guessit_properties lists every property. Full schema: '
69
+ + 'https://github.com/opensubtitles/guessit-js/blob/main/docs/output-schema.json',
70
+ properties: {
71
+ type: { type: 'string', enum: ['movie', 'episode'] },
72
+ title: {},
73
+ year: {},
74
+ season: {},
75
+ episode: {},
76
+ },
77
+ additionalProperties: true,
78
+ },
79
+ annotations: { readOnlyHint: true, openWorldHint: false, idempotentHint: true },
80
+ },
81
+ {
82
+ name: 'guessit_batch',
83
+ title: 'Parse many media filenames',
84
+ description:
85
+ 'Parse many filenames in one call with the same options. Returns one entry per '
86
+ + 'name, in order: {input_string, result} or {input_string, error}. Faster than calling '
87
+ + 'guessit repeatedly.',
88
+ inputSchema: {
89
+ type: 'object',
90
+ properties: {
91
+ filenames: { type: 'array', items: { type: 'string' }, minItems: 1 },
92
+ options: OPTIONS_SCHEMA,
93
+ },
94
+ required: ['filenames'],
95
+ additionalProperties: false,
96
+ },
97
+ outputSchema: {
98
+ type: 'object',
99
+ properties: {
100
+ results: {
101
+ type: 'array',
102
+ description: 'One entry per input name, in order',
103
+ items: {
104
+ type: 'object',
105
+ properties: {
106
+ input_string: { type: 'string' },
107
+ result: { type: 'object', additionalProperties: true },
108
+ error: { type: 'string' },
109
+ },
110
+ required: ['input_string'],
111
+ },
112
+ },
113
+ },
114
+ required: ['results'],
115
+ },
116
+ annotations: { readOnlyHint: true, openWorldHint: false, idempotentHint: true },
117
+ },
118
+ {
119
+ name: 'guessit_properties',
120
+ title: 'List guessit properties',
121
+ description:
122
+ 'List every property guessit can return with its possible values (enum values such as '
123
+ + 'source: ["Blu-ray", "Web", ...]; [null] for free-form ones such as title).',
124
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
125
+ outputSchema: {
126
+ type: 'object',
127
+ description: 'Property name -> possible values',
128
+ additionalProperties: { type: 'array' },
129
+ },
130
+ annotations: { readOnlyHint: true, openWorldHint: false, idempotentHint: true },
131
+ },
132
+ ];
133
+
134
+ /** The tool list, with the batch limit of the surface serving it. */
135
+ function toolsFor(api) {
136
+ return TOOLS.map((t) => (t.name !== 'guessit_batch' ? t : {
137
+ ...t,
138
+ description: t.description.replace('many filenames', `up to ${api.maxBatch} filenames`),
139
+ inputSchema: {
140
+ ...t.inputSchema,
141
+ properties: {
142
+ ...t.inputSchema.properties,
143
+ filenames: { ...t.inputSchema.properties.filenames, maxItems: api.maxBatch },
144
+ },
145
+ },
146
+ }));
147
+ }
148
+
149
+ function toolResult(value) {
150
+ // structuredContent must be an object; batch results are wrapped.
151
+ const structured = Array.isArray(value) ? { results: value } : value;
152
+ return {
153
+ content: [{ type: 'text', text: JSON.stringify(value) }],
154
+ structuredContent: structured,
155
+ };
156
+ }
157
+
158
+ function toolError(message) {
159
+ return { content: [{ type: 'text', text: message }], isError: true };
160
+ }
161
+
162
+ function validOptions(options) {
163
+ if (options === undefined) return {};
164
+ if (!options || typeof options !== 'object' || Array.isArray(options)) {
165
+ throw new Error('options must be an object');
166
+ }
167
+ return options;
168
+ }
169
+
170
+ /**
171
+ * Answer one JSON-RPC message. Returns the response object, or null when the
172
+ * message is a notification (or anything else that takes no answer).
173
+ * @param {{ guessit: Function, guessitMany: Function, properties: Function, version: string }} api
174
+ */
175
+ /** The protocol version a request's _meta declares (modern revisions), if any. */
176
+ function requestedVersion(msg) {
177
+ const meta = msg && msg.params && msg.params._meta;
178
+ return meta && typeof meta === 'object' ? meta[`${META}protocolVersion`] : undefined;
179
+ }
180
+
181
+ /** Modern requests declare their version per request; server/discover exists only there. */
182
+ export function isModernRequest(msg) {
183
+ return !!msg && typeof msg === 'object'
184
+ && (requestedVersion(msg) !== undefined || msg.method === 'server/discover');
185
+ }
186
+
187
+ /**
188
+ * Answer one JSON-RPC message. Returns the response object, or null when the
189
+ * message is a notification (or anything else that takes no answer).
190
+ * @param {{ guessit: Function, guessitMany: Function, properties: Function, version: string, maxBatch: number }} api
191
+ */
192
+ export function handleMcpMessage(api, msg) {
193
+ const fail = (id, code, message, data) => ({ jsonrpc: '2.0', id, error: data === undefined ? { code, message } : { code, message, data } });
194
+
195
+ function callTool(name, args) {
196
+ args = args ?? {};
197
+ try {
198
+ if (name === 'guessit') {
199
+ if (typeof args.filename !== 'string' || !args.filename) return toolError('filename (string) is required');
200
+ if (args.filename.length > MAX_FILENAME_LENGTH) return toolError(`filename exceeds ${MAX_FILENAME_LENGTH} characters`);
201
+ return toolResult(api.guessit(args.filename, validOptions(args.options)));
202
+ }
203
+ if (name === 'guessit_batch') {
204
+ const names = args.filenames;
205
+ if (!Array.isArray(names) || names.length === 0) return toolError('filenames (non-empty array of strings) is required');
206
+ if (names.length > api.maxBatch) return toolError(`at most ${api.maxBatch} filenames per call`);
207
+ const strings = names.map(String);
208
+ if (strings.some((f) => f.length > MAX_FILENAME_LENGTH)) return toolError(`filename exceeds ${MAX_FILENAME_LENGTH} characters`);
209
+ return toolResult(api.guessitMany(strings, validOptions(args.options)));
210
+ }
211
+ if (name === 'guessit_properties') return toolResult(api.properties());
212
+ } catch (e) {
213
+ return toolError(String((e && e.message) || e));
214
+ }
215
+ return null;
216
+ }
217
+
218
+ if (!msg || typeof msg !== 'object' || msg.jsonrpc !== '2.0' || typeof msg.method !== 'string') {
219
+ return msg && typeof msg === 'object' && msg.id !== undefined ? fail(msg.id, -32600, 'Invalid Request') : null;
220
+ }
221
+ const { id, method, params } = msg;
222
+ const isNotification = id === undefined || id === null;
223
+ if (isNotification) return null; // notifications/initialized, cancelled, ... take no answer
224
+
225
+ // Modern (stateless) requests: validate the per-request _meta first.
226
+ const modern = isModernRequest(msg);
227
+ const requested = requestedVersion(msg);
228
+ let modernShape = false;
229
+ if (modern) {
230
+ if (typeof requested !== 'string') {
231
+ return fail(id, -32602, `Invalid params: _meta["${META}protocolVersion"] is required`);
232
+ }
233
+ if (!SUPPORTED_PROTOCOLS.includes(requested)) {
234
+ return fail(id, UNSUPPORTED_PROTOCOL_VERSION, 'Unsupported protocol version', { supported: SUPPORTED_PROTOCOLS, requested });
235
+ }
236
+ modernShape = MODERN_PROTOCOLS.includes(requested);
237
+ const caps = params._meta[`${META}clientCapabilities`];
238
+ if (modernShape && (!caps || typeof caps !== 'object' || Array.isArray(caps))) {
239
+ return fail(id, -32602, `Invalid params: _meta["${META}clientCapabilities"] is required`);
240
+ }
241
+ }
242
+ // Modern results say they are complete and name the server (there is no handshake).
243
+ const reply = (result) => ({
244
+ jsonrpc: '2.0',
245
+ id,
246
+ result: modernShape
247
+ ? { resultType: 'complete', ...result, _meta: { [`${META}serverInfo`]: serverInfo(api) } }
248
+ : result,
249
+ });
250
+
251
+ switch (method) {
252
+ case 'server/discover':
253
+ return reply({
254
+ supportedVersions: SUPPORTED_PROTOCOLS,
255
+ capabilities: { tools: {} },
256
+ instructions: INSTRUCTIONS,
257
+ ...CACHEABLE,
258
+ });
259
+ case 'initialize': {
260
+ // The legacy handshake negotiates a legacy revision only.
261
+ const asked = params && params.protocolVersion;
262
+ return reply({
263
+ protocolVersion: LEGACY_PROTOCOLS.includes(asked) ? asked : LEGACY_PROTOCOLS[0],
264
+ capabilities: { tools: { listChanged: false } },
265
+ serverInfo: serverInfo(api),
266
+ instructions: INSTRUCTIONS,
267
+ });
268
+ }
269
+ case 'ping':
270
+ return reply({});
271
+ case 'tools/list':
272
+ return reply(modernShape ? { tools: toolsFor(api), ...CACHEABLE } : { tools: toolsFor(api) });
273
+ case 'tools/call': {
274
+ const result = callTool(params && params.name, params && params.arguments);
275
+ return result === null ? fail(id, -32602, `Unknown tool: ${params && params.name}`) : reply(result);
276
+ }
277
+ default:
278
+ return fail(id, -32601, `Method not found: ${method}`);
279
+ }
280
+ }
281
+
282
+ /** Parse one transport payload (a message or a JSON-RPC batch) and answer it. */
283
+ export function handleMcpPayload(api, text) {
284
+ let msg;
285
+ try {
286
+ msg = JSON.parse(text);
287
+ } catch {
288
+ return { jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } };
289
+ }
290
+ if (Array.isArray(msg)) {
291
+ const out = msg.map((m) => handleMcpMessage(api, m)).filter(Boolean);
292
+ return out.length ? out : null;
293
+ }
294
+ return handleMcpMessage(api, msg);
295
+ }
296
+
297
+ /** Decode an Mcp-Name / Mcp-Param-* header value ("=?base64?...?=" sentinel or plain ASCII). */
298
+ function decodeHeaderValue(v) {
299
+ const m = /^=\?base64\?([A-Za-z0-9+/=]*)\?=$/.exec(v);
300
+ if (!m) return v;
301
+ try {
302
+ return new TextDecoder('utf-8', { fatal: true }).decode(Uint8Array.from(atob(m[1]), (c) => c.charCodeAt(0)));
303
+ } catch {
304
+ return null;
305
+ }
306
+ }
307
+
308
+ /**
309
+ * Streamable HTTP POST /mcp, shared by server.ts and the Cloudflare worker.
310
+ * Stateless: every request is answered with plain JSON, notifications with 202.
311
+ * @param {string} text the request body
312
+ * @param {(name: string) => string | null | undefined} header case-insensitive header lookup
313
+ * @returns {{ status: number, body: unknown }} body null means "no body"
314
+ */
315
+ export function handleMcpHttp(api, text, header) {
316
+ let msg;
317
+ try {
318
+ msg = JSON.parse(text);
319
+ } catch {
320
+ return { status: 400, body: { jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } } };
321
+ }
322
+ const mismatch = (message) => ({
323
+ status: 400,
324
+ body: { jsonrpc: '2.0', id: msg && typeof msg === 'object' && 'id' in msg ? msg.id : null, error: { code: HEADER_MISMATCH, message } },
325
+ });
326
+
327
+ // Modern request: the mirrored headers must be present and match the body.
328
+ if (!Array.isArray(msg) && isModernRequest(msg)) {
329
+ const version = requestedVersion(msg);
330
+ const hv = header('mcp-protocol-version');
331
+ if (!hv) return mismatch('Header mismatch: MCP-Protocol-Version header is required');
332
+ if (typeof version === 'string' && hv !== version) {
333
+ return mismatch(`Header mismatch: MCP-Protocol-Version header value '${hv}' does not match body value '${version}'`);
334
+ }
335
+ const hm = header('mcp-method');
336
+ if (!hm) return mismatch('Header mismatch: Mcp-Method header is required');
337
+ if (hm !== msg.method) return mismatch(`Header mismatch: Mcp-Method header value '${hm}' does not match body value '${msg.method}'`);
338
+ if (msg.method === 'tools/call') {
339
+ const raw = header('mcp-name');
340
+ if (!raw) return mismatch('Header mismatch: Mcp-Name header is required for tools/call');
341
+ const name = decodeHeaderValue(raw);
342
+ if (name === null) return mismatch('Header mismatch: Mcp-Name header is not valid Base64 UTF-8');
343
+ if (name !== (msg.params && msg.params.name)) return mismatch('Header mismatch: Mcp-Name header does not match params.name');
344
+ }
345
+ const answer = handleMcpMessage(api, msg);
346
+ if (!answer) return { status: 202, body: null };
347
+ if (!answer.error) return { status: 200, body: answer };
348
+ const { code } = answer.error;
349
+ return { status: code === -32601 ? 404 : code === -32603 ? 500 : 400, body: answer };
350
+ }
351
+
352
+ // Legacy (initialize handshake) revisions: as before, JSON-RPC errors ride on 200,
353
+ // except an MCP-Protocol-Version header this server cannot speak.
354
+ const hv = header('mcp-protocol-version');
355
+ if (hv && !SUPPORTED_PROTOCOLS.includes(hv)) {
356
+ return {
357
+ status: 400,
358
+ body: {
359
+ jsonrpc: '2.0',
360
+ id: msg && typeof msg === 'object' && 'id' in msg ? msg.id : null,
361
+ error: { code: UNSUPPORTED_PROTOCOL_VERSION, message: 'Unsupported protocol version', data: { supported: SUPPORTED_PROTOCOLS, requested: hv } },
362
+ },
363
+ };
364
+ }
365
+ const answer = Array.isArray(msg)
366
+ ? (() => { const out = msg.map((m) => handleMcpMessage(api, m)).filter(Boolean); return out.length ? out : null; })()
367
+ : handleMcpMessage(api, msg);
368
+ return answer ? { status: 200, body: answer } : { status: 202, body: null };
369
+ }
370
+
371
+ export { TOOLS, SUPPORTED_PROTOCOLS, MODERN_PROTOCOLS, LEGACY_PROTOCOLS };
package/bin/mcp.mjs ADDED
@@ -0,0 +1,27 @@
1
+ // guessit-js MCP server on stdio: lets AI agents (Claude, Cursor, VS Code, any MCP
2
+ // client) call guessit as a tool. Newline-delimited JSON-RPC 2.0 on stdin/stdout.
3
+ //
4
+ // npx -y guessit-js --mcp
5
+ //
6
+ // stdout carries protocol messages only; anything else goes to stderr.
7
+
8
+ import { createInterface } from 'node:readline';
9
+ import { handleMcpPayload } from './mcp-core.mjs';
10
+
11
+ /** In-process there is no HTTP request to bound, only a sanity cap. */
12
+ const STDIO_MAX_BATCH = 1000;
13
+
14
+ /**
15
+ * Run the MCP server on stdin/stdout until stdin closes.
16
+ * @param {{ guessit: Function, guessitMany: Function, properties: Function, version: string }} api
17
+ */
18
+ export function runMcpServer(api, { input = process.stdin, output = process.stdout } = {}) {
19
+ const surface = { maxBatch: STDIO_MAX_BATCH, ...api };
20
+ const rl = createInterface({ input, crlfDelay: Infinity });
21
+ rl.on('line', (line) => {
22
+ if (!line.trim()) return;
23
+ const answer = handleMcpPayload(surface, line);
24
+ if (answer) output.write(JSON.stringify(answer) + '\n');
25
+ });
26
+ return rl;
27
+ }