Skip to content

Docs

Connect SublimePDF to MCP clients

MCP is optional for SublimePDF. Expose PDF generation to MCP hosts with a small self-run stdio server built on the official MCP TypeScript SDK and the REST API.

Updated 9 min readSublimePDF Team

The Model Context Protocol (MCP) is one way to give an AI agent access to SublimePDF. It is not a requirement. Any model that supports ordinary tool calling can generate PDFs through the REST API with a JSON Schema tool and a small executor, and the agent quickstart shows that path end to end. Use MCP when your agent runs inside an MCP host you do not control the loop of, such as a desktop assistant, an IDE or an agent runtime that discovers tools over MCP.

Do you need MCP?

Your situationRecommended path
You call a model API from your own backend and handle tool calls in your codePlain tool calling: agent quickstart. No MCP layer.
You use an agent framework that accepts JSON Schema toolsPlain tool calling, registered through the framework's tool wrapper
Your agent runs in an MCP host (desktop assistant, IDE, agent runtime) and you want it to create PDFsThe self-run MCP server on this page
Several MCP hosts on one machine should share the same PDF toolThe self-run MCP server, configured once per host

Both paths end in the same REST calls: POST /html-to-pdf with HTML (and optional data), or POST /templates/{id}/generate with a saved template ID and JSON data. The tool accepts either input on equal terms, and the API key stays in your process either way.

How the MCP route works

  1. The MCP host launches mcp-server.mjs as a child process and talks to it over stdio (newline-delimited JSON-RPC on stdin and stdout).
  2. The host calls tools/list and finds one tool, generate_pdf, with the same JSON Schema as the quickstart: html, or template_id with data.
  3. When the model wants a document, the host sends tools/call with the arguments.
  4. The server passes them to executeGeneratePdf. That function validates them, calls SublimePDF with the key from the server's environment, saves the PDF and builds a document reference.
  5. The server answers with that reference as text, as a resource_link to the file and as structuredContent. Failures come back as a result with isError: true that the model can read and act on.

The MCP authorization specification covers HTTP-based transports. For stdio it says implementations "SHOULD NOT follow this specification, and instead retrieve credentials from the environment". That is what this server does: the host passes SUBLIMEPDF_API_KEY as an environment variable, and the key never appears in tool schemas, arguments or results.

Step 1: Get the files and install the SDK

You need Node.js 22.18 or later. The server imports the TypeScript executor directly through Node's built-in type stripping. Download the files into one folder:

Then install the server package of the official TypeScript SDK:

npm install @modelcontextprotocol/server@^2

The example was built and tested with @modelcontextprotocol/server 2.4.0, the v2 line of the SDK, which publishes split server and client packages. The older v1 package, @modelcontextprotocol/sdk, uses different import paths. This example was not tested with v1.

Step 2: The server

This is the complete server. It registers the existing JSON Schema with fromJsonSchema, so the schema the MCP host sees is the same one plain tool-calling agents use, with no second Zod copy to keep in sync.

import { McpServer, fromJsonSchema } from "@modelcontextprotocol/server";
import { serveStdio } from "@modelcontextprotocol/server/stdio";
import { executeGeneratePdf, generatePdfTool } from "./generate-pdf-tool.ts";
 
function createServer() {
    const server = new McpServer({ name: "sublimepdf-generate-pdf", version: "1.0.0" });
 
    server.registerTool(
        generatePdfTool.name,
        {
            title: "Generate PDF",
            description: generatePdfTool.description,
            inputSchema: fromJsonSchema(generatePdfTool.parameters),
            annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
        },
        async (args) => {
            const result = await executeGeneratePdf(args);
            if (!result.ok) {
                return { isError: true, content: [{ type: "text", text: JSON.stringify(result.error) }] };
            }
            const doc = result.document;
            return {
                content: [
                    { type: "text", text: JSON.stringify(doc) },
                    { type: "resource_link", uri: doc.uri, name: doc.file_name, mimeType: doc.content_type },
                ],
                structuredContent: doc,
            };
        },
    );
 
    return server;
}
 
serveStdio(createServer, { onerror: (error) => console.error("[mcp-server]", error) });

Notes on the choices:

  • Logging goes to stderr. On the stdio transport the specification says the server "MUST NOT write anything to its stdout that is not a valid MCP message". A stray console.log corrupts the stream. The executor and the server only write to stderr.
  • Execution errors are results, not exceptions. The specification separates protocol errors (unknown tool, malformed request) from tool execution errors (API failures, invalid input), which go back in a normal result with isError: true so the model can self-correct. The executor already produces errors in that shape.
  • The result carries a reference, not the PDF. Embedding the PDF as a resource would put tens of kilobytes of base64 into the conversation. The resource_link points at the saved file, and structuredContent gives hosts a machine-readable copy. The specification asks tools that return structured content to also include the serialized JSON as text, which the first content block does.
  • Annotations are hints. openWorldHint: true says the tool talks to an external service, and readOnlyHint: false says it creates something. The specification tells clients to treat annotations as untrusted unless they come from trusted servers, so they inform the host's UI but do not replace your own checks.

Step 3: Register it with your MCP host

