@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.js CHANGED
@@ -4,8 +4,53 @@
4
4
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
5
5
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
6
6
 
7
+ // src/jobs-upload.mjs
8
+ import { createHash, randomUUID } from "crypto";
9
+ async function uploadJob(endpoint, form, headers, timeoutMs = 6e5) {
10
+ const file = form.get("file");
11
+ const url = new URL(endpoint);
12
+ const id = headers["Idempotency-Key"] || randomUUID();
13
+ const send = (target, init2) => fetch(target, { ...init2, headers: { ...headers, ...init2.headers }, redirect: "error", signal: AbortSignal.timeout(timeoutMs) });
14
+ const legacy = () => send(endpoint, { method: "POST", body: form });
15
+ if (!file || file.size <= 2 * 1024 * 1024) return legacy();
16
+ const base = new URL("/api/intake/v1/jobs/uploads", url);
17
+ const options = Object.fromEntries([...form].filter(([name]) => name !== "file"));
18
+ 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 }) });
19
+ if (init.status === 404 || init.status === 405) return legacy();
20
+ if (!init.ok) return init;
21
+ const state = await init.json();
22
+ if (state.uploadId !== id || !Number.isSafeInteger(state.chunkSize) || state.chunkSize < 1) throw new Error("Invalid upload session");
23
+ const session = `${base}/${id}`;
24
+ const complete = new Map(state.chunks.map((c) => [c.idx, c.sha256]));
25
+ async function repeat(target, opts) {
26
+ try {
27
+ const res = await send(target, opts);
28
+ if (![502, 503, 504, 408].includes(res.status)) return res;
29
+ await res.body?.cancel();
30
+ } catch (error) {
31
+ if (!(error instanceof TypeError) && error.name !== "TimeoutError") throw error;
32
+ }
33
+ try {
34
+ return await send(target, opts);
35
+ } catch (error) {
36
+ throw new Error(`Upload interrupted at ${new URL(target).pathname}; resume with upload_id=${id}: ${error.cause?.code || error.message}`);
37
+ }
38
+ }
39
+ for (let n = 0; n < Math.ceil(file.size / state.chunkSize); n++) {
40
+ const chunk = file.slice(n * state.chunkSize, (n + 1) * state.chunkSize);
41
+ if (complete.has(n)) {
42
+ if (createHash("sha256").update(new Uint8Array(await chunk.arrayBuffer())).digest("hex") !== complete.get(n)) throw new Error("Upload ID belongs to different file contents");
43
+ continue;
44
+ }
45
+ const res = await repeat(`${session}/chunks/${n}`, { method: "PUT", body: chunk });
46
+ if (!res.ok) return res;
47
+ await res.body?.cancel();
48
+ }
49
+ return repeat(`${session}/commit`, { method: "POST" });
50
+ }
51
+
7
52
  // src/client.ts
8
- import { randomUUID } from "crypto";
53
+ import { randomUUID as randomUUID2 } from "crypto";
9
54
  import { Readable } from "stream";
10
55
  import { pipeline } from "stream/promises";
11
56
 
@@ -227,12 +272,11 @@ var KolmoPdfClient = class {
227
272
  }
228
273
  headers() {
229
274
  return {
230
- "X-API-Key": this.apiKey,
231
275
  Authorization: `Bearer ${this.apiKey}`
232
276
  };
233
277
  }
