* pdf-server: support folders in cli + files in roots * fix(pdf-server): use path.relative for robust ancestor dir matching - Replace string prefix matching (startsWith) with path.relative-based isAncestorDir() which correctly handles trailing slashes, path normalization, and prevents both .. traversal and prefix attacks. - Use path.resolve consistently when adding paths to allowedLocalFiles and allowedLocalDirs (main.ts was missing this). - Use resolved path for exact file match check in validateUrl. - Improve error message formatting for easier debugging. - Add tests for trailing slashes, grandparent dirs, and isAncestorDir. * chore(pdf-server): remove JSONL interaction logging Remove the withLogging transport wrapper, logInteraction helper, InteractionLogger type, and all log parameter threading that were added for debugging. * fix(pdf-server): support computer:// URL scheme for local files Some clients (e.g. Claude Code) use computer:// instead of file:// for local file references. Handle both schemes in isFileUrl and fileUrlToPath. * fix(pdf-server): add debug logging for rejected files, ignore .jsonl logs * fix(pdf-server): accept bare file paths in addition to file:// URLs Clients like Claude Desktop may pass raw absolute paths (e.g. /Users/.../file.pdf) instead of file:// URLs. Handle these in validateUrl and readPdfRange. * debug(pdf-server): add hex char diagnostics for path mismatch * fix(pdf-server): resolve symlinks to handle sandbox path remapping Use fs.realpathSync to resolve symlinks/bind mounts when comparing file paths against allowed directories. This fixes the path namespace mismatch where Claude Desktop sends container paths (e.g. /sessions/...) while MCP roots use host paths (e.g. /Users/...). Both the file path and directory paths are resolved through symlinks before comparison, so either side can be a symlink. Also stores realpath of roots in allowedLocalDirs/Files so matching works in both directions. Removes verbose hex diagnostics (no longer needed). * fix(pdf-server): decode percent-encoded bare paths (e.g. %20 for spaces) Clients may send bare file paths with percent-encoded characters (e.g., Application%20Support). Apply decodeURIComponent to bare paths before resolving, matching the behavior already used for file:// URLs. * fix(pdf-server): add full diagnostics to client-facing error message Include url, resolved path, realpath, allowedFiles, and per-directory path.relative results in the error returned to the client, so we can diagnose why isAncestorDir fails when paths look identical. * debug(pdf-server): add hex dump to diagnose invisible char differences path.relative returns 10 levels of .. despite paths looking identical, meaning they differ at the byte level. Add hex dump of first 30 chars of both paths to catch invisible Unicode or encoding differences. * fix(pdf-server): use inode comparison for bind-mount path matching The cowork VM remaps paths via bind mounts: the tool input uses VM-internal paths (/sessions/...) while MCP roots use host paths (/Users/...). Since path.relative can't match across bind mounts, compare directory inodes instead (dev+ino from fs.statSync). Walks up the file's parent directories checking each against allowed dirs by inode, which works regardless of path namespace differences. * fix(pdf-server): resolve VM-internal paths via directory basename matching When the MCP server runs on the host but receives unrewritten VM paths (e.g., /sessions/name/mnt/uploads/file.pdf), the tool call url argument isn't rewritten by the cowork VM proxy because it doesn't know which arguments are file paths. Fix: when path validation fails, try to match the file by finding the directory basename (e.g., 'uploads') in the VM path and looking for the relative path suffix under each allowed directory on the host. Also returns the resolved host path so readPdfRange reads the correct file on the host filesystem. * revert(pdf-server): remove resolveVmPath hack The VM path mismatch (VM-internal paths not rewritten in tool call arguments) should be fixed in the cowork VM proxy layer, not worked around in the MCP server. Removes: - resolveVmPath() function - resolvedPath field from validateUrl return type - effectiveUrl remapping in tool handlers - VM path resolution test * nit
153 lines
4.1 KiB
TypeScript
153 lines
4.1 KiB
TypeScript
/**
|
|
* Entry point for running the MCP server.
|
|
* Run with: npx mcp-pdf-server
|
|
* Or: node dist/index.js [--stdio] [pdf-urls...]
|
|
*/
|
|
|
|
import fs from "node:fs";
|
|
import path from "node:path";
|
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
import { createMcpExpressApp } from "@modelcontextprotocol/sdk/server/express.js";
|
|
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
import cors from "cors";
|
|
import type { Request, Response } from "express";
|
|
import {
|
|
createServer,
|
|
isArxivUrl,
|
|
isFileUrl,
|
|
normalizeArxivUrl,
|
|
pathToFileUrl,
|
|
fileUrlToPath,
|
|
allowedLocalFiles,
|
|
DEFAULT_PDF,
|
|
allowedLocalDirs,
|
|
} from "./server.js";
|
|
|
|
/**
|
|
* Starts an MCP server with Streamable HTTP transport in stateless mode.
|
|
*/
|
|
export async function startStreamableHTTPServer(
|
|
createServer: () => McpServer,
|
|
): Promise<void> {
|
|
const port = parseInt(process.env.PORT ?? "3001", 10);
|
|
|
|
const app = createMcpExpressApp({ host: "0.0.0.0" });
|
|
app.use(cors());
|
|
|
|
app.all("/mcp", async (req: Request, res: Response) => {
|
|
const server = createServer();
|
|
const transport = new StreamableHTTPServerTransport({
|
|
sessionIdGenerator: undefined,
|
|
});
|
|
|
|
res.on("close", () => {
|
|
transport.close().catch(() => {});
|
|
server.close().catch(() => {});
|
|
});
|
|
|
|
try {
|
|
await server.connect(transport);
|
|
await transport.handleRequest(req, res, req.body);
|
|
} catch (error) {
|
|
console.error("MCP error:", error);
|
|
if (!res.headersSent) {
|
|
res.status(500).json({
|
|
jsonrpc: "2.0",
|
|
error: { code: -32603, message: "Internal server error" },
|
|
id: null,
|
|
});
|
|
}
|
|
}
|
|
});
|
|
|
|
const httpServer = app.listen(port, (err) => {
|
|
if (err) {
|
|
console.error("Failed to start server:", err);
|
|
process.exit(1);
|
|
}
|
|
console.log(`MCP server listening on http://localhost:${port}/mcp`);
|
|
});
|
|
|
|
const shutdown = () => {
|
|
console.log("\nShutting down...");
|
|
httpServer.close(() => process.exit(0));
|
|
};
|
|
|
|
process.on("SIGINT", shutdown);
|
|
process.on("SIGTERM", shutdown);
|
|
}
|
|
|
|
/**
|
|
* Starts an MCP server with stdio transport.
|
|
*
|
|
* @param createServer - Factory function that creates a new McpServer instance.
|
|
*/
|
|
export async function startStdioServer(
|
|
createServer: () => McpServer,
|
|
): Promise<void> {
|
|
await createServer().connect(new StdioServerTransport());
|
|
}
|
|
|
|
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 = pathToFileUrl(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();
|
|
|
|
// Register local files in whitelist
|
|
for (const url of urls) {
|
|
if (isFileUrl(url)) {
|
|
const filePath = path.resolve(fileUrlToPath(url));
|
|
if (fs.existsSync(filePath)) {
|
|
const s = fs.statSync(filePath);
|
|
if (s.isFile()) {
|
|
allowedLocalFiles.add(filePath);
|
|
console.error(`[pdf-server] Registered local file: ${filePath}`);
|
|
} else if (s.isDirectory()) {
|
|
allowedLocalDirs.add(filePath);
|
|
console.error(`[pdf-server] Registered local directory: ${filePath}`);
|
|
}
|
|
} else {
|
|
console.error(`[pdf-server] Warning: File not found: ${filePath}`);
|
|
}
|
|
}
|
|
}
|
|
|
|
console.error(`[pdf-server] Ready (${urls.length} URL(s) configured)`);
|
|
|
|
if (stdio) {
|
|
await startStdioServer(createServer);
|
|
} else {
|
|
await startStreamableHTTPServer(createServer);
|
|
}
|
|
}
|
|
|
|
main().catch((e) => {
|
|
console.error(e);
|
|
process.exit(1);
|
|
});
|