@kolmopdf/mcp-server 1.2.3 → 1.2.5

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/index.cjs CHANGED
@@ -28,8 +28,53 @@ module.exports = __toCommonJS(index_exports);
28
28
  var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
29
29
  var import_stdio = require("@modelcontextprotocol/sdk/server/stdio.js");
30
30
 
31
- // src/client.ts
31
+ // src/jobs-upload.mjs
32
32
  var import_node_crypto = require("crypto");
33
+ async function uploadJob(endpoint, form, headers, timeoutMs = 6e5) {
34
+ const file = form.get("file");
35
+ const url = new URL(endpoint);
36
+ const id = headers["Idempotency-Key"] || (0, import_node_crypto.randomUUID)();
37
+ const send = (target, init2) => fetch(target, { ...init2, headers: { ...headers, ...init2.headers }, redirect: "error", signal: AbortSignal.timeout(timeoutMs) });
38
+ const legacy = () => send(endpoint, { method: "POST", body: form });
39
+ if (!file || file.size <= 2 * 1024 * 1024) return legacy();
40
+ const base = new URL("/api/intake/v1/jobs/uploads", url);
41
+ const options = Object.fromEntries([...form].filter(([name]) => name !== "file"));
42
+ const init = await send(base, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ uploadId: id, fileName: file.name, fileSize: file.size, operation: url.pathname.split("/").pop(), options }) });
43
+ if (init.status === 404 || init.status === 405) return legacy();
44
+ if (!init.ok) return init;
45
+ const state = await init.json();
46
+ if (state.uploadId !== id || !Number.isSafeInteger(state.chunkSize) || state.chunkSize < 1) throw new Error("Invalid upload session");
47
+ const session = `${base}/${id}`;
48
+ const complete = new Map(state.chunks.map((c) => [c.idx, c.sha256]));
49
+ async function repeat(target, opts) {
50
+ try {
51
+ const res = await send(target, opts);
52
+ if (![502, 503, 504, 408].includes(res.status)) return res;
53
+ await res.body?.cancel();
54
+ } catch (error) {
55
+ if (!(error instanceof TypeError) && error.name !== "TimeoutError") throw error;
56
+ }
57
+ try {
58
+ return await send(target, opts);
59
+ } catch (error) {
60
+ throw new Error(`Upload interrupted at ${new URL(target).pathname}; resume with upload_id=${id}: ${error.cause?.code || error.message}`);
61
+ }
62
+ }
63
+ for (let n = 0; n < Math.ceil(file.size / state.chunkSize); n++) {
64
+ const chunk = file.slice(n * state.chunkSize, (n + 1) * state.chunkSize);
65
+ if (complete.has(n)) {
66
+ if ((0, import_node_crypto.createHash)("sha256").update(new Uint8Array(await chunk.arrayBuffer())).digest("hex") !== complete.get(n)) throw new Error("Upload ID belongs to different file contents");
67
+ continue;
68
+ }
69
+ const res = await repeat(`${session}/chunks/${n}`, { method: "PUT", body: chunk });
70
+ if (!res.ok) return res;
71
+ await res.body?.cancel();
72
+ }
73
+ return repeat(`${session}/commit`, { method: "POST" });
74
+ }
75
+
76
+ // src/client.ts
77
+ var import_node_crypto2 = require("crypto");
33
78
  var import_node_stream = require("stream");
34
79
  var import_promises = require("stream/promises");
35
80
 
@@ -251,12 +296,11 @@ var KolmoPdfClient = class {
251
296
  }
252
297
  headers() {
253
298
  return {
254
- "X-API-Key": this.apiKey,
255
299
  Authorization: `Bearer ${this.apiKey}`
256
300
  };
257
301
  }