234
278
  async jsonRequest(url, init) {
235
- const res = await fetch(url, init);
279
+ const res = init.body instanceof FormData ? await uploadJob(url, init.body, init.headers, this.uploadTimeoutMs) : await fetch(url, init);
236
280
  let body = {};
237
281
  const text = await res.text();
238
282
  try {
@@ -304,7 +348,7 @@ var KolmoPdfClient = class {
304
348
  if (form.enrichment !== void 0) fd.append("enrichment", form.enrichment);
305
349
  const body = await this.jsonRequest(`${this.jobsBase}/parse`, {
306
350
  method: "POST",
307
- headers: { ...this.headers(), "Idempotency-Key": randomUUID() },
351
+ headers: { ...this.headers(), "Idempotency-Key": form.upload_id || randomUUID2() },
308
352
  body: fd,
309
353
  signal: AbortSignal.timeout(this.uploadTimeoutMs)
310
354
  });
@@ -321,7 +365,7 @@ var KolmoPdfClient = class {
321
365
  fd.append("enableTableTranslation", String(form.enable_table_translation));
322
366
  const body = await this.jsonRequest(`${this.jobsBase}/translate-pdf`, {
323
367
  method: "POST",
324
- headers: { ...this.headers(), "Idempotency-Key": randomUUID() },
368
+ headers: { ...this.headers(), "Idempotency-Key": randomUUID2() },
325
369
  body: fd,
326
370
  signal: AbortSignal.timeout(this.uploadTimeoutMs)
327
371
  });
@@ -332,7 +376,7 @@ var KolmoPdfClient = class {
332
376
  if (form.target_format) fd.append("targetFormat", form.target_format);
333
377
  const body = await this.jsonRequest(`${this.jobsBase}/convert`, {
334
378
  method: "POST",
335
- headers: { ...this.headers(), "Idempotency-Key": randomUUID() },
379
+ headers: { ...this.headers(), "Idempotency-Key": randomUUID2() },
336
380
  body: fd,
337
381
  signal: AbortSignal.timeout(this.uploadTimeoutMs)
338
382
  });
@@ -537,10 +581,49 @@ import { readFile, stat } from "fs/promises";
537
581
  import { PDFDocument } from "pdf-lib";
538
582
  var MAX_PAGES = 800;
539
583
  var MAX_FILE_BYTES = 300 * 1024 * 1024;
584
+ async function countPages(data) {
585
+ const doc = await PDFDocument.load(data, { ignoreEncryption: true });
586
+ const pages = doc.getPageCount();
587
+ if (!Number.isSafeInteger(pages) || pages <= 0) throw new Error("Invalid page count");
588
+ return pages;
589
+ }
590
+ function completePdfPrefix(data) {
591
+ const text = data.toString("latin1");
592
+ const markers = /(?:^|[\r\n])startxref\s+(\d+)\s+%%EOF/g;
593
+ let last = null;
594
+ for (let match = markers.exec(text); match; match = markers.exec(text)) last = match;
595
+ if (!last) return null;
596
+ const end = last.index + last[0].length;
597
+ const xrefOffset = Number(last[1]);
598
+ if (end >= data.length || !Number.isSafeInteger(xrefOffset) || xrefOffset >= last.index) return null;
599
+ if (!/^(?:xref\b|\d+\s+\d+\s+obj\b)/.test(text.slice(xrefOffset, xrefOffset + 64))) return null;
600
+ return data.subarray(0, end);
601
+ }
540
602
  async function readPageCount(filePath) {
541
603
  const data = await readFile(filePath);
542
- const doc = await PDFDocument.load(data, { ignoreEncryption: true });
543
- return doc.getPageCount();
604
+ try {
605
+ return await countPages(data);
606
+ } catch {
607
+ const prefix = completePdfPrefix(data);
608
+ if (prefix) {
609
+ try {
610
+ return await countPages(prefix);
611
+ } catch {
612
+ }
613
+ }
614
+ throw new KolmoPdfError("client_local_validation", {
615
+ message: "Exact page count is unavailable locally. This does not mean the PDF is unreadable.",
616
+ remediation: "Submit the original PDF for server-side validation; local credit estimation is unavailable."
617
+ });
618
+ }
619
+ }
620
+ async function readPageCountForSubmission(filePath) {
621
+ try {
622
+ return await readPageCount(filePath);
623
+ } catch (error) {
624
+ if (error instanceof KolmoPdfError && error.errorCode === "client_local_validation") return null;
625
+ throw error;
626
+ }
544
627
  }
545
628
  async function readFileSize(filePath) {
546
629
  const s = await stat(filePath);
@@ -1032,6 +1115,7 @@ var parsePdfName = "kolmopdf_parse_pdf";
1032
1115
  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).";
1033
1116
  var parsePdfInputSchema = z5.object({
1034
1117
  file_path: z5.string().describe("Absolute or cwd-relative path to a local PDF file."),
1118
+ upload_id: z5.string().uuid().optional().describe("Resume a previous interrupted upload ID."),
1035
1119
  table_mode: z5.enum(["markdown", "image"]).optional(),
1036
1120
  formula_format: z5.enum(["dollar", "bracket"]).optional(),
1037
1121
  enable_translation: z5.boolean().optional(),
@@ -1053,8 +1137,8 @@ async function parsePdfHandler(args, ctx) {
1053
1137
  if (fileSize > MAX_FILE_BYTES) {
1054
1138
  throw new KolmoPdfError("parse_file_too_large");
1055
1139
  }
1056
- const pageCount = await readPageCount(filePath);
1057
- if (pageCount > MAX_PAGES) {
1140
+ const pageCount = await readPageCountForSubmission(filePath);
1141
+ if (pageCount !== null && pageCount > MAX_PAGES) {
1058
1142
  throw new KolmoPdfError("parse_page_limit_exceeded");
1059
1143
  }
1060
1144
  await ctx.progress?.report("[uploading] Sending PDF to KolmoPDF...");
@@ -1062,6 +1146,7 @@ async function parsePdfHandler(args, ctx) {
1062
1146
  const submitResult = await client.parse(
1063
1147
  fileBuffer,
1064
1148
  {
1149
+ upload_id: args.upload_id,
1065
1150
  table_mode: args.table_mode,
1066
1151
  formula_format: args.formula_format,
1067
1152
  enable_translation: args.enable_translation,
@@ -1152,8 +1237,8 @@ async function translatePdfHandler(args, ctx) {
1152
1237
  if (fileSize > MAX_FILE_BYTES) {
1153
1238
  throw new KolmoPdfError("translate_pdf_file_too_large");
1154
1239
  }
1155
- const pageCount = await readPageCount(filePath);
1156
- if (pageCount > MAX_PAGES) {
1240
+ const pageCount = await readPageCountForSubmission(filePath);
1241
+ if (pageCount !== null && pageCount > MAX_PAGES) {
1157
1242
  throw new KolmoPdfError("translate_pdf_page_limit_exceeded");
1158
1243
  }
1159
1244
  await ctx.progress?.report("[uploading] Sending PDF for translation...");
@@ -1213,7 +1298,7 @@ async function translatePdfHandler(args, ctx) {
1213
1298
  }
1214
1299
 
1215
1300
  // src/index.ts
1216
- var VERSION = "1.2.3";
1301
+ var VERSION = "1.2.5";
1217
1302
  function buildContext() {
1218
1303
  const config = loadConfig();
1219
1304
  return {