Hosts that launch stdio servers ask for the same three things: a command, its arguments and environment variables. The file location and exact key names differ between hosts, so check your host's documentation. A typical entry looks like this:

{
  "mcpServers": {
    "sublimepdf": {
      "command": "node",
      "args": ["/absolute/path/to/mcp-server.mjs"],
      "env": {
        "SUBLIMEPDF_API_KEY": "YOUR_API_KEY",
        "PDF_OUTPUT_DIR": "/absolute/path/to/generated-pdfs"
      }
    }
  }
}

Use absolute paths: hosts often start servers from a different working directory. If your host can read secrets from the system keychain or a secret manager, use that instead of a plain-text key in the config file.

What the client sees

These responses come from the test run described below, using the official SDK client over stdio. File paths are shortened. tools/list returns the tool with the shared schema:

{
  "name": "generate_pdf",
  "title": "Generate PDF",
  "inputSchema": {
    "type": "object",
    "properties": { "template_id": { "...": "..." }, "data": { "...": "..." }, "html": { "...": "..." }, "filename": { "...": "..." } },
    "additionalProperties": false
  },
  "annotations": { "readOnlyHint": false, "destructiveHint": false, "idempotentHint": false, "openWorldHint": true }
}

A successful tools/call with template_id: "report" and the sample report data:

{
  "content": [
    { "type": "text", "text": "{\"document_id\":\"2c0805f0-...\",\"source\":\"template\",\"template_id\":\"report\",\"file_name\":\"week-47-report.pdf\",\"bytes\":113951,\"pages\":2,...}" },
    { "type": "resource_link", "uri": "file:///.../week-47-report.pdf", "name": "week-47-report.pdf", "mimeType": "application/pdf" }
  ],
  "structuredContent": { "document_id": "2c0805f0-...", "source": "template", "template_id": "report", "file_name": "week-47-report.pdf", "bytes": 113951, "pages": 2, "content_type": "application/pdf" }
}

A call with a required template field missing comes back as a tool execution error the model can fix:

{
  "isError": true,
  "content": [
    { "type": "text", "text": "{\"status\":422,\"type\":\"validation_error\",\"message\":\"data.summary is required\",\"field\":\"summary\",\"retryable\":false,\"instruction\":\"The data is invalid at \\\"summary\\\". Correct that value (or ask the user for it) and call the tool again once. Do not resend the same arguments.\"}" }
  ]
}

Arguments that break the schema never reach the executor. The SDK validates them against inputSchema and returns isError: true with "Input validation error: Invalid arguments for tool generate_pdf: data must NOT have additional properties". Calling a tool name the server does not have is a protocol error: the client received JSON-RPC error code -32602, "Tool generate_docx not found".

How it was tested

The repository's MCP test installs the SDK in a scratch directory outside the project. It starts the local mock of the SublimePDF API, launches mcp-server.mjs through the SDK's StdioClientTransport, and drives it with the SDK Client. Nine scenarios passed with @modelcontextprotocol/server and @modelcontextprotocol/client 2.4.0 on Node.js 24.5, most recently on 23 November 2026 after the tool description was revised:

ScenarioResult
tools/list advertises generate_pdf with the shared JSON SchemaPass
Template call returns a document reference and a resource_linkPass
HTML call returns a document referencePass
Missing template field (422) returns isError with the field namePass
Unknown template (404) returns isErrorPass
A 503 followed by success: both requests carried the same Idempotency-KeyPass
Unknown argument rejected by SDK schema validation, no HTTP requestPass
Both template_id and html rejected by the executor, no HTTP requestPass
Unknown tool name returns a protocol errorPass

The server file also type-checks with tsc --strict --checkJs against the SDK's type definitions. What was not tested: a production SublimePDF account, the Streamable HTTP transport, MCP authorization, and any particular desktop host. The mock answers HTML calls with a fixed placeholder PDF, not a rendering of your HTML.

Security notes

  • Keep a person in the loop for documents that leave your system. The specification says there "SHOULD always be a human in the loop with the ability to deny tool invocations". Most hosts ask before running a tool. Keep that confirmation on for this server.
  • Treat arguments as untrusted. The SDK validates against the schema, and the executor validates again: file names cannot contain directories, data and html have size caps, and exactly one of template_id or html is allowed.
  • Watch the file:// links. A resource_link to a local file is only useful to a host on the same machine. If the agent runs elsewhere, change the executor to upload the PDF to your storage and return that URL or key instead.
  • Remote servers need more work. Serving this tool over Streamable HTTP means following the transport's security rules (validate the Origin header, bind local servers to 127.0.0.1) and the HTTP authorization specification. Start with stdio unless you need a shared remote server.

Next steps

Sources

  1. Model Context Protocol specification 2025-11-25: Tools · accessed 23 November 2026
  2. Model Context Protocol specification 2025-11-25: Transports · accessed 23 November 2026
  3. Model Context Protocol specification 2025-11-25: Authorization · accessed 23 November 2026
  4. Model Context Protocol: Build an MCP server · accessed 22 November 2026
  5. MCP TypeScript SDK (README) · accessed 22 November 2026

Generate your first PDF with one API call.

Create an account, copy an API key and send HTML, or a template ID with JSON data, from your code or your agent.