File size: 7,069 Bytes
e1cc3bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * PDF MCP Server - Didactic Example
 *
 * Demonstrates:
 * - Chunked data through size-limited tool responses
 * - Model context updates (current page text + selection)
 * - Display modes: fullscreen with scrolling vs inline with resize
 * - External link opening (openLink)
 */
import {
  registerAppResource,
  registerAppTool,
  RESOURCE_MIME_TYPE,
} from "@modelcontextprotocol/ext-apps/server";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import type {
  CallToolResult,
  ReadResourceResult,
} from "@modelcontextprotocol/sdk/types.js";
import fs from "node:fs/promises";
import path from "node:path";
import { z } from "zod";

import {
  buildPdfIndex,
  findEntryByUrl,
  createEntry,
  isArxivUrl,
  isFileUrl,
  toFileUrl,
  normalizeArxivUrl,
} from "./src/pdf-indexer.js";
import { loadPdfBytesChunk, populatePdfMetadata } from "./src/pdf-loader.js";
import {
  ReadPdfBytesInputSchema,
  PdfBytesChunkSchema,
  type PdfIndex,
} from "./src/types.js";
import { startServer } from "./server-utils.js";

const DIST_DIR = path.join(import.meta.dirname, "dist");
const RESOURCE_URI = "ui://pdf-viewer/mcp-app.html";
const DEFAULT_PDF = "https://arxiv.org/pdf/1706.03762"; // Attention Is All You Need

let pdfIndex: PdfIndex | null = null;

export function createServer(): McpServer {
  const server = new McpServer({ name: "PDF Server", version: "1.0.0" });

  // Tool: list_pdfs
  server.tool(
    "list_pdfs",
    "List indexed PDFs",
    {},
    async (): Promise<CallToolResult> => {
      if (!pdfIndex) throw new Error("Not initialized");
      return {
        content: [
          { type: "text", text: JSON.stringify(pdfIndex.entries, null, 2) },
        ],
        structuredContent: { entries: pdfIndex.entries },
      };
    },
  );

  // Tool: read_pdf_bytes (app-only) - Chunked binary loading
  registerAppTool(
    server,
    "read_pdf_bytes",
    {
      title: "Read PDF Bytes",
      description: "Load binary data in chunks",
      inputSchema: ReadPdfBytesInputSchema.shape,
      outputSchema: PdfBytesChunkSchema,
      _meta: { ui: { visibility: ["app"] } },
    },
    async (args: unknown): Promise<CallToolResult> => {
      if (!pdfIndex) throw new Error("Not initialized");
      const {
        url: rawUrl,
        offset,
        byteCount,
      } = ReadPdfBytesInputSchema.parse(args);
      const url = isArxivUrl(rawUrl) ? normalizeArxivUrl(rawUrl) : rawUrl;
      let entry = findEntryByUrl(pdfIndex, url);

      // Dynamically add arxiv URLs (handles server restart between display_pdf and read_pdf_bytes)
      if (!entry) {
        if (isFileUrl(url)) {
          throw new Error("File URLs must be in the initial list");
        }
        if (!isArxivUrl(url)) {
          throw new Error(`PDF not found: ${url}`);
        }
        entry = createEntry(url);
        await populatePdfMetadata(entry);
        pdfIndex.entries.push(entry);
      }

      const chunk = await loadPdfBytesChunk(entry, offset, byteCount);
      return {
        content: [
          {
            type: "text",
            text: `${chunk.byteCount} bytes at ${chunk.offset}/${chunk.totalBytes}`,
          },
        ],
        structuredContent: chunk,
      };
    },
  );

  // Tool: display_pdf - Interactive viewer with UI
  registerAppTool(
    server,
    "display_pdf",
    {
      title: "Display PDF",
      description: `Display an interactive PDF viewer in the chat.

Use this tool when the user asks to view, display, read, or open a PDF. Accepts:
- URLs from list_pdfs (preloaded PDFs)
- Any arxiv.org URL (loaded dynamically)

The viewer supports zoom, navigation, text selection, and fullscreen mode.`,
      inputSchema: {
        url: z
          .string()
          .default(DEFAULT_PDF)
          .describe("PDF URL (arxiv.org for dynamic loading)"),
        page: z.number().min(1).default(1).describe("Initial page"),
      },
      outputSchema: z.object({
        url: z.string(),
        title: z.string().optional(),
        pageCount: z.number(),
        initialPage: z.number(),
      }),
      _meta: { ui: { resourceUri: RESOURCE_URI } },
    },
    async ({ url: rawUrl, page }): Promise<CallToolResult> => {
      if (!pdfIndex) throw new Error("Not initialized");

      // Normalize arxiv URLs to PDF format
      const url = isArxivUrl(rawUrl) ? normalizeArxivUrl(rawUrl) : rawUrl;

      let entry = findEntryByUrl(pdfIndex, url);

      if (!entry) {
        if (isFileUrl(url)) {
          throw new Error("File URLs must be in the initial list");
        }
        if (!isArxivUrl(url)) {
          throw new Error(`Only arxiv.org URLs can be loaded dynamically`);
        }

        entry = createEntry(url);
        await populatePdfMetadata(entry);
        pdfIndex.entries.push(entry);
      }

      const result = {
        url: entry.url,
        title: entry.metadata.title,
        pageCount: entry.metadata.pageCount,
        initialPage: Math.min(page, entry.metadata.pageCount),
      };

      return {
        content: [
          {
            type: "text",
            text: `Displaying interactive PDF viewer${entry.metadata.title ? ` for "${entry.metadata.title}"` : ""} (${entry.url}, ${entry.metadata.pageCount} pages)`,
          },
        ],
        structuredContent: result,
      };
    },
  );

  // Resource: UI HTML
  registerAppResource(
    server,
    RESOURCE_URI,
    RESOURCE_URI,
    { mimeType: RESOURCE_MIME_TYPE },
    async (): Promise<ReadResourceResult> => {
      const html = await fs.readFile(
        path.join(DIST_DIR, "mcp-app.html"),
        "utf-8",
      );
      return {
        contents: [
          { uri: RESOURCE_URI, mimeType: RESOURCE_MIME_TYPE, text: html },
        ],
      };
    },
  );

  return server;
}

// CLI
function parseArgs(): { urls: string[]; stdio: boolean } {
  const args = process.argv.slice(2);
  const urls: string[] = [];
  let stdio = false;

  for (const arg of args) {
    if (arg === "--stdio") {
      stdio = true;
    } else if (!arg.startsWith("-")) {
      // Convert local paths to file:// URLs, normalize arxiv URLs
      let url = arg;
      if (
        !arg.startsWith("http://") &&
        !arg.startsWith("https://") &&
        !arg.startsWith("file://")
      ) {
        url = toFileUrl(arg);
      } else if (isArxivUrl(arg)) {
        url = normalizeArxivUrl(arg);
      }
      urls.push(url);
    }
  }

  return { urls: urls.length > 0 ? urls : [DEFAULT_PDF], stdio };
}

async function main() {
  const { urls, stdio } = parseArgs();

  console.error(`[pdf-server] Initializing with ${urls.length} PDF(s)...`);
  pdfIndex = await buildPdfIndex(urls);
  console.error(`[pdf-server] Ready`);

  if (stdio) {
    await createServer().connect(new StdioServerTransport());
  } else {
    const port = parseInt(process.env.PORT ?? "3001", 10);
    await startServer(createServer, { port, name: "PDF Server" });
  }
}

main().catch((e) => {
  console.error(e);
  process.exit(1);
});