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 situation | Recommended path |
|---|---|
| You call a model API from your own backend and handle tool calls in your code | Plain tool calling: agent quickstart. No MCP layer. |
| You use an agent framework that accepts JSON Schema tools | Plain 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 PDFs | The self-run MCP server on this page |
| Several MCP hosts on one machine should share the same PDF tool | The 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
- The MCP host launches
mcp-server.mjsas a child process and talks to it over stdio (newline-delimited JSON-RPC on stdin and stdout). - The host calls
tools/listand finds one tool,generate_pdf, with the same JSON Schema as the quickstart:html, ortemplate_idwithdata. - When the model wants a document, the host sends
tools/callwith the arguments. - 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. - The server answers with that reference as text, as a
resource_linkto the file and asstructuredContent. Failures come back as a result withisError: truethat 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:
- mcp-server.mjs, the MCP adapter shown below
- generate-pdf-tool.ts, the tool schema and executor from the quickstart
- package.json, which marks the folder as ES modules (the SDK ships ES modules only)
Then install the server package of the official TypeScript SDK:
npm install @modelcontextprotocol/server@^2The 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.logcorrupts 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: trueso 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_linkpoints at the saved file, andstructuredContentgives 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: truesays the tool talks to an external service, andreadOnlyHint: falsesays 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:
| Scenario | Result |
|---|---|
tools/list advertises generate_pdf with the shared JSON Schema | Pass |
Template call returns a document reference and a resource_link | Pass |
| HTML call returns a document reference | Pass |
Missing template field (422) returns isError with the field name | Pass |
Unknown template (404) returns isError | Pass |
A 503 followed by success: both requests carried the same Idempotency-Key | Pass |
| Unknown argument rejected by SDK schema validation, no HTTP request | Pass |
Both template_id and html rejected by the executor, no HTTP request | Pass |
| Unknown tool name returns a protocol error | Pass |
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,
dataandhtmlhave size caps, and exactly one oftemplate_idorhtmlis allowed. - Watch the
file://links. Aresource_linkto 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
Originheader, 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
- Agent quickstart: the same tool without MCP, a complete agent loop, and error handling and idempotency in detail.
- HTML to PDF API: what the API underneath renders and the options it accepts.
- API reference: every endpoint, option and status code.
- Invoice template and report template: sample templates with the data the examples above use.
- Error handling guide: retry and backoff policy for the REST API underneath.
- API authentication guide: storing and rotating the key you pass to the server.
Sources
- Model Context Protocol specification 2025-11-25: Tools · accessed 23 November 2026
- Model Context Protocol specification 2025-11-25: Transports · accessed 23 November 2026
- Model Context Protocol specification 2025-11-25: Authorization · accessed 23 November 2026
- Model Context Protocol: Build an MCP server · accessed 22 November 2026
- MCP TypeScript SDK (README) · accessed 22 November 2026