-
Notifications
You must be signed in to change notification settings - Fork 276
Expand file tree
/
Copy pathserver.ts
More file actions
2770 lines (2572 loc) · 95.2 KB
/
server.ts
File metadata and controls
2770 lines (2572 loc) · 95.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* PDF MCP Server
*
* An MCP server that displays PDFs in an interactive viewer.
* Supports local files and remote HTTPS URLs.
*
* Tools:
* - list_pdfs: List available PDFs
* - display_pdf: Show interactive PDF viewer
* - read_pdf_bytes: Stream PDF data in chunks (used by viewer)
*/
import { randomUUID } from "crypto";
import fs from "node:fs";
import path from "node:path";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import type { Server } from "@modelcontextprotocol/sdk/server/index.js";
import {
registerAppResource,
registerAppTool,
RESOURCE_MIME_TYPE,
} from "@modelcontextprotocol/ext-apps/server";
import {
RootsListChangedNotificationSchema,
type CallToolResult,
type ReadResourceResult,
} from "@modelcontextprotocol/sdk/types.js";
// Use the legacy build to avoid DOMMatrix dependency in Node.js
import {
getDocument,
VerbosityLevel,
version as PDFJS_VERSION,
} from "pdfjs-dist/legacy/build/pdf.mjs";
/**
* PDF Standard-14 fonts from CDN. Used by both server and viewer so we
* declare a single well-known origin in CSP connectDomains.
*
* pdf.js in Node defaults to NodeStandardFontDataFactory (fs.readFile) which
* can't fetch URLs, so we pass {@link FetchStandardFontDataFactory} alongside.
* The browser viewer uses the DOM factory by default and just needs the URL.
*/
export const STANDARD_FONT_DATA_URL = `https://unpkg.com/pdfjs-dist@${PDFJS_VERSION}/standard_fonts/`;
const STANDARD_FONT_ORIGIN = "https://unpkg.com";
/** pdf.js font factory that uses fetch() instead of fs.readFile. */
class FetchStandardFontDataFactory {
baseUrl: string | null;
constructor({ baseUrl = null }: { baseUrl?: string | null }) {
this.baseUrl = baseUrl;
}
async fetch({ filename }: { filename: string }): Promise<Uint8Array> {
if (!this.baseUrl) throw new Error("standardFontDataUrl not provided");
const url = `${this.baseUrl}${filename}`;
const res = await globalThis.fetch(url);
if (!res.ok) throw new Error(`Failed to fetch ${url}: ${res.status}`);
return new Uint8Array(await res.arrayBuffer());
}
}
import type {
PrimitiveSchemaDefinition,
ElicitResult,
} from "@modelcontextprotocol/sdk/types.js";
import { z } from "zod";
// =============================================================================
// Configuration
// =============================================================================
export const DEFAULT_PDF = "https://arxiv.org/pdf/1706.03762"; // Attention Is All You Need
export const MAX_CHUNK_BYTES = 512 * 1024; // 512KB max per request
export const RESOURCE_URI = "ui://pdf-viewer/mcp-app.html";
/** Inactivity timeout: clear cache entry if not accessed for this long */
export const CACHE_INACTIVITY_TIMEOUT_MS = 10_000; // 10 seconds
/** Max lifetime: clear cache entry after this time regardless of access */
export const CACHE_MAX_LIFETIME_MS = 60_000; // 60 seconds
/** Max size for cached PDFs (defensive limit to prevent memory exhaustion) */
export const CACHE_MAX_PDF_SIZE_BYTES = 50 * 1024 * 1024; // 50MB
/** Allowed local file paths (CLI args + file roots — read access). */
export const allowedLocalFiles = new Set<string>();
/** Allowed local directories (CLI args + directory roots — read access). */
export const allowedLocalDirs = new Set<string>();
/**
* Subset of allowedLocalFiles that came from CLI args (not MCP roots).
* Only these individual files are writable. File roots from the client
* are uploaded copies in ad-hoc hidden folders — treat as read-only.
* Directory roots are mounted folders; files UNDER them are writable.
*/
export const cliLocalFiles = new Set<string>();
/**
* Write-permission flags. Object wrapper (not a bare `let`) so main.ts can
* mutate via the exported binding without re-import gymnastics — same
* pattern as the Sets above.
*/
export const writeFlags = {
/**
* Claude Desktop mounts its per-conversation drop folder as a directory
* root whose basename is literally `uploads`. Files in there are one-shot
* copies the client doesn't expect us to overwrite. Default: read-only.
* `--writeable-uploads-root` flips this for local testing.
*/
allowUploadsRoot: false,
};
/**
* Saving is allowed iff:
* (a) the file was passed as a CLI arg — the user explicitly named it
* when starting the server, so overwriting is clearly intentional; OR
* (b) the file is STRICTLY UNDER a directory root at any depth
* (isAncestorDir excludes rel === "", so the root itself never
* counts), AND the client did not ALSO send it as a file root.
* A file root is the client's way of saying "here's an upload" —
* treat that signal as authoritative even when the path happens
* to fall inside a mounted directory.
*
* EXCEPTION to (b): a dir root whose basename is `uploads` is treated
* as read-only unless `writeFlags.allowUploadsRoot` is set. This is how
* Claude Desktop surfaces attached files — writing back to them
* surprises the user (the attachment doesn't update).
*
* With no directory roots and no CLI files, nothing is writable.
*/
export function isWritablePath(resolved: string): boolean {
if (cliLocalFiles.has(resolved)) return true;
// MCP file root → always read-only, regardless of ancestry
if (allowedLocalFiles.has(resolved)) return false;
return [...allowedLocalDirs].some((dir) => {
if (!isAncestorDir(dir, resolved)) return false;
if (!writeFlags.allowUploadsRoot && path.basename(dir) === "uploads") {
return false;
}
return true;
});
}
// Works both from source (server.ts) and compiled (dist/server.js)
const DIST_DIR = import.meta.filename.endsWith(".ts")
? path.join(import.meta.dirname, "dist")
: import.meta.dirname;
// =============================================================================
// Command Queue (shared across stateless server instances)
// =============================================================================
/** Commands expire after this many ms if never polled */
const COMMAND_TTL_MS = 60_000; // 60 seconds
/** Periodic sweep interval to drop stale queues */
const SWEEP_INTERVAL_MS = 30_000; // 30 seconds
/** Fixed batch window: when commands are present, wait this long before returning to let more accumulate */
const POLL_BATCH_WAIT_MS = 200;
const LONG_POLL_TIMEOUT_MS = 30_000; // Max time to hold a long-poll request open
// =============================================================================
// Interact Tool Input Schemas (runtime validators)
// =============================================================================
//
// Annotation structure docs live in src/pdf-annotations.ts (the TS
// interfaces) and in the interact tool description. The inputSchema
// for `annotations` accepts z.record(z.any()) to keep the model-facing
// API forgiving; adding strict validation here would be a behavior change.
const FormField = z.object({
name: z.string(),
value: z.union([z.string(), z.boolean()]),
});
const PageInterval = z.object({
start: z.number().min(1).optional(),
end: z.number().min(1).optional(),
});
// =============================================================================
// Command Queue — wire protocol shared with the viewer
// =============================================================================
// PdfCommand is the single source of truth for what flows through the
// poll queue. Defined once in src/commands.ts; both sides import it.
// (`import type` → no pdf-lib bundled into the server.)
import type { PdfCommand } from "./src/commands.js";
export type { PdfCommand };
// =============================================================================
// Pending get_pages Requests (request-response bridge via client)
// =============================================================================
// Keep well under the MCP SDK's DEFAULT_REQUEST_TIMEOUT_MSEC (60s) so we
// reject first and return a real error instead of the client cancelling us.
const GET_PAGES_TIMEOUT_MS = 45_000;
/**
* Grace period for the viewer's first poll. If interact() arrives before the
* iframe has ever polled, we wait this long for it to show up (iframe mount +
* PDF load + startPolling). If no poll comes, the viewer almost certainly
* never rendered — failing fast beats a silent 45s hang.
*/
const VIEWER_FIRST_POLL_GRACE_MS = 8_000;
interface PageDataEntry {
page: number;
text?: string;
image?: string; // base64 PNG
}
const pendingPageRequests = new Map<
string,
(data: PageDataEntry[] | Error) => void
>();
/**
* Wait for the viewer to render and submit page data.
* Rejects on timeout or when the interact request is aborted upstream.
*/
function waitForPageData(
requestId: string,
signal?: AbortSignal,
): Promise<PageDataEntry[]> {
return new Promise<PageDataEntry[]>((resolve, reject) => {
const settle = (v: PageDataEntry[] | Error) => {
clearTimeout(timer);
signal?.removeEventListener("abort", onAbort);
pendingPageRequests.delete(requestId);
v instanceof Error ? reject(v) : resolve(v);
};
const onAbort = () => settle(new Error("interact request cancelled"));
const timer = setTimeout(
() => settle(new Error("Timeout waiting for page data from viewer")),
GET_PAGES_TIMEOUT_MS,
);
signal?.addEventListener("abort", onAbort);
pendingPageRequests.set(requestId, settle);
});
}
/**
* Wait for the viewer's first poll_pdf_commands call.
*
* Called before waitForPageData() / waitForSaveData() so a viewer that never
* mounted fails in ~8s with a specific message instead of a generic 45s
* "Timeout waiting for ..." that gives no hint why.
*
* Intentionally does NOT touch pollWaiters: piggybacking on that single-slot
* Map races with poll_pdf_commands' batch-wait branch (which never cancels the
* prior waiter) and with concurrent interact calls (which would overwrite each
* other). A plain check loop on viewsPolled is stateless — multiple callers
* can wait independently and all observe the same add() when it happens.
*/
async function ensureViewerIsPolling(uuid: string): Promise<void> {
const deadline = Date.now() + VIEWER_FIRST_POLL_GRACE_MS;
while (!viewsPolled.has(uuid)) {
if (Date.now() >= deadline) {
throw new Error(
`Viewer never connected for viewUUID ${uuid} (no poll within ${VIEWER_FIRST_POLL_GRACE_MS / 1000}s). ` +
`The iframe likely failed to mount — this happens when the conversation ` +
`goes idle before the viewer finishes loading. Call display_pdf again to get a fresh viewUUID.`,
);
}
await new Promise((r) => setTimeout(r, 100));
}
}
// =============================================================================
// Pending save_as Requests (request-response bridge via client)
// =============================================================================
//
// Same shape as get_pages: model's interact call blocks while the viewer
// builds annotated bytes and posts them back. Reuses GET_PAGES_TIMEOUT_MS
// (45s) — generous because pdf-lib reflow on a large doc can take seconds.
const pendingSaveRequests = new Map<string, (v: string | Error) => void>();
/**
* Wait for the viewer to build annotated PDF bytes and submit them as base64.
* Rejects on timeout, abort, or when the viewer reports an error.
*/
function waitForSaveData(
requestId: string,
signal?: AbortSignal,
): Promise<string> {
return new Promise<string>((resolve, reject) => {
const settle = (v: string | Error) => {
clearTimeout(timer);
signal?.removeEventListener("abort", onAbort);
pendingSaveRequests.delete(requestId);
v instanceof Error ? reject(v) : resolve(v);
};
const onAbort = () => settle(new Error("interact request cancelled"));
const timer = setTimeout(
() => settle(new Error("Timeout waiting for PDF bytes from viewer")),
GET_PAGES_TIMEOUT_MS,
);
signal?.addEventListener("abort", onAbort);
pendingSaveRequests.set(requestId, settle);
});
}
interface QueueEntry {
commands: PdfCommand[];
/** Timestamp of the most recent enqueue or dequeue */
lastActivity: number;
}
const commandQueues = new Map<string, QueueEntry>();
/** Waiters for long-poll: resolve callback wakes up a blocked poll_pdf_commands */
const pollWaiters = new Map<string, () => void>();
/**
* viewUUIDs that have been polled at least once. A view missing from this set
* means the iframe never reached startPolling() — usually because it wasn't
* mounted yet, or ontoolresult threw before the poll loop started. Used to
* fail fast in get_screenshot/get_text instead of waiting the full 45s for
* a viewer that was never there.
*/
const viewsPolled = new Set<string>();
/**
* Resolved local file path per viewer UUID, for save_as without an explicit
* target. Only set for local files (remote PDFs have nothing to overwrite).
* Populated during display_pdf, cleared by the heartbeat sweep.
*
* Exported for tests.
*/
export const viewSourcePaths = new Map<string, string>();
/** Valid form field names per viewer UUID (populated during display_pdf) */
const viewFieldNames = new Map<string, Set<string>>();
/** Detailed form field info per viewer UUID (populated during display_pdf) */
const viewFieldInfo = new Map<string, FormFieldInfo[]>();
/**
* Active fs.watch per view. Only created for local files when interact is
* enabled (stdio). Watcher is re-established on `rename` events to survive
* atomic writes (vim/vscode write-to-tmp-then-rename changes the inode).
*/
interface ViewFileWatch {
filePath: string;
watcher: fs.FSWatcher;
lastMtimeMs: number;
debounce: ReturnType<typeof setTimeout> | null;
}
const viewFileWatches = new Map<string, ViewFileWatch>();
/**
* Per-view heartbeat. THIS is what the sweep iterates — not commandQueues.
*
* Why not commandQueues: display_pdf populates viewFieldNames/viewFieldInfo/
* viewFileWatches but never touches commandQueues (only enqueueCommand does,
* and it's triply gated). And dequeueCommands deletes the entry on every poll,
* so even when it exists the sweep's TTL window is ~200ms wide. Net effect:
* the sweep found nothing and the aux maps leaked every display_pdf call.
* viewFileWatches entries hold an fs.StatWatcher (FD + timer) — slow FD
* exhaustion on HTTP --enable-interact.
*/
const viewLastActivity = new Map<string, number>();
/** Register or refresh the heartbeat for a view. */
function touchView(uuid: string): void {
viewLastActivity.set(uuid, Date.now());
}
function pruneStaleQueues(): void {
const now = Date.now();
for (const [uuid, lastActivity] of viewLastActivity) {
if (now - lastActivity > COMMAND_TTL_MS) {
viewLastActivity.delete(uuid);
commandQueues.delete(uuid);
viewFieldNames.delete(uuid);
viewFieldInfo.delete(uuid);
viewsPolled.delete(uuid);
viewSourcePaths.delete(uuid);
stopFileWatch(uuid);
}
}
}
// Periodic sweep so abandoned views don't leak
setInterval(pruneStaleQueues, SWEEP_INTERVAL_MS).unref();
function enqueueCommand(viewUUID: string, command: PdfCommand): void {
let entry = commandQueues.get(viewUUID);
if (!entry) {
entry = { commands: [], lastActivity: Date.now() };
commandQueues.set(viewUUID, entry);
}
entry.commands.push(command);
entry.lastActivity = Date.now();
touchView(viewUUID);
// Wake up any long-polling request waiting for this viewUUID
const waiter = pollWaiters.get(viewUUID);
if (waiter) {
pollWaiters.delete(viewUUID);
waiter();
}
}
function dequeueCommands(viewUUID: string): PdfCommand[] {
// Poll is activity — keep the view alive even when the queue is empty
// (the common case: viewer polls every ~30s with nothing to receive).
touchView(viewUUID);
const entry = commandQueues.get(viewUUID);
if (!entry) return [];
const commands = entry.commands;
commandQueues.delete(viewUUID);
return commands;
}
// =============================================================================
// File Watching (local files, stdio only)
// =============================================================================
const FILE_WATCH_DEBOUNCE_MS = 150;
export function startFileWatch(viewUUID: string, filePath: string): void {
const resolved = path.resolve(filePath);
let stat: fs.Stats;
try {
stat = fs.statSync(resolved);
} catch {
return; // vanished between validation and here
}
// Replace any existing watcher for this view
stopFileWatch(viewUUID);
const entry: ViewFileWatch = {
filePath: resolved,
watcher: null as unknown as fs.FSWatcher,
lastMtimeMs: stat.mtimeMs,
debounce: null,
};
const onEvent = (eventType: string): void => {
if (entry.debounce) clearTimeout(entry.debounce);
entry.debounce = setTimeout(() => {
entry.debounce = null;
let s: fs.Stats;
try {
s = fs.statSync(resolved);
} catch {
return; // gone mid-atomic-write; next rename will re-attach
}
if (s.mtimeMs === entry.lastMtimeMs) return; // spurious / already sent
entry.lastMtimeMs = s.mtimeMs;
enqueueCommand(viewUUID, { type: "file_changed", mtimeMs: s.mtimeMs });
}, FILE_WATCH_DEBOUNCE_MS);
// Atomic saves replace the inode — old watcher stops firing. Re-attach.
if (eventType === "rename") {
try {
entry.watcher.close();
} catch {
/* already closed */
}
try {
entry.watcher = fs.watch(resolved, onEvent);
} catch {
// File removed, not replaced. Leave closed; pruneStaleQueues cleans up.
}
}
};
try {
entry.watcher = fs.watch(resolved, onEvent);
} catch {
return; // fs.watch unsupported (e.g. some network filesystems)
}
viewFileWatches.set(viewUUID, entry);
}
export function stopFileWatch(viewUUID: string): void {
const entry = viewFileWatches.get(viewUUID);
if (!entry) return;
if (entry.debounce) clearTimeout(entry.debounce);
try {
entry.watcher.close();
} catch {
/* ignore */
}
viewFileWatches.delete(viewUUID);
}
// =============================================================================
// URL Validation & Normalization
// =============================================================================
export function isFileUrl(url: string): boolean {
return url.startsWith("file://") || url.startsWith("computer://");
}
export function isArxivUrl(url: string): boolean {
try {
const parsed = new URL(url);
return (
parsed.hostname === "arxiv.org" || parsed.hostname === "www.arxiv.org"
);
} catch {
return false;
}
}
export function normalizeArxivUrl(url: string): string {
// Convert arxiv abstract URLs to PDF URLs
// https://arxiv.org/abs/1706.03762 -> https://arxiv.org/pdf/1706.03762
return url.replace("/abs/", "/pdf/").replace(/\.pdf$/, "");
}
export function fileUrlToPath(fileUrl: string): string {
// Support both file:// and computer:// (used by some clients for local files)
return decodeURIComponent(fileUrl.replace(/^(?:file|computer):\/\//, ""));
}
export function pathToFileUrl(filePath: string): string {
const absolutePath = path.resolve(filePath);
return `file://${encodeURIComponent(absolutePath).replace(/%2F/g, "/")}`;
}
/**
* Check if `dir` is an ancestor of `filePath` using path.relative,
* which is more robust than string prefix matching (handles normalization).
*/
export function isAncestorDir(dir: string, filePath: string): boolean {
const rel = path.relative(dir, filePath);
// Must be non-empty (not the dir itself when checking files),
// must not start with ".." (escaping), and must not be absolute (different root).
return rel !== "" && !rel.startsWith("..") && !path.isAbsolute(rel);
}
/**
* Check if `url` looks like an absolute local file path (not a URL scheme).
* Handles Unix paths (/...), home-relative (~), and Windows drive letters (C:\...).
*/
function isLocalPath(url: string): boolean {
return (
url.startsWith("/") || url.startsWith("~") || /^[A-Za-z]:[/\\]/.test(url)
);
}
export function validateUrl(url: string): {
valid: boolean;
error?: string;
} {
if (isFileUrl(url) || isLocalPath(url)) {
// fileUrlToPath already decodes percent-encoding; for bare paths,
// decode here in case the client sends %20 for spaces etc.
const filePath = isFileUrl(url)
? fileUrlToPath(url)
: decodeURIComponent(url);
const resolved = path.resolve(filePath);
// Check exact match (CLI args / roots)
if (allowedLocalFiles.has(resolved)) {
if (!fs.existsSync(resolved)) {
return { valid: false, error: `File not found: ${resolved}` };
}
return { valid: true };
}
// Check directory match (MCP roots / CLI dirs).
// Try both the raw path and its realpath (resolves symlinks).
let realResolved: string | undefined;
try {
realResolved = fs.realpathSync(resolved);
} catch {
// File may not exist yet at this path
}
if (
[...allowedLocalDirs].some((dir) => {
let realDir: string | undefined;
try {
realDir = fs.realpathSync(dir);
} catch {
// Dir may not exist
}
return (
isAncestorDir(dir, resolved) ||
(realResolved != null && isAncestorDir(dir, realResolved)) ||
(realDir != null && isAncestorDir(realDir, resolved)) ||
(realDir != null &&
realResolved != null &&
isAncestorDir(realDir, realResolved))
);
})
) {
if (!fs.existsSync(resolved)) {
return { valid: false, error: `File not found: ${resolved}` };
}
return { valid: true };
}
console.error(
`[pdf-server] Local file not in allowed list: ${resolved}\n Allowed dirs: ${[...allowedLocalDirs].join(", ")}`,
);
return {
valid: false,
error: `Local file not in allowed list: ${resolved}\nAllowed directories: ${[...allowedLocalDirs].join(", ")}`,
};
}
// Remote URL - require HTTPS
try {
const parsed = new URL(url);
if (parsed.protocol !== "https:") {
return { valid: false, error: `Only HTTPS URLs are allowed: ${url}` };
}
return { valid: true };
} catch {
return { valid: false, error: `Invalid URL: ${url}` };
}
}
// =============================================================================
// Session-Local PDF Cache
// =============================================================================
/**
* Cache entry for remote PDFs from servers that don't support Range requests.
* Tracks both inactivity and max lifetime for automatic cleanup.
*/
interface CacheEntry {
/** The cached PDF data */
data: Uint8Array;
/** Timestamp when entry was created (for max lifetime) */
createdAt: number;
/** Timer that fires after CACHE_INACTIVITY_TIMEOUT_MS of no access */
inactivityTimer: ReturnType<typeof setTimeout>;
/** Timer that fires after CACHE_MAX_LIFETIME_MS from creation */
maxLifetimeTimer: ReturnType<typeof setTimeout>;
}
/**
* Session-local PDF cache utilities.
* Each call to createPdfCache() creates an independent cache instance.
*/
export interface PdfCache {
/** Read a range of bytes from a PDF, using cache for servers without Range support */
readPdfRange(
url: string,
offset: number,
byteCount: number,
): Promise<{ data: Uint8Array; totalBytes: number }>;
/** Get current number of cached entries */
getCacheSize(): number;
/** Clear all cached entries and their timers */
clearCache(): void;
}
/**
* Creates a session-local PDF cache with automatic timeout-based cleanup.
*
* When a remote server returns HTTP 200 (full body) instead of 206 (partial),
* the full response is cached so subsequent chunk requests don't re-download.
*
* Entries are automatically cleared after:
* - CACHE_INACTIVITY_TIMEOUT_MS of no access (resets on each access)
* - CACHE_MAX_LIFETIME_MS from creation (absolute timeout)
*/
export function createPdfCache(): PdfCache {
const cache = new Map<string, CacheEntry>();
/** Delete a cache entry and clear its timers */
function deleteCacheEntry(url: string): void {
const entry = cache.get(url);
if (entry) {
clearTimeout(entry.inactivityTimer);
clearTimeout(entry.maxLifetimeTimer);
cache.delete(url);
}
}
/** Get cached data and refresh the inactivity timer */
function getCacheEntry(url: string): Uint8Array | undefined {
const entry = cache.get(url);
if (!entry) return undefined;
// Refresh inactivity timer on access
clearTimeout(entry.inactivityTimer);
entry.inactivityTimer = setTimeout(() => {
deleteCacheEntry(url);
}, CACHE_INACTIVITY_TIMEOUT_MS);
return entry.data;
}
/** Add data to cache with both inactivity and max lifetime timers */
function setCacheEntry(url: string, data: Uint8Array): void {
// Clear any existing entry first
deleteCacheEntry(url);
const entry: CacheEntry = {
data,
createdAt: Date.now(),
inactivityTimer: setTimeout(() => {
deleteCacheEntry(url);
}, CACHE_INACTIVITY_TIMEOUT_MS),
maxLifetimeTimer: setTimeout(() => {
deleteCacheEntry(url);
}, CACHE_MAX_LIFETIME_MS),
};
cache.set(url, entry);
}
/** Slice a cached or freshly-fetched full body to the requested range. */
function sliceToChunk(
fullData: Uint8Array,
offset: number,
clampedByteCount: number,
): { data: Uint8Array; totalBytes: number } {
const totalBytes = fullData.length;
const start = Math.min(offset, totalBytes);
const end = Math.min(start + clampedByteCount, totalBytes);
return { data: fullData.slice(start, end), totalBytes };
}
async function readPdfRange(
url: string,
offset: number,
byteCount: number,
): Promise<{ data: Uint8Array; totalBytes: number }> {
const normalized = isArxivUrl(url) ? normalizeArxivUrl(url) : url;
const clampedByteCount = Math.min(byteCount, MAX_CHUNK_BYTES);
if (isFileUrl(normalized) || isLocalPath(normalized)) {
const filePath = isFileUrl(normalized)
? fileUrlToPath(normalized)
: decodeURIComponent(normalized);
const stats = await fs.promises.stat(filePath);
const totalBytes = stats.size;
// Clamp to file bounds
const start = Math.min(offset, totalBytes);
const end = Math.min(start + clampedByteCount, totalBytes);
if (start >= totalBytes) {
return { data: new Uint8Array(0), totalBytes };
}
// Read range from local file
const buffer = Buffer.alloc(end - start);
const fd = await fs.promises.open(filePath, "r");
try {
await fd.read(buffer, 0, end - start, start);
} finally {
await fd.close();
}
return { data: new Uint8Array(buffer), totalBytes };
}
// Serve from cache if we previously downloaded the full body
const cached = getCacheEntry(normalized);
if (cached) {
return sliceToChunk(cached, offset, clampedByteCount);
}
// Remote URL - try Range request, fall back to full GET if not supported
let response = await fetch(normalized, {
headers: {
Range: `bytes=${offset}-${offset + clampedByteCount - 1}`,
},
});
// If server doesn't support Range (501, 416, etc.), fall back to plain GET
if (!response.ok && response.status !== 206) {
response = await fetch(normalized);
if (!response.ok) {
throw new Error(
`Failed to fetch PDF: ${response.status} ${response.statusText}`,
);
}
}
// HTTP 200 means the server ignored our Range header and sent the full body.
// Cache it so subsequent chunk requests don't re-download, then slice.
if (response.status === 200) {
// Check Content-Length header first as a preliminary size check
const contentLength = response.headers.get("content-length");
if (contentLength) {
const declaredSize = parseInt(contentLength, 10);
if (declaredSize > CACHE_MAX_PDF_SIZE_BYTES) {
throw new Error(
`PDF too large to cache: ${declaredSize} bytes exceeds ${CACHE_MAX_PDF_SIZE_BYTES} byte limit`,
);
}
}
const fullData = new Uint8Array(await response.arrayBuffer());
// Check actual size (may differ from Content-Length)
if (fullData.length > CACHE_MAX_PDF_SIZE_BYTES) {
throw new Error(
`PDF too large to cache: ${fullData.length} bytes exceeds ${CACHE_MAX_PDF_SIZE_BYTES} byte limit`,
);
}
setCacheEntry(normalized, fullData);
return sliceToChunk(fullData, offset, clampedByteCount);
}
// HTTP 206 Partial Content — parse total size from Content-Range header
const contentRange = response.headers.get("content-range");
let totalBytes = 0;
if (contentRange) {
const match = contentRange.match(/bytes \d+-\d+\/(\d+)/);
if (match) {
totalBytes = parseInt(match[1], 10);
}
}
const data = new Uint8Array(await response.arrayBuffer());
return { data, totalBytes };
}
return {
readPdfRange,
getCacheSize: () => cache.size,
clearCache: () => {
for (const url of [...cache.keys()]) {
deleteCacheEntry(url);
}
},
};
}
// =============================================================================
// MCP Roots
// =============================================================================
/**
* Query the client for roots and update allowedLocalDirs with any file:// roots
* that point to existing directories.
*/
async function refreshRoots(server: Server): Promise<void> {
if (!server.getClientCapabilities()?.roots) return;
try {
const { roots } = await server.listRoots();
allowedLocalDirs.clear();
for (const root of roots) {
if (isFileUrl(root.uri)) {
const dir = fileUrlToPath(root.uri);
const resolved = path.resolve(dir);
try {
const s = fs.statSync(resolved);
if (s.isFile()) {
console.error(
`[pdf-server] Root is a file, not a directory (skipped): ${resolved}`,
);
allowedLocalFiles.add(resolved);
} else if (s.isDirectory()) {
allowedLocalDirs.add(resolved);
console.error(`[pdf-server] Root directory allowed: ${resolved}`);
}
} catch {
// stat failed — skip non-existent roots
}
}
}
} catch (err) {
console.error(
`[pdf-server] Failed to list roots: ${err instanceof Error ? err.message : err}`,
);
}
}
// =============================================================================
// PDF Form Field Extraction
// =============================================================================
/**
* Extract form fields from a PDF and build an elicitation schema.
* Returns null if the PDF has no form fields.
*/
/** Shape of field objects returned by pdfjs-dist's getFieldObjects(). */
interface PdfJsFieldObject {
type: string;
name: string;
editable: boolean;
exportValues?: string;
items?: Array<{ exportValue: string; displayValue: string }>;
}
/** Detailed info about a form field, including its location on the page. */
interface FormFieldInfo {
name: string;
type: string;
page: number;
label?: string;
/** Bounding box in model coordinates (top-left origin) */
x: number;
y: number;
width: number;
height: number;
/** Radio button export value (buttonValue) — distinguishes widgets that share a field name. */
exportValue?: string;
/** Dropdown/listbox option values, as seen in the widget's `options` array. */
options?: string[];
}
/**
* Extract detailed form field info (name, type, page, bounding box, label)
* from a PDF. Bounding boxes are converted to model coordinates (top-left origin).
*/
async function extractFormFieldInfo(
url: string,
readRange: (
url: string,
offset: number,
byteCount: number,
) => Promise<{ data: Uint8Array; totalBytes: number }>,
): Promise<FormFieldInfo[]> {
const { totalBytes } = await readRange(url, 0, 1);
const { data } = await readRange(url, 0, totalBytes);
const loadingTask = getDocument({
data,
standardFontDataUrl: STANDARD_FONT_DATA_URL,
StandardFontDataFactory: FetchStandardFontDataFactory,
// We only introspect form fields (never render) — silence residual
// warnings like "Unimplemented border style: inset".
verbosity: VerbosityLevel.ERRORS,
});
const pdfDoc = await loadingTask.promise;
const fields: FormFieldInfo[] = [];
try {
for (let i = 1; i <= pdfDoc.numPages; i++) {
const page = await pdfDoc.getPage(i);
const pageHeight = page.getViewport({ scale: 1.0 }).height;
const annotations = await page.getAnnotations();
for (const ann of annotations) {
// Only include form widgets (annotationType 20)
if (ann.annotationType !== 20) continue;
if (!ann.rect) continue;
const fieldName = ann.fieldName || "";
const fieldType = ann.fieldType || "unknown";
// PDF rect is [x1, y1, x2, y2] in bottom-left origin
const x1 = Math.min(ann.rect[0], ann.rect[2]);
const y1 = Math.min(ann.rect[1], ann.rect[3]);
const x2 = Math.max(ann.rect[0], ann.rect[2]);
const y2 = Math.max(ann.rect[1], ann.rect[3]);
const width = x2 - x1;
const height = y2 - y1;
// Convert to model coords (top-left origin): modelY = pageHeight - pdfY - height
const modelY = pageHeight - y2;
// Choice widgets (combo/listbox) carry `options` as
// [{exportValue, displayValue}]. Expose export values — that's
// what fill_form needs.
let options: string[] | undefined;
if (Array.isArray(ann.options) && ann.options.length > 0) {
options = ann.options
.map((o: { exportValue?: string }) => o?.exportValue)
.filter((v: unknown): v is string => typeof v === "string");
}
fields.push({
name: fieldName,
type: fieldType,
page: i,
x: Math.round(x1),
y: Math.round(modelY),
width: Math.round(width),
height: Math.round(height),
...(ann.alternativeText ? { label: ann.alternativeText } : undefined),
// Radio: buttonValue is the per-widget export value — the only
// thing distinguishing three `size [Btn]` lines from each other.
...(ann.radioButton && ann.buttonValue != null
? { exportValue: String(ann.buttonValue) }
: undefined),
...(options?.length ? { options } : undefined),
});
}
}
} finally {
pdfDoc.destroy();
}
return fields;
}
async function extractFormSchema(
url: string,
readRange: (
url: string,
offset: number,