guessit-js 5.1.0 → 5.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
@@ -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,42 @@ 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
+ **Local (stdio)**, no server to run:
270
+
271
+ ```bash
272
+ claude mcp add guessit -- npx -y guessit-js --mcp # Claude Code
273
+ ```
274
+
275
+ ```json
276
+ { "mcpServers": { "guessit": { "command": "npx", "args": ["-y", "guessit-js", "--mcp"] } } }
277
+ ```
278
+
279
+ (Claude Desktop `claude_desktop_config.json`, Cursor `.cursor/mcp.json`, VS Code
280
+ `.vscode/mcp.json` with `"servers"` instead of `"mcpServers"`.)
281
+
282
+ **Remote (Streamable HTTP)**, nothing to install: `https://guessit.opensubtitles.com/mcp`
283
+ (demo tier, same limits as the hosted API), or `POST /mcp` on a self-hosted
284
+ `npm start` server.
285
+
286
+ ```bash
287
+ claude mcp add --transport http guessit https://guessit.opensubtitles.com/mcp
288
+ ```
289
+
290
+ For language models reading about the project: [`llms.txt`](https://opensubtitles.github.io/guessit-js/llms.txt)
291
+ (also at `/llms.txt` on the hosted API) and the [OpenAPI spec](https://opensubtitles.github.io/guessit-js/openapi.json).
292
+
256
293
  ## WASM
257
294
 
258
295
  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,185 @@
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
+ const SUPPORTED_PROTOCOLS = ['2025-06-18', '2025-03-26', '2024-11-05'];
7
+ const MAX_FILENAME_LENGTH = 4096;
8
+
9
+ const OPTIONS_SCHEMA = {
10
+ type: 'object',
11
+ description:
12
+ 'Optional guessit options, as in the library and Python guessit: type ("movie" | "episode"), '
13
+ + 'output ("python" default: language/country as names like "French"; "codes": {"alpha3": "fra"} '
14
+ + 'objects that keep regions such as pt-BR), expected_title, allowed_languages, allowed_countries, '
15
+ + 'name_only, date_day_first, date_year_first, excludes, includes.',
16
+ additionalProperties: true,
17
+ };
18
+
19
+ const TOOLS = [
20
+ {
21
+ name: 'guessit',
22
+ title: 'Parse a media filename',
23
+ description:
24
+ 'Extract metadata from one movie or TV episode filename or release name: title, year, '
25
+ + 'season, episode, episode_title, screen_size, source, video_codec, audio_codec, language, '
26
+ + 'subtitle_language, release_group, streaming_service, container, type (movie or episode) and '
27
+ + 'more (56 properties). Output matches Python guessit\'s JSON. Pass just the file name or a '
28
+ + 'full path; directory names help (e.g. "Show/Season 2/episode.mkv").',
29
+ inputSchema: {
30
+ type: 'object',
31
+ properties: {
32
+ filename: { type: 'string', description: 'Filename, path or release name, e.g. "The.Matrix.1999.1080p.BluRay.x264-GRP.mkv"' },
33
+ options: OPTIONS_SCHEMA,
34
+ },
35
+ required: ['filename'],
36
+ additionalProperties: false,
37
+ },
38
+ annotations: { readOnlyHint: true, openWorldHint: false, idempotentHint: true },
39
+ },
40
+ {
41
+ name: 'guessit_batch',
42
+ title: 'Parse many media filenames',
43
+ description:
44
+ 'Parse many filenames in one call with the same options. Returns one entry per '
45
+ + 'name, in order: {input_string, result} or {input_string, error}. Faster than calling '
46
+ + 'guessit repeatedly.',
47
+ inputSchema: {
48
+ type: 'object',
49
+ properties: {
50
+ filenames: { type: 'array', items: { type: 'string' }, minItems: 1 },
51
+ options: OPTIONS_SCHEMA,
52
+ },
53
+ required: ['filenames'],
54
+ additionalProperties: false,
55
+ },
56
+ annotations: { readOnlyHint: true, openWorldHint: false, idempotentHint: true },
57
+ },
58
+ {
59
+ name: 'guessit_properties',
60
+ title: 'List guessit properties',
61
+ description:
62
+ 'List every property guessit can return with its possible values (enum values such as '
63
+ + 'source: ["Blu-ray", "Web", ...]; [null] for free-form ones such as title).',
64
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
65
+ annotations: { readOnlyHint: true, openWorldHint: false, idempotentHint: true },
66
+ },
67
+ ];
68
+
69
+ /** The tool list, with the batch limit of the surface serving it. */
70
+ function toolsFor(api) {
71
+ return TOOLS.map((t) => (t.name !== 'guessit_batch' ? t : {
72
+ ...t,
73
+ description: t.description.replace('many filenames', `up to ${api.maxBatch} filenames`),
74
+ inputSchema: {
75
+ ...t.inputSchema,
76
+ properties: {
77
+ ...t.inputSchema.properties,
78
+ filenames: { ...t.inputSchema.properties.filenames, maxItems: api.maxBatch },
79
+ },
80
+ },
81
+ }));
82
+ }
83
+
84
+ function toolResult(value) {
85
+ // structuredContent must be an object; batch results are wrapped.
86
+ const structured = Array.isArray(value) ? { results: value } : value;
87
+ return {
88
+ content: [{ type: 'text', text: JSON.stringify(value) }],
89
+ structuredContent: structured,
90
+ };
91
+ }
92
+
93
+ function toolError(message) {
94
+ return { content: [{ type: 'text', text: message }], isError: true };
95
+ }
96
+
97
+ function validOptions(options) {
98
+ if (options === undefined) return {};
99
+ if (!options || typeof options !== 'object' || Array.isArray(options)) {
100
+ throw new Error('options must be an object');
101
+ }
102
+ return options;
103
+ }
104
+
105
+ /**
106
+ * Answer one JSON-RPC message. Returns the response object, or null when the
107
+ * message is a notification (or anything else that takes no answer).
108
+ * @param {{ guessit: Function, guessitMany: Function, properties: Function, version: string }} api
109
+ */
110
+ export function handleMcpMessage(api, msg) {
111
+ const reply = (id, result) => ({ jsonrpc: '2.0', id, result });
112
+ const fail = (id, code, message) => ({ jsonrpc: '2.0', id, error: { code, message } });
113
+
114
+ function callTool(name, args) {
115
+ args = args ?? {};
116
+ try {
117
+ if (name === 'guessit') {
118
+ if (typeof args.filename !== 'string' || !args.filename) return toolError('filename (string) is required');
119
+ if (args.filename.length > MAX_FILENAME_LENGTH) return toolError(`filename exceeds ${MAX_FILENAME_LENGTH} characters`);
120
+ return toolResult(api.guessit(args.filename, validOptions(args.options)));
121
+ }
122
+ if (name === 'guessit_batch') {
123
+ const names = args.filenames;
124
+ if (!Array.isArray(names) || names.length === 0) return toolError('filenames (non-empty array of strings) is required');
125
+ if (names.length > api.maxBatch) return toolError(`at most ${api.maxBatch} filenames per call`);
126
+ const strings = names.map(String);
127
+ if (strings.some((f) => f.length > MAX_FILENAME_LENGTH)) return toolError(`filename exceeds ${MAX_FILENAME_LENGTH} characters`);
128
+ return toolResult(api.guessitMany(strings, validOptions(args.options)));
129
+ }
130
+ if (name === 'guessit_properties') return toolResult(api.properties());
131
+ } catch (e) {
132
+ return toolError(String((e && e.message) || e));
133
+ }
134
+ return null;
135
+ }
136
+
137
+ if (!msg || typeof msg !== 'object' || msg.jsonrpc !== '2.0' || typeof msg.method !== 'string') {
138
+ return msg && typeof msg === 'object' && msg.id !== undefined ? fail(msg.id, -32600, 'Invalid Request') : null;
139
+ }
140
+ const { id, method, params } = msg;
141
+ const isNotification = id === undefined || id === null;
142
+ switch (method) {
143
+ case 'initialize': {
144
+ const requested = params && params.protocolVersion;
145
+ return reply(id, {
146
+ protocolVersion: SUPPORTED_PROTOCOLS.includes(requested) ? requested : SUPPORTED_PROTOCOLS[0],
147
+ capabilities: { tools: { listChanged: false } },
148
+ serverInfo: { name: 'guessit-js', title: 'guessit-js', version: api.version },
149
+ instructions:
150
+ 'guessit-js extracts metadata (title, year, season, episode, resolution, codecs, '
151
+ + 'languages, release group, ...) from movie and TV filenames. Use guessit for one '
152
+ + 'name, guessit_batch for many. Output matches Python guessit; pass '
153
+ + 'options.output="codes" for ISO language codes with regions.',
154
+ });
155
+ }
156
+ case 'ping':
157
+ return isNotification ? null : reply(id, {});
158
+ case 'tools/list':
159
+ return reply(id, { tools: toolsFor(api) });
160
+ case 'tools/call': {
161
+ const result = callTool(params && params.name, params && params.arguments);
162
+ return result === null ? fail(id, -32602, `Unknown tool: ${params && params.name}`) : reply(id, result);
163
+ }
164
+ default:
165
+ // Notifications (notifications/initialized, cancelled, ...) take no answer.
166
+ return isNotification ? null : fail(id, -32601, `Method not found: ${method}`);
167
+ }
168
+ }
169
+
170
+ /** Parse one transport payload (a message or a JSON-RPC batch) and answer it. */
171
+ export function handleMcpPayload(api, text) {
172
+ let msg;
173
+ try {
174
+ msg = JSON.parse(text);
175
+ } catch {
176
+ return { jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } };
177
+ }
178
+ if (Array.isArray(msg)) {
179
+ const out = msg.map((m) => handleMcpMessage(api, m)).filter(Boolean);
180
+ return out.length ? out : null;
181
+ }
182
+ return handleMcpMessage(api, msg);
183
+ }
184
+
185
+ export { TOOLS };
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
+ }