filecheck-mcp 0.1.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/dist/cli.js ADDED
@@ -0,0 +1,1007 @@
1
+ #!/usr/bin/env node
2
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
3
+ import { Filecheck, isTerminal, AuthenticationError, InvalidRequestError, NotFoundError, RateLimitError, ConnectionError, FilecheckError } from 'filecheck-node';
4
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
5
+ import { stat, mkdir, writeFile, readFile } from 'fs/promises';
6
+ import { join, dirname, basename, extname } from 'path';
7
+ import { z } from 'zod';
8
+
9
+ // src/capabilities.ts
10
+ var LOCAL_CAPABILITIES = { localFiles: true, maxWaitMs: 18e4 };
11
+ var FINDINGS_LIMIT = 20;
12
+ var PAGES_LIMIT = 20;
13
+ var FINDING_KEYS_HANDLED = /* @__PURE__ */ new Set([
14
+ "locate",
15
+ "autofix",
16
+ "overlay",
17
+ "sectionId",
18
+ "ruleId",
19
+ "severity"
20
+ ]);
21
+ function jsonResult(structured, text) {
22
+ return { content: [{ type: "text", text }], structuredContent: structured };
23
+ }
24
+ function compactFinding(finding) {
25
+ const autofix = finding.autofix;
26
+ const out = {
27
+ sectionId: finding.sectionId,
28
+ ruleId: finding.ruleId,
29
+ severity: finding.severity,
30
+ autofixable: autofix?.available === true
31
+ };
32
+ for (const [key2, value] of Object.entries(finding)) {
33
+ if (FINDING_KEYS_HANDLED.has(key2) || value === void 0) continue;
34
+ if (value === null || ["string", "number", "boolean"].includes(typeof value)) out[key2] = value;
35
+ }
36
+ return out;
37
+ }
38
+ function compactArtifact(artifact) {
39
+ const { bucket: _bucket, key: _key, ...rest } = artifact;
40
+ return rest;
41
+ }
42
+ function evaluationOf(result) {
43
+ const report = result.report;
44
+ return report?.evaluation ?? null;
45
+ }
46
+ function verdictText(job, pending) {
47
+ if (pending) return `Job ${job.id} is still processing (status: ${job.status}).`;
48
+ if (job.status === "error") {
49
+ return "Processing failed \u2014 the file could not be checked. This is an execution error, not a verdict on the file.";
50
+ }
51
+ if (job.status === "skipped") return "Processing was skipped (unsupported for this file type).";
52
+ switch (job.outcome) {
53
+ case "pass":
54
+ return "File is print-ready.";
55
+ case "warn":
56
+ return "File is usable with warnings \u2014 review the findings.";
57
+ case "fail":
58
+ return "Check completed successfully, but the file is NOT print-ready \u2014 see findings.";
59
+ case "fixed":
60
+ return "File had issues that were fixed automatically \u2014 use the fixed deliverable, not the original.";
61
+ case "unchanged":
62
+ return "Autofix ran but the file needed no changes.";
63
+ case "mixed":
64
+ return "Files in this job have differing verdicts \u2014 check each file.";
65
+ default:
66
+ return "Completed (no verdict for this operation).";
67
+ }
68
+ }
69
+ function formatJobResult(run) {
70
+ const { job, pending } = run;
71
+ const verdict = verdictText(job, pending);
72
+ const structured = {
73
+ jobId: job.id,
74
+ status: job.status,
75
+ outcome: job.outcome ?? null,
76
+ verdict
77
+ };
78
+ if (pending) {
79
+ structured.pending = true;
80
+ structured.nextStep = `Wait a few seconds, then call get_job with jobId "${job.id}". Do NOT submit the file again \u2014 the job is already running.`;
81
+ return jsonResult(structured, `${verdict} ${structured.nextStep}`);
82
+ }
83
+ const notes = [];
84
+ let findingsBudget = FINDINGS_LIMIT;
85
+ let truncated = false;
86
+ const preflights = job.results?.preflight ?? [];
87
+ if (preflights.length > 0) {
88
+ structured.files = preflights.map((result) => {
89
+ const file = {
90
+ taskId: result.taskId,
91
+ source: result.source,
92
+ fileType: result.fileType,
93
+ status: result.status,
94
+ outcome: result.outcome ?? null
95
+ };
96
+ const evaluation = evaluationOf(result);
97
+ if (!evaluation) {
98
+ file.hasEvaluation = false;
99
+ file.note = "No profile was applied, so there is no pass/fail evaluation \u2014 use get_report to inspect the raw report.";
100
+ return file;
101
+ }
102
+ file.summary = evaluation.summary;
103
+ const findings = evaluation.findings ?? [];
104
+ const kept = findings.slice(0, Math.max(0, findingsBudget));
105
+ findingsBudget -= kept.length;
106
+ file.findings = kept.map(compactFinding);
107
+ if (kept.length < findings.length) {
108
+ file.findingsOmitted = findings.length - kept.length;
109
+ truncated = true;
110
+ }
111
+ if (evaluation.recommendedAutofix) file.recommendedAutofix = evaluation.recommendedAutofix;
112
+ return file;
113
+ });
114
+ if (truncated) {
115
+ structured.findingsTruncated = true;
116
+ notes.push("Findings were capped \u2014 use get_report for the full list.");
117
+ }
118
+ }
119
+ const validates = job.results?.validate ?? [];
120
+ if (validates.length > 0) {
121
+ structured.validate = validates.map((result) => ({
122
+ taskId: result.taskId,
123
+ source: result.source,
124
+ status: result.status,
125
+ outcome: result.outcome ?? null,
126
+ compliant: result.compliant,
127
+ profiles: result.profiles.map((profile) => ({
128
+ requested: profile.requested,
129
+ matched: profile.matched,
130
+ profileName: profile.profileName,
131
+ compliant: profile.compliant,
132
+ checks: profile.checks,
133
+ rules: profile.rules,
134
+ failureCount: profile.failures.length,
135
+ failures: profile.failures.slice(0, 10)
136
+ }))
137
+ }));
138
+ }
139
+ const optimizes = job.results?.optimize ?? [];
140
+ if (optimizes.length > 0) {
141
+ structured.optimize = optimizes.map((result) => ({
142
+ taskId: result.taskId,
143
+ source: result.source,
144
+ status: result.status,
145
+ outcome: result.outcome ?? null,
146
+ output: result.output ? {
147
+ sizeBytes: result.output.sizeBytes,
148
+ downloadUrl: result.output.downloadUrl,
149
+ expiresIn: result.output.expiresIn,
150
+ appliedFixes: result.output.appliedFixes,
151
+ skippedFixes: result.output.skippedFixes
152
+ } : null
153
+ }));
154
+ }
155
+ const previews = [];
156
+ for (const task of job.tasks) {
157
+ for (const step of task.steps) {
158
+ if (step.type !== "previews" || !step.outputs?.length) continue;
159
+ for (const output of step.outputs) {
160
+ const pages = Array.isArray(output.pages) ? output.pages : [];
161
+ previews.push({
162
+ taskId: task.id,
163
+ count: output.count,
164
+ total: output.total,
165
+ pages: pages.slice(0, PAGES_LIMIT),
166
+ ...pages.length > PAGES_LIMIT ? { pagesOmitted: pages.length - PAGES_LIMIT } : {}
167
+ });
168
+ }
169
+ }
170
+ }
171
+ if (previews.length > 0) structured.previews = previews;
172
+ if (job.deliverables.length > 0) {
173
+ structured.deliverables = job.deliverables.map(compactArtifact);
174
+ notes.push(
175
+ `${job.deliverables.length} deliverable(s); download URLs expire in ~60 minutes \u2014 re-call get_job for fresh ones.`
176
+ );
177
+ }
178
+ const text = [
179
+ `${verdict} (status: ${job.status}, outcome: ${job.outcome ?? "n/a"}, jobId: ${job.id})`,
180
+ ...notes
181
+ ].join(" ");
182
+ return jsonResult(structured, text);
183
+ }
184
+ function toolErrorResult(error) {
185
+ return { content: [{ type: "text", text: errorText(error) }], isError: true };
186
+ }
187
+ function errorText(error) {
188
+ if (error instanceof AuthenticationError) {
189
+ if (error.status === 403) {
190
+ return `Forbidden: ${error.message}. A 403 usually means the fileRef was uploaded with a different API key \u2014 re-upload the file with this key and use the new fileRef.`;
191
+ }
192
+ return `Authentication failed: ${error.message}. Check the API key (FILECHECK_API_KEY for the local server, the Authorization header for the remote one) \u2014 it must be an active sk_\u2026 secret key.`;
193
+ }
194
+ if (error instanceof InvalidRequestError) {
195
+ return `Invalid request: ${error.message}`;
196
+ }
197
+ if (error instanceof NotFoundError) {
198
+ return `Not found: ${error.message}. Check the id \u2014 jobs are also soft-deleted by delete_job and expire per retention.`;
199
+ }
200
+ if (error instanceof RateLimitError) {
201
+ return `Rate limited: ${error.message}. Back off and retry.`;
202
+ }
203
+ if (error instanceof ConnectionError) {
204
+ return `Network failure talking to the Filecheck API: ${error.message}. Retry once; if it persists, check connectivity.`;
205
+ }
206
+ if (error instanceof FilecheckError) {
207
+ if (error.status === 402) {
208
+ return `Submissions are paused for this account (billing): ${error.message}. Top up credit in the Filecheck dashboard, then retry.`;
209
+ }
210
+ return `Filecheck API error${error.status ? ` (${error.status})` : ""}: ${error.message}`;
211
+ }
212
+ return error instanceof Error ? error.message : String(error);
213
+ }
214
+
215
+ // src/tools/artifact.ts
216
+ function describeDeliverables(deliverables) {
217
+ return deliverables.map(
218
+ (d, i) => `[${i}] ${d.fileName ?? d.kind ?? d.role ?? "unnamed"} (${d.mimeType ?? "unknown type"})`
219
+ ).join(", ");
220
+ }
221
+ function pickDeliverable(deliverables, selector) {
222
+ if (selector === void 0) return deliverables.length === 1 ? deliverables[0] ?? null : null;
223
+ if (typeof selector === "number") return deliverables[selector] ?? null;
224
+ return deliverables.find((d) => d.fileName === selector) ?? deliverables.find((d) => d.kind === selector || d.role === selector) ?? null;
225
+ }
226
+ function registerSaveArtifact(server, { client }) {
227
+ server.registerTool(
228
+ "save_artifact",
229
+ {
230
+ title: "Save a deliverable to disk",
231
+ description: "Download one of a job's deliverables (fixed file, optimized file, report, \u2026) to a local path. Re-fetches the job first so the download URL is fresh \u2014 pass the jobId, not a URL.",
232
+ inputSchema: {
233
+ jobId: z.string().describe("The job_\u2026 id whose deliverable to save."),
234
+ deliverable: z.union([z.number().int().min(0), z.string()]).optional().describe(
235
+ "Index, fileName, kind, or role of the deliverable. Optional when the job has exactly one."
236
+ ),
237
+ outPath: z.string().describe(
238
+ "Where to save: a file path, or an existing directory (the deliverable fileName is appended)."
239
+ )
240
+ },
241
+ outputSchema: {
242
+ savedTo: z.string(),
243
+ bytes: z.number(),
244
+ mimeType: z.string().nullable().optional()
245
+ },
246
+ annotations: {
247
+ readOnlyHint: false,
248
+ destructiveHint: false,
249
+ idempotentHint: true,
250
+ openWorldHint: true
251
+ }
252
+ },
253
+ async (args) => {
254
+ try {
255
+ const job = await client.jobs.retrieve(args.jobId);
256
+ if (job.deliverables.length === 0) {
257
+ return toolErrorResult(
258
+ new Error(
259
+ `Job ${args.jobId} has no deliverables (status: ${job.status}, outcome: ${job.outcome ?? "n/a"}).`
260
+ )
261
+ );
262
+ }
263
+ const chosen = pickDeliverable(job.deliverables, args.deliverable);
264
+ if (!chosen) {
265
+ return toolErrorResult(
266
+ new Error(
267
+ `Could not pick a deliverable${args.deliverable !== void 0 ? ` matching '${args.deliverable}'` : " \u2014 the job has several"}. Available: ${describeDeliverables(job.deliverables)}. Pass one as 'deliverable'.`
268
+ )
269
+ );
270
+ }
271
+ if (!chosen.downloadUrl) {
272
+ return toolErrorResult(
273
+ new Error("The selected deliverable has no download URL on a fresh read.")
274
+ );
275
+ }
276
+ const response = await fetch(chosen.downloadUrl);
277
+ if (!response.ok) {
278
+ return toolErrorResult(new Error(`Download failed with status ${response.status}.`));
279
+ }
280
+ const bytes = Buffer.from(await response.arrayBuffer());
281
+ let target = args.outPath;
282
+ const existing = await stat(target).catch(() => null);
283
+ if (existing?.isDirectory()) {
284
+ target = join(target, chosen.fileName ?? `${args.jobId}-deliverable`);
285
+ } else {
286
+ await mkdir(dirname(target), { recursive: true });
287
+ }
288
+ await writeFile(target, bytes);
289
+ return jsonResult(
290
+ { savedTo: target, bytes: bytes.length, mimeType: chosen.mimeType ?? null },
291
+ `Saved ${chosen.fileName ?? "deliverable"} (${bytes.length} bytes) to ${target}.`
292
+ );
293
+ } catch (error) {
294
+ return toolErrorResult(error);
295
+ }
296
+ }
297
+ );
298
+ }
299
+ var CATALOG_TYPES = ["profiles", "rules", "workflows", "connectors", "optimize-presets"];
300
+ function compactItem(item) {
301
+ const out = { id: item.id };
302
+ for (const key2 of ["title", "name", "kind", "description", "enabled", "source"]) {
303
+ const value = item[key2];
304
+ if (value === null || ["string", "number", "boolean"].includes(typeof value)) out[key2] = value;
305
+ }
306
+ return out;
307
+ }
308
+ function registerListCatalog(server, { client }) {
309
+ const resources = {
310
+ profiles: client.profiles,
311
+ rules: client.rules,
312
+ workflows: client.workflows,
313
+ connectors: client.connectors,
314
+ "optimize-presets": client.optimizePresets
315
+ };
316
+ server.registerTool(
317
+ "list_catalog",
318
+ {
319
+ title: "Browse the resource catalog",
320
+ description: "Browse the tenant's resource catalog: preflight `profiles` (check-sets for check_file/fix_file), intake `rules`, `workflows`, `connectors`, and `optimize-presets` (params objects for optimize_file). Entries tagged source:'domain' are the tenant's own; source:'store' are Filecheck built-ins. Pass `id` for the full definition of one entry.",
321
+ inputSchema: {
322
+ type: z.enum(CATALOG_TYPES).describe("Which collection to browse."),
323
+ id: z.string().optional().describe("Fetch one entry in full instead of listing.")
324
+ },
325
+ outputSchema: {
326
+ type: z.string(),
327
+ items: z.array(z.object({}).passthrough()).optional().describe("Compact listing (no id given)."),
328
+ item: z.object({}).passthrough().optional().describe("Full entry (id given).")
329
+ },
330
+ annotations: { readOnlyHint: true, openWorldHint: true }
331
+ },
332
+ async (args) => {
333
+ try {
334
+ const resource = resources[args.type];
335
+ if (args.id) {
336
+ const item = await resource.retrieve(args.id);
337
+ return jsonResult({ type: args.type, item }, `${args.type} entry ${args.id}.`);
338
+ }
339
+ const items = (await resource.list()).map(compactItem);
340
+ return jsonResult(
341
+ { type: args.type, items },
342
+ `${items.length} ${args.type} entr${items.length === 1 ? "y" : "ies"}. Pass an id for the full definition.`
343
+ );
344
+ } catch (error) {
345
+ return toolErrorResult(error);
346
+ }
347
+ }
348
+ );
349
+ }
350
+ var MAX_LOCAL_BYTES = 200 * 1024 * 1024;
351
+ var MIME_BY_EXT = {
352
+ ".pdf": "application/pdf",
353
+ ".png": "image/png",
354
+ ".jpg": "image/jpeg",
355
+ ".jpeg": "image/jpeg",
356
+ ".tif": "image/tiff",
357
+ ".tiff": "image/tiff",
358
+ ".webp": "image/webp",
359
+ ".svg": "image/svg+xml",
360
+ ".eps": "application/postscript",
361
+ ".ai": "application/postscript",
362
+ ".zip": "application/zip"
363
+ };
364
+ async function resolveSource(client, caps, source) {
365
+ const locators = [
366
+ caps.localFiles && source.filePath ? "filePath" : null,
367
+ source.url ? "url" : null,
368
+ source.fileRef ? "fileRef" : null
369
+ ].filter(Boolean);
370
+ if (locators.length !== 1) {
371
+ const allowed = caps.localFiles ? "filePath, url, or fileRef" : "url or fileRef";
372
+ throw new Error(
373
+ locators.length === 0 ? `source needs exactly one of ${allowed} \u2014 none was provided.` : `source needs exactly one of ${allowed} \u2014 got ${locators.join(" + ")}.`
374
+ );
375
+ }
376
+ if (source.filePath && caps.localFiles) {
377
+ const info = await stat(source.filePath).catch(() => null);
378
+ if (!info?.isFile()) {
379
+ throw new Error(`filePath not found or not a file: ${source.filePath}`);
380
+ }
381
+ if (info.size > MAX_LOCAL_BYTES) {
382
+ throw new Error(
383
+ `File is ${Math.round(info.size / 1024 / 1024)} MB; filePath uploads are capped at ${MAX_LOCAL_BYTES / 1024 / 1024} MB. Host the file and pass a url source instead.`
384
+ );
385
+ }
386
+ const fileName = source.name ?? basename(source.filePath);
387
+ const upload = await client.uploads.create(await readFile(source.filePath), {
388
+ fileName,
389
+ mimeType: MIME_BY_EXT[extname(source.filePath).toLowerCase()]
390
+ });
391
+ return { fileRef: upload.fileRef, name: fileName };
392
+ }
393
+ if (source.url) {
394
+ return {
395
+ url: source.url,
396
+ ...source.headers ? { headers: source.headers } : {},
397
+ ...source.name ? { name: source.name } : {}
398
+ };
399
+ }
400
+ return { fileRef: source.fileRef, ...source.name ? { name: source.name } : {} };
401
+ }
402
+ var SYNC_HOLD_THRESHOLD_MS = 3e4;
403
+ var POLL_MIN_MS = 500;
404
+ var POLL_MAX_MS = 2e3;
405
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
406
+ async function submitAndWait(client, caps, submit, waitSeconds) {
407
+ const budgetMs = Math.min(
408
+ waitSeconds !== void 0 ? waitSeconds * 1e3 : caps.maxWaitMs,
409
+ caps.maxWaitMs
410
+ );
411
+ const deadline = Date.now() + budgetMs;
412
+ const useSync = budgetMs >= SYNC_HOLD_THRESHOLD_MS;
413
+ const { job } = await submit(
414
+ useSync ? { wait: true, waitTimeoutMs: budgetMs } : { wait: false, waitTimeoutMs: 0 }
415
+ );
416
+ let final = job;
417
+ if (isTerminal(final)) {
418
+ final = await client.jobs.retrieve(final.id);
419
+ } else if (Date.now() < deadline) {
420
+ final = await poll(client, final.id, deadline);
421
+ }
422
+ return { job: final, pending: !isTerminal(final) };
423
+ }
424
+ async function poll(client, id, deadline) {
425
+ let delay = POLL_MIN_MS;
426
+ let job = await client.jobs.retrieve(id);
427
+ while (!isTerminal(job) && Date.now() < deadline) {
428
+ await sleep(Math.min(delay, Math.max(0, deadline - Date.now())));
429
+ delay = Math.min(delay * 2, POLL_MAX_MS);
430
+ job = await client.jobs.retrieve(id);
431
+ }
432
+ return job;
433
+ }
434
+ function makeSourceSchema(caps) {
435
+ const shape = {
436
+ url: z.string().regex(/^https?:\/\//, "must be an http(s) URL").optional().describe("Public (or header-authenticated) URL to fetch the file from."),
437
+ fileRef: z.string().regex(/^upload_/, 'must start with "upload_"').optional().describe("An `upload_\u2026` reference from a previous upload with this same API key."),
438
+ headers: z.record(z.string()).optional().describe("Extra HTTP headers sent when fetching `url` (e.g. Authorization)."),
439
+ name: z.string().optional().describe("Original filename hint.")
440
+ };
441
+ if (caps.localFiles) {
442
+ shape.filePath = z.string().optional().describe("Absolute path to a file on the local machine (uploaded for you; max 200 MB).");
443
+ }
444
+ const which = caps.localFiles ? "`filePath`, `url`, or `fileRef`" : "`url` or `fileRef`";
445
+ const remoteHint = caps.localFiles ? "" : " For files on the local machine, run the local server instead: `npx filecheck-mcp`.";
446
+ return z.object(shape).describe(`The file to process. Set exactly one of ${which}.${remoteHint}`);
447
+ }
448
+ var bounded = (min, max) => z.number().int().min(min).max(max);
449
+ var contextSchema = z.object({
450
+ artworkSize: z.object({
451
+ width_mm: z.number().positive().max(1e5),
452
+ height_mm: z.number().positive().max(1e5)
453
+ }).optional().describe(
454
+ "Finished (trim) size of the product ordered. Both dimensions are required for the page-size check to take effect."
455
+ ),
456
+ pageCount: z.object({ min: bounded(0, 1e4).optional(), max: bounded(0, 1e4).optional() }).optional().describe(
457
+ "Expected page count. Set min === max for an exact count (a double-sided card is 2)."
458
+ ),
459
+ fileCount: z.object({ min: bounded(0, 100).optional(), max: bounded(0, 100).optional() }).optional().describe("Expected number of separate files. NOT the order quantity."),
460
+ bleed: z.object({ required_mm: z.number().min(0).max(500) }).optional().describe(
461
+ "Bleed the chosen finish requires (a hemmed banner needs more than a trimmed card)."
462
+ ),
463
+ safety: z.object({ min_mm: z.number().min(0).max(500) }).optional().describe("Safe margin the chosen finish requires (eyelets and pole pockets eat into it).")
464
+ }).describe(
465
+ "What the customer ordered \u2014 finished size, pages, finish. Narrows the resolved profile to the ordered product, so one profile serves every size. Only tightens checks the profile already has enabled; no effect without a profileId. Pass it whenever the product dimensions are known."
466
+ );
467
+ var waitSecondsSchema = z.number().int().min(0).max(600).optional().describe(
468
+ "Max seconds to wait for the job to finish before returning a pending result (capped by the server; 0 = return immediately). Omit for the default budget."
469
+ );
470
+ var jobOutputShape = {
471
+ jobId: z.string(),
472
+ status: z.string().describe(
473
+ "Execution lifecycle: pending | running | done | skipped | error. Says nothing about the verdict."
474
+ ),
475
+ outcome: z.string().nullable().optional().describe(
476
+ 'Verdict: pass | warn | fail | fixed | unchanged | na | mixed. Independent of status \u2014 status:done + outcome:fail means "checked successfully, file is NOT print-ready".'
477
+ ),
478
+ pending: z.boolean().optional().describe("True when the job has not reached a terminal status yet."),
479
+ verdict: z.string().describe("Human-readable one-line verdict."),
480
+ files: z.array(z.object({}).passthrough()).optional().describe("Per-file preflight results: summary, capped findings, recommended autofix."),
481
+ validate: z.array(z.object({}).passthrough()).optional().describe("PDF/A / PDF/UA conformance results."),
482
+ optimize: z.array(z.object({}).passthrough()).optional().describe("Optimization results."),
483
+ previews: z.array(z.object({}).passthrough()).optional().describe("Rendered page previews."),
484
+ deliverables: z.array(z.object({}).passthrough()).optional().describe(
485
+ "Final file set. downloadUrl expires in ~60 minutes \u2014 re-call get_job for fresh URLs, never store them."
486
+ ),
487
+ findingsTruncated: z.boolean().optional().describe("True when findings were capped; use get_report for the rest."),
488
+ nextStep: z.string().optional().describe("Present when action is needed (e.g. poll get_job). Follow it.")
489
+ };
490
+
491
+ // src/tools/check.ts
492
+ function registerCheckFile(server, { client, caps }) {
493
+ server.registerTool(
494
+ "check_file",
495
+ {
496
+ title: "Check (preflight) a print file",
497
+ description: "Check a file for print-readiness against a preflight profile. Returns a verdict with findings and a recommended autofix. READ THE TWO AXES: `status` is execution (done/error), `outcome` is the verdict \u2014 status:done + outcome:fail means the check completed and the file is NOT print-ready; do not treat done as success. Pass `context` whenever the ordered product dimensions are known. Omitting `profileId` runs every supported check but returns raw findings with no pass/fail verdict. If the result is pending, poll get_job \u2014 never resubmit.",
498
+ inputSchema: {
499
+ source: makeSourceSchema(caps),
500
+ profileId: z.string().optional().describe(
501
+ "Preflight profile id (discover via list_catalog type 'profiles'). Omit to run all checks with no verdict."
502
+ ),
503
+ ruleId: z.string().optional().describe(
504
+ "Intake rule id (list_catalog type 'rules'). When set, the rule's flow decides steps and profile per file type; profileId is then a fallback hint only."
505
+ ),
506
+ context: contextSchema.optional(),
507
+ waitSeconds: waitSecondsSchema
508
+ },
509
+ outputSchema: jobOutputShape,
510
+ annotations: {
511
+ readOnlyHint: false,
512
+ destructiveHint: false,
513
+ idempotentHint: false,
514
+ openWorldHint: true
515
+ }
516
+ },
517
+ async (args) => {
518
+ try {
519
+ const source = await resolveSource(client, caps, args.source);
520
+ const run = await submitAndWait(
521
+ client,
522
+ caps,
523
+ (wait) => args.ruleId ? client.jobs.create({
524
+ // POST /jobs requires steps per source; the rule overrides them.
525
+ sources: [
526
+ {
527
+ ...source,
528
+ steps: [
529
+ {
530
+ type: "preflight",
531
+ ...args.profileId ? { params: { profileId: args.profileId } } : {}
532
+ }
533
+ ]
534
+ }
535
+ ],
536
+ ruleId: args.ruleId,
537
+ ...args.context ? { context: args.context } : {},
538
+ ...wait
539
+ }) : client.jobs.preflight({
540
+ sources: [
541
+ { ...source, ...args.profileId ? { profileId: args.profileId } : {} }
542
+ ],
543
+ ...args.context ? { context: args.context } : {},
544
+ ...wait
545
+ }),
546
+ args.waitSeconds
547
+ );
548
+ return formatJobResult(run);
549
+ } catch (error) {
550
+ return toolErrorResult(error);
551
+ }
552
+ }
553
+ );
554
+ }
555
+ function registerFixFile(server, { client, caps }) {
556
+ server.registerTool(
557
+ "fix_file",
558
+ {
559
+ title: "Fix a print file automatically",
560
+ description: "Preflight a file, apply every safe automatic fix, and (by default) re-check the fixed output. The fixed file is returned as a deliverable \u2014 use IT, not the original. outcome:fixed means issues were repaired; outcome:fail after a repreflight means problems remain that autofix cannot solve. `status` is execution, `outcome` is the verdict \u2014 read both. If pending, poll get_job; never resubmit.",
561
+ inputSchema: {
562
+ source: makeSourceSchema(caps),
563
+ profileId: z.string().optional().describe(
564
+ "Preflight profile that decides what counts as a problem (list_catalog type 'profiles')."
565
+ ),
566
+ context: contextSchema.optional(),
567
+ repreflight: z.boolean().optional().describe("Re-run preflight on the fixed output to confirm the repair (default true)."),
568
+ waitSeconds: waitSecondsSchema
569
+ },
570
+ outputSchema: jobOutputShape,
571
+ annotations: {
572
+ readOnlyHint: false,
573
+ destructiveHint: false,
574
+ idempotentHint: false,
575
+ openWorldHint: true
576
+ }
577
+ },
578
+ async (args) => {
579
+ try {
580
+ const source = await resolveSource(client, caps, args.source);
581
+ const run = await submitAndWait(
582
+ client,
583
+ caps,
584
+ (wait) => client.jobs.fix({
585
+ sources: [{ ...source, ...args.profileId ? { profileId: args.profileId } : {} }],
586
+ repreflight: args.repreflight ?? true,
587
+ ...args.context ? { context: args.context } : {},
588
+ ...wait
589
+ }),
590
+ args.waitSeconds
591
+ );
592
+ return formatJobResult(run);
593
+ } catch (error) {
594
+ return toolErrorResult(error);
595
+ }
596
+ }
597
+ );
598
+ }
599
+ function registerJobTools(server, { client }) {
600
+ server.registerTool(
601
+ "get_job",
602
+ {
603
+ title: "Get a job (poll / refresh URLs)",
604
+ description: "Fetch a job by id: current status + outcome, per-file results, and FRESHLY SIGNED download URLs (~60 min TTL). This is both the polling target for pending jobs and the way to refresh expired download URLs. `status` is execution, `outcome` is the verdict \u2014 status:done + outcome:fail means checked successfully but NOT print-ready.",
605
+ inputSchema: {
606
+ jobId: z.string().describe("The job_\u2026 id returned by a submit tool.")
607
+ },
608
+ outputSchema: jobOutputShape,
609
+ annotations: { readOnlyHint: true, openWorldHint: true }
610
+ },
611
+ async (args) => {
612
+ try {
613
+ const job = await client.jobs.retrieve(args.jobId);
614
+ return formatJobResult({ job, pending: !isTerminal(job) });
615
+ } catch (error) {
616
+ return toolErrorResult(error);
617
+ }
618
+ }
619
+ );
620
+ server.registerTool(
621
+ "list_jobs",
622
+ {
623
+ title: "List recent jobs",
624
+ description: "List recent jobs (newest first) as lean envelopes: id, status, outcome, timestamps. Use get_job for details and download URLs. Pass the returned nextKey to fetch the next page.",
625
+ inputSchema: {
626
+ limit: z.number().int().min(1).max(100).optional().describe("Page size (default 20)."),
627
+ nextKey: z.string().optional().describe("Opaque pagination cursor from a previous call.")
628
+ },
629
+ outputSchema: {
630
+ jobs: z.array(z.object({}).passthrough()),
631
+ nextKey: z.string().nullable().optional().describe("Pass back to fetch the next page; absent on the last page.")
632
+ },
633
+ annotations: { readOnlyHint: true, openWorldHint: true }
634
+ },
635
+ async (args) => {
636
+ try {
637
+ const page = await client.jobs.list({ limit: args.limit ?? 20, nextKey: args.nextKey });
638
+ const jobs = page.jobs.map((job) => ({
639
+ jobId: job.id,
640
+ status: job.status,
641
+ outcome: job.outcome ?? null,
642
+ createdAt: job.createdAt,
643
+ channel: job.channel,
644
+ orderId: job.orderId,
645
+ fileCount: job.tasks.length
646
+ }));
647
+ const structured = { jobs };
648
+ if (page.nextKey) structured.nextKey = page.nextKey;
649
+ return jsonResult(
650
+ structured,
651
+ `${jobs.length} job(s)${page.nextKey ? " (more available via nextKey)" : ""}. Remember: outcome is the verdict, status is only execution.`
652
+ );
653
+ } catch (error) {
654
+ return toolErrorResult(error);
655
+ }
656
+ }
657
+ );
658
+ server.registerTool(
659
+ "delete_job",
660
+ {
661
+ title: "Delete a job",
662
+ description: "Soft-delete a job and its tasks. The job disappears from listings and its artifacts are scheduled for cleanup. Not undoable via the API.",
663
+ inputSchema: {
664
+ jobId: z.string().describe("The job_\u2026 id to delete.")
665
+ },
666
+ outputSchema: {
667
+ deleted: z.boolean(),
668
+ jobId: z.string(),
669
+ taskIds: z.array(z.string()).optional()
670
+ },
671
+ annotations: {
672
+ readOnlyHint: false,
673
+ destructiveHint: true,
674
+ idempotentHint: true,
675
+ openWorldHint: true
676
+ }
677
+ },
678
+ async (args) => {
679
+ try {
680
+ const result = await client.jobs.del(args.jobId);
681
+ return jsonResult(
682
+ {
683
+ deleted: true,
684
+ jobId: result.id,
685
+ ...result.taskIds ? { taskIds: result.taskIds } : {}
686
+ },
687
+ `Job ${result.id} deleted.`
688
+ );
689
+ } catch (error) {
690
+ return toolErrorResult(error);
691
+ }
692
+ }
693
+ );
694
+ }
695
+ function registerOptimizeFile(server, { client, caps }) {
696
+ server.registerTool(
697
+ "optimize_file",
698
+ {
699
+ title: "Optimize a file",
700
+ description: "Optimize a PDF or image: downsample and recompress images, strip dead weight, flatten. Options are namespaced under `params.pdf` and/or `params.raster` (see the schema at https://filecheck.io/docs/schemas/jobs-optimize-post.json). An optimize preset from list_catalog type 'optimize-presets' contains a ready-made params object you can pass through. The optimized file arrives as a deliverable with a download URL (~60 min TTL).",
701
+ inputSchema: {
702
+ source: makeSourceSchema(caps),
703
+ params: z.record(z.unknown()).optional().describe("Namespaced optimize options: `{ pdf: {\u2026}, raster: {\u2026} }`. Omit for defaults."),
704
+ waitSeconds: waitSecondsSchema
705
+ },
706
+ outputSchema: jobOutputShape,
707
+ annotations: {
708
+ readOnlyHint: false,
709
+ destructiveHint: false,
710
+ idempotentHint: false,
711
+ openWorldHint: true
712
+ }
713
+ },
714
+ async (args) => {
715
+ try {
716
+ const source = await resolveSource(client, caps, args.source);
717
+ const run = await submitAndWait(
718
+ client,
719
+ caps,
720
+ (wait) => client.jobs.optimize({ sources: [{ ...source, params: args.params ?? {} }], ...wait }),
721
+ args.waitSeconds
722
+ );
723
+ return formatJobResult(run);
724
+ } catch (error) {
725
+ return toolErrorResult(error);
726
+ }
727
+ }
728
+ );
729
+ }
730
+ function registerRenderPreviews(server, { client, caps }) {
731
+ server.registerTool(
732
+ "render_previews",
733
+ {
734
+ title: "Render page previews",
735
+ description: "Render raster preview images of a file's pages \u2014 useful to actually look at a file. Preview URLs ride in the `previews` output (capped at 20 pages per file) and expire like all download URLs (~60 min).",
736
+ inputSchema: {
737
+ source: makeSourceSchema(caps),
738
+ params: z.record(z.unknown()).optional().describe(
739
+ "Optional rendering options passed through to the previews engine (size, page range, format)."
740
+ ),
741
+ waitSeconds: waitSecondsSchema
742
+ },
743
+ outputSchema: jobOutputShape,
744
+ annotations: {
745
+ readOnlyHint: false,
746
+ destructiveHint: false,
747
+ idempotentHint: false,
748
+ openWorldHint: true
749
+ }
750
+ },
751
+ async (args) => {
752
+ try {
753
+ const source = await resolveSource(client, caps, args.source);
754
+ const run = await submitAndWait(
755
+ client,
756
+ caps,
757
+ (wait) => client.jobs.previews({
758
+ sources: [{ ...source, ...args.params ? { params: args.params } : {} }],
759
+ ...wait
760
+ }),
761
+ args.waitSeconds
762
+ );
763
+ return formatJobResult(run);
764
+ } catch (error) {
765
+ return toolErrorResult(error);
766
+ }
767
+ }
768
+ );
769
+ }
770
+ var SEVERITIES = ["reject", "warn", "ignore"];
771
+ function registerGetReport(server, { client }) {
772
+ server.registerTool(
773
+ "get_report",
774
+ {
775
+ title: "Read the raw preflight report",
776
+ description: "Drill into the full preflight report of a checked file \u2014 the raw analysis (pages, fonts, images, color, spot colors, layers, \u2026) plus the complete evaluation findings that job results cap. Call without `section` first for an overview of available sections and their sizes, then request one section at a time; array sections are paginated with offset/limit. `severity` filters the evaluation findings instead.",
777
+ inputSchema: {
778
+ jobId: z.string().describe("The job_\u2026 id of a completed check."),
779
+ taskIndex: z.number().int().min(0).optional().describe("Which file of the job (0-based, default 0) \u2014 jobs can contain several files."),
780
+ section: z.string().optional().describe(
781
+ "Report section to read (e.g. 'fonts', 'images', 'pages', 'evaluation'). Omit for the overview."
782
+ ),
783
+ severity: z.enum(SEVERITIES).optional().describe("Return only evaluation findings of this severity (overrides section)."),
784
+ offset: z.number().int().min(0).optional().describe("Pagination offset into array sections (default 0)."),
785
+ limit: z.number().int().min(1).max(200).optional().describe("Max array entries to return (default 50).")
786
+ },
787
+ outputSchema: {
788
+ jobId: z.string(),
789
+ taskIndex: z.number(),
790
+ section: z.string().optional(),
791
+ sections: z.array(z.object({}).passthrough()).optional().describe("Overview: available sections and sizes."),
792
+ data: z.unknown().optional().describe("The requested slice."),
793
+ total: z.number().optional(),
794
+ offset: z.number().optional(),
795
+ returned: z.number().optional()
796
+ },
797
+ annotations: { readOnlyHint: true, openWorldHint: true }
798
+ },
799
+ async (args) => {
800
+ try {
801
+ const job = await client.jobs.retrieve(args.jobId);
802
+ const preflights = job.results?.preflight ?? [];
803
+ const taskIndex = args.taskIndex ?? 0;
804
+ const result = preflights[taskIndex];
805
+ if (!result) {
806
+ return toolErrorResult(
807
+ new Error(
808
+ preflights.length === 0 ? `Job ${args.jobId} has no preflight results (status: ${job.status}). If it is still running, poll get_job first.` : `taskIndex ${taskIndex} is out of range \u2014 this job has ${preflights.length} preflighted file(s).`
809
+ )
810
+ );
811
+ }
812
+ const report = result.report;
813
+ if (!report) {
814
+ return toolErrorResult(
815
+ new Error(`No report is stored for file ${taskIndex} of job ${args.jobId}.`)
816
+ );
817
+ }
818
+ const offset = args.offset ?? 0;
819
+ const limit = args.limit ?? 50;
820
+ const base = { jobId: args.jobId, taskIndex };
821
+ if (args.severity) {
822
+ const evaluation = report.evaluation;
823
+ const findings = (evaluation?.findings ?? []).filter((f) => f.severity === args.severity);
824
+ const slice = findings.slice(offset, offset + limit);
825
+ return jsonResult(
826
+ {
827
+ ...base,
828
+ section: "evaluation.findings",
829
+ data: slice,
830
+ total: findings.length,
831
+ offset,
832
+ returned: slice.length
833
+ },
834
+ `${findings.length} ${args.severity} finding(s); returned ${slice.length} from offset ${offset}.`
835
+ );
836
+ }
837
+ if (args.section) {
838
+ if (!(args.section in report)) {
839
+ return toolErrorResult(
840
+ new Error(
841
+ `Section '${args.section}' not in this report. Available: ${Object.keys(report).join(", ")}.`
842
+ )
843
+ );
844
+ }
845
+ const value = report[args.section];
846
+ if (Array.isArray(value)) {
847
+ const slice = value.slice(offset, offset + limit);
848
+ return jsonResult(
849
+ {
850
+ ...base,
851
+ section: args.section,
852
+ data: slice,
853
+ total: value.length,
854
+ offset,
855
+ returned: slice.length
856
+ },
857
+ `Section '${args.section}': ${value.length} entries; returned ${slice.length} from offset ${offset}.`
858
+ );
859
+ }
860
+ return jsonResult(
861
+ { ...base, section: args.section, data: value },
862
+ `Section '${args.section}'.`
863
+ );
864
+ }
865
+ const sections = Object.entries(report).map(([key2, value]) => ({
866
+ key: key2,
867
+ kind: Array.isArray(value) ? "array" : value === null ? "null" : typeof value,
868
+ ...Array.isArray(value) ? { count: value.length } : {}
869
+ }));
870
+ return jsonResult(
871
+ { ...base, sections },
872
+ `Report for file ${taskIndex} of job ${args.jobId} \u2014 ${sections.length} sections. Request one via 'section'.`
873
+ );
874
+ } catch (error) {
875
+ return toolErrorResult(error);
876
+ }
877
+ }
878
+ );
879
+ }
880
+ var PROFILE_CODES = [
881
+ "auto",
882
+ "1a",
883
+ "1b",
884
+ "2a",
885
+ "2b",
886
+ "2u",
887
+ "3a",
888
+ "3b",
889
+ "3u",
890
+ "4",
891
+ "4e",
892
+ "4f",
893
+ "ua1",
894
+ "ua2"
895
+ ];
896
+ function registerValidatePdf(server, { client, caps }) {
897
+ server.registerTool(
898
+ "validate_pdf",
899
+ {
900
+ title: "Validate PDF/A / PDF/UA conformance",
901
+ description: "Validate a PDF against PDF/A (archival) and PDF/UA (accessibility) conformance levels using veraPDF. Levels: 'auto' detects the claimed level; '1b'/'2b'/'3b' etc. are PDF/A flavors; 'ua1'/'ua2' are PDF/UA. Read `compliant` per profile for the verdict; `status` only says whether validation ran.",
902
+ inputSchema: {
903
+ source: makeSourceSchema(caps),
904
+ levels: z.array(z.enum(PROFILE_CODES)).optional().describe(
905
+ "Conformance levels to check (default 'auto' \u2014 detect from the file's own claim)."
906
+ ),
907
+ waitSeconds: waitSecondsSchema
908
+ },
909
+ outputSchema: jobOutputShape,
910
+ annotations: {
911
+ readOnlyHint: false,
912
+ destructiveHint: false,
913
+ idempotentHint: false,
914
+ openWorldHint: true
915
+ }
916
+ },
917
+ async (args) => {
918
+ try {
919
+ const source = await resolveSource(client, caps, args.source);
920
+ const run = await submitAndWait(
921
+ client,
922
+ caps,
923
+ (wait) => client.jobs.validate({
924
+ sources: [
925
+ {
926
+ ...source,
927
+ ...args.levels?.length ? { profile: args.levels.length === 1 ? args.levels[0] : [...args.levels] } : {}
928
+ }
929
+ ],
930
+ ...wait
931
+ }),
932
+ args.waitSeconds
933
+ );
934
+ return formatJobResult(run);
935
+ } catch (error) {
936
+ return toolErrorResult(error);
937
+ }
938
+ }
939
+ );
940
+ }
941
+
942
+ // src/version.ts
943
+ var VERSION = "0.1.0";
944
+
945
+ // src/server.ts
946
+ var INSTRUCTIONS = `Filecheck checks print files (PDF, images) for print-readiness, fixes what it can automatically, validates PDF/A / PDF/UA conformance, optimizes, and renders previews.
947
+
948
+ CRITICAL \u2014 every job has two independent axes:
949
+ - status = execution lifecycle: pending | running | done | skipped | error
950
+ - outcome = verdict: pass | warn | fail | fixed | unchanged | na | mixed
951
+ status:done + outcome:fail means the check ran successfully AND the file is NOT print-ready. Never report success from status alone.
952
+
953
+ Download URLs are presigned and expire after ~60 minutes; get_job re-mints them on every call \u2014 never store or cache URLs.
954
+ If a tool returns pending:true, poll get_job with the returned jobId. Never resubmit a file that is already processing.
955
+ Typical flow: check_file \u2192 (findings autofixable?) fix_file \u2192 download/save deliverables. Discover profiles and rules with list_catalog.`;
956
+ function createFilecheckMcp({ client, capabilities }) {
957
+ const server = new McpServer(
958
+ { name: "filecheck", version: VERSION },
959
+ { instructions: INSTRUCTIONS }
960
+ );
961
+ const ctx = { client, caps: capabilities };
962
+ registerCheckFile(server, ctx);
963
+ registerFixFile(server, ctx);
964
+ registerValidatePdf(server, ctx);
965
+ registerOptimizeFile(server, ctx);
966
+ registerRenderPreviews(server, ctx);
967
+ registerJobTools(server, ctx);
968
+ registerListCatalog(server, ctx);
969
+ registerGetReport(server, ctx);
970
+ registerSaveArtifact(server, ctx);
971
+ return server;
972
+ }
973
+
974
+ // src/cli.ts
975
+ var key = process.env.FILECHECK_API_KEY;
976
+ if (!key) {
977
+ process.stderr.write(
978
+ [
979
+ `filecheck-mcp v${VERSION}: FILECHECK_API_KEY is not set.`,
980
+ "",
981
+ "Set it to your secret API key (sk_\u2026) from the Filecheck dashboard, e.g.:",
982
+ "",
983
+ " claude mcp add filecheck -e FILECHECK_API_KEY=sk_... -- npx -y filecheck-mcp",
984
+ "",
985
+ "Docs: https://filecheck.io/docs/integrations/mcp",
986
+ ""
987
+ ].join("\n")
988
+ );
989
+ process.exit(1);
990
+ }
991
+ try {
992
+ const client = new Filecheck(key, {
993
+ baseUrl: process.env.FILECHECK_BASE_URL || void 0
994
+ });
995
+ const server = createFilecheckMcp({ client, capabilities: LOCAL_CAPABILITIES });
996
+ await server.connect(new StdioServerTransport());
997
+ process.stderr.write(`filecheck-mcp v${VERSION} ready (stdio)
998
+ `);
999
+ } catch (error) {
1000
+ process.stderr.write(
1001
+ `filecheck-mcp failed to start: ${error instanceof Error ? error.message : String(error)}
1002
+ `
1003
+ );
1004
+ process.exit(1);
1005
+ }
1006
+ //# sourceMappingURL=cli.js.map
1007
+ //# sourceMappingURL=cli.js.map