258
302
  async jsonRequest(url, init) {
259
- const res = await fetch(url, init);
303
+ const res = init.body instanceof FormData ? await uploadJob(url, init.body, init.headers, this.uploadTimeoutMs) : await fetch(url, init);
260
304
  let body = {};
261
305
  const text = await res.text();
262
306
  try {
@@ -328,7 +372,7 @@ var KolmoPdfClient = class {
328
372
  if (form.enrichment !== void 0) fd.append("enrichment", form.enrichment);
329
373
  const body = await this.jsonRequest(`${this.jobsBase}/parse`, {
330
374
  method: "POST",
331
- headers: { ...this.headers(), "Idempotency-Key": (0, import_node_crypto.randomUUID)() },
375
+ headers: { ...this.headers(), "Idempotency-Key": form.upload_id || (0, import_node_crypto2.randomUUID)() },
332
376
  body: fd,
333
377
  signal: AbortSignal.timeout(this.uploadTimeoutMs)
334
378
  });
@@ -345,7 +389,7 @@ var KolmoPdfClient = class {
345
389
  fd.append("enableTableTranslation", String(form.enable_table_translation));
346
390
  const body = await this.jsonRequest(`${this.jobsBase}/translate-pdf`, {
347
391
  method: "POST",
348
- headers: { ...this.headers(), "Idempotency-Key": (0, import_node_crypto.randomUUID)() },
392
+ headers: { ...this.headers(), "Idempotency-Key": (0, import_node_crypto2.randomUUID)() },
349
393
  body: fd,
350
394
  signal: AbortSignal.timeout(this.uploadTimeoutMs)
351
395
  });
@@ -356,7 +400,7 @@ var KolmoPdfClient = class {
356
400
  if (form.target_format) fd.append("targetFormat", form.target_format);
357
401
  const body = await this.jsonRequest(`${this.jobsBase}/convert`, {
358
402
  method: "POST",
359
- headers: { ...this.headers(), "Idempotency-Key": (0, import_node_crypto.randomUUID)() },
403
+ headers: { ...this.headers(), "Idempotency-Key": (0, import_node_crypto2.randomUUID)() },
360
404
  body: fd,
361
405
  signal: AbortSignal.timeout(this.uploadTimeoutMs)
362
406
  });
@@ -561,10 +605,49 @@ var import_promises2 = require("fs/promises");
561
605
  var import_pdf_lib = require("pdf-lib");
562
606
  var MAX_PAGES = 800;
563
607
  var MAX_FILE_BYTES = 300 * 1024 * 1024;
608
+ async function countPages(data) {
609
+ const doc = await import_pdf_lib.PDFDocument.load(data, { ignoreEncryption: true });
610
+ const pages = doc.getPageCount();
611
+ if (!Number.isSafeInteger(pages) || pages <= 0) throw new Error("Invalid page count");
612
+ return pages;
613
+ }
614
+ function completePdfPrefix(data) {
615
+ const text = data.toString("latin1");
616
+ const markers = /(?:^|[\r\n])startxref\s+(\d+)\s+%%EOF/g;
617
+ let last = null;
618
+ for (let match = markers.exec(text); match; match = markers.exec(text)) last = match;
619
+ if (!last) return null;
620
+ const end = last.index + last[0].length;
621
+ const xrefOffset = Number(last[1]);
622
+ if (end >= data.length || !Number.isSafeInteger(xrefOffset) || xrefOffset >= last.index) return null;
623
+ if (!/^(?:xref\b|\d+\s+\d+\s+obj\b)/.test(text.slice(xrefOffset, xrefOffset + 64))) return null;
624
+ return data.subarray(0, end);
625
+ }
564
626
  async function readPageCount(filePath) {
565
627
  const data = await (0, import_promises2.readFile)(filePath);
566
- const doc = await import_pdf_lib.PDFDocument.load(data, { ignoreEncryption: true });
567
- return doc.getPageCount();
628
+ try {
629
+ return await countPages(data);
630
+ } catch {
631
+ const prefix = completePdfPrefix(data);
632
+ if (prefix) {
633
+ try {
634
+ return await countPages(prefix);
635
+ } catch {
636
+ }
637
+ }
638
+ throw new KolmoPdfError("client_local_validation", {
639
+ message: "Exact page count is unavailable locally. This does not mean the PDF is unreadable.",
640
+ remediation: "Submit the original PDF for server-side validation; local credit estimation is unavailable."
641
+ });
642
+ }
643
+ }
644
+ async function readPageCountForSubmission(filePath) {
645
+ try {
646
+ return await readPageCount(filePath);
647
+ } catch (error) {
648
+ if (error instanceof KolmoPdfError && error.errorCode === "client_local_validation") return null;
649
+ throw error;
650
+ }
568
651
  }
569
652
  async function readFileSize(filePath) {
570
653
  const s = await (0, import_promises2.stat)(filePath);
@@ -1056,6 +1139,7 @@ var parsePdfName = "kolmopdf_parse_pdf";
1056
1139
  var parsePdfDescription = "Parse a local PDF into Markdown via KolmoPDF. Handles formulas, tables, multi-column layouts, and code blocks. Optionally translates while parsing. Server may attach outline.md/summary.md sidecars (ZIP download).";
1057
1140
  var parsePdfInputSchema = import_zod5.z.object({
1058
1141
  file_path: import_zod5.z.string().describe("Absolute or cwd-relative path to a local PDF file."),
1142
+ upload_id: import_zod5.z.string().uuid().optional().describe("Resume a previous interrupted upload ID."),
1059
1143
  table_mode: import_zod5.z.enum(["markdown", "image"]).optional(),
1060
1144
  formula_format: import_zod5.z.enum(["dollar", "bracket"]).optional(),
1061
1145
  enable_translation: import_zod5.z.boolean().optional(),
@@ -1077,8 +1161,8 @@ async function parsePdfHandler(args, ctx) {
1077
1161
  if (fileSize > MAX_FILE_BYTES) {
1078
1162
  throw new KolmoPdfError("parse_file_too_large");
1079
1163
  }
1080
- const pageCount = await readPageCount(filePath);
1081
- if (pageCount > MAX_PAGES) {
1164
+ const pageCount = await readPageCountForSubmission(filePath);
1165
+ if (pageCount !== null && pageCount > MAX_PAGES) {
1082
1166
  throw new KolmoPdfError("parse_page_limit_exceeded");
1083
1167
  }
1084
1168
  await ctx.progress?.report("[uploading] Sending PDF to KolmoPDF...");
@@ -1086,6 +1170,7 @@ async function parsePdfHandler(args, ctx) {
1086
1170
  const submitResult = await client.parse(
1087
1171
  fileBuffer,
1088
1172
  {
1173
+ upload_id: args.upload_id,
1089
1174
  table_mode: args.table_mode,
1090
1175
  formula_format: args.formula_format,
1091
1176
  enable_translation: args.enable_translation,
@@ -1176,8 +1261,8 @@ async function translatePdfHandler(args, ctx) {
1176
1261
  if (fileSize > MAX_FILE_BYTES) {
1177
1262
  throw new KolmoPdfError("translate_pdf_file_too_large");
1178
1263
  }
1179
- const pageCount = await readPageCount(filePath);
1180
- if (pageCount > MAX_PAGES) {
1264
+ const pageCount = await readPageCountForSubmission(filePath);
1265
+ if (pageCount !== null && pageCount > MAX_PAGES) {
1181
1266
  throw new KolmoPdfError("translate_pdf_page_limit_exceeded");
1182
1267
  }
1183
1268
  await ctx.progress?.report("[uploading] Sending PDF for translation...");
@@ -1237,7 +1322,7 @@ async function translatePdfHandler(args, ctx) {
1237
1322
  }
1238
1323
 
1239
1324
  // src/index.ts
1240
- var VERSION = "1.2.3";
1325
+ var VERSION = "1.2.5";
1241
1326
  function buildContext() {
1242
1327
  const config = loadConfig();
1243
1328
  return {