Doramagic Project Pack · Human Manual

mcp-server

Related topics: Project Structure, PDF Generation Tools, Installation and Setup

Introduction

Related topics: Project Structure, PDF Generation Tools, Installation and Setup

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Core Functionality

Continue reading this section for the full explanation and source context.

Section Component Overview

Continue reading this section for the full explanation and source context.

Section File Structure

Continue reading this section for the full explanation and source context.

Related topics: Project Structure, PDF Generation Tools, Installation and Setup

Introduction

TemplateFox MCP Server is a Model Context Protocol (MCP) server implementation that bridges AI assistants with the TemplateFox PDF generation API. This server enables AI assistants such as Claude, Cursor, and Windsurf to generate PDFs from templates directly through natural language commands. Source: README.md

Overview

The MCP server acts as an intermediary layer that translates MCP tool calls into TemplateFox API requests. It provides a standardized interface for AI assistants to interact with PDF generation capabilities without requiring direct API integration knowledge. Source: README.md

Core Functionality

The server exposes eight primary tools that cover the complete PDF generation workflow:

ToolPurpose
generate_pdfSynchronous PDF generation from templates
generate_pdf_asyncAsynchronous PDF generation with job queuing
get_pdf_job_statusPoll status of async generation jobs
list_pdf_jobsList and filter async job history
list_templatesDiscover available PDF templates
get_template_fieldsRetrieve template variable definitions
get_account_infoCheck account credits and status
list_transactionsView credit transaction history

Source: README.md

Architecture

The server follows a modular architecture with clear separation of concerns across three main source files.

Component Overview

graph TD
    A["AI Assistant<br/>(Claude, Cursor, Windsurf)"] --> B["MCP Client"]
    B --> C["TemplateFox MCP Server"]
    C --> D["API Client<br/>(api-client.ts)"]
    C --> E["Tools Registry<br/>(tools.ts)"]
    D --> F["TemplateFox API<br/>api.templatefox.com"]
    E --> D
    
    subgraph "Transport Modes"
        G["StdioServerTransport<br/>(Local/CLI)"]
        H["StreamableHTTPServerTransport<br/>(HTTP/Cloud)"]
    end
    
    C --> G
    C --> H

File Structure

FileResponsibility
src/index.tsServer initialization, transport configuration, HTTP middleware
src/tools.tsMCP tool definitions using Zod schemas for validation
src/api-client.tsHTTP request handling, API key management, AsyncLocalStorage context

Source: src/index.ts:1-60, src/tools.ts:1-50, src/api-client.ts:1-35

Transport Modes

The server supports two distinct transport mechanisms, automatically selected based on environment configuration.

Standard I/O Mode (Default)

The StdioServerTransport handles local and CLI-based deployments. This mode is activated by default when running via npx or direct Node.js execution without the PORT environment variable. Source: src/index.ts:35-40

graph LR
    A["AI Assistant"] -->|"stdio"| B["StdioServerTransport"]
    B --> C["McpServer Instance"]
    C --> D["Tool Handler"]
    D --> E["TemplateFox API"]

Activation:

npx -y @templatefox/mcp-server

HTTP Mode (Cloud/Remote)

The StreamableHTTPServerTransport enables remote deployments and cloud hosting. This mode activates when the PORT environment variable is set. Source: src/index.ts:21-33

Activation:

PORT=8080 TEMPLATEFOX_API_KEY=sk_your_key node dist/index.js

Remote Endpoint:

https://mcp-server-599407781746.us-central1.run.app/mcp

Source: README.md

API Key Management

The server implements a dual-layer API key resolution strategy to support both local and HTTP transport modes.

graph TD
    A["API Request"] --> B{Transport Type}
    B -->|HTTP| C["Extract from Headers"]
    B -->|Stdio| D["Read from Environment"]
    C --> E{"Key Present?"}
    D --> E
    E -->|Yes| F["AsyncLocalStorage Context"]
    E -->|No| G["Throw Error"]
    F --> H["API Client"]
    G --> I["401 Unauthorized"]

Key Resolution Priority

  1. HTTP Mode: Per-request API key from Authorization: Bearer or x-api-key header via AsyncLocalStorage
  2. Stdio Mode: Environment variable TEMPLATEFOX_API_KEY

Source: src/api-client.ts:14-28

AsyncLocalStorage Context

The server uses Node.js AsyncLocalStorage to maintain per-request API key context in HTTP mode. This ensures API keys remain isolated across concurrent requests. Source: src/api-client.ts:3-18

const apiKeyStore = new AsyncLocalStorage<string>();

export function runWithApiKey<T>(apiKey: string, fn: () => T): T {
  return apiKeyStore.run(apiKey, fn);
}

Tool Registration

Tools are registered using the @modelcontextprotocol/sdk package with Zod schema validation for all input parameters. Source: src/tools.ts:1-10

Tool Configuration Pattern

Each tool follows a consistent registration pattern:

server.tool(
  "tool_name",                    // Tool identifier
  "Description text",            // Human-readable description
  { /* Zod schema */ },          // Input validation
  { /* Hints */ },               // Read/destructive hints
  async (params) => { ... }      // Handler function
);

Tool Hints

HintDescription
readOnlyHint: trueRead-only operation (GET requests)
destructiveHint: falseNon-destructive operation

Source: src/tools.ts:50-60

Server Configuration

Environment Variables

VariableRequiredDefaultDescription
TEMPLATEFOX_API_KEYYes (Stdio)-API key starting with sk_
TEMPLATEFOX_BASE_URLNohttps://api.templatefox.comOverride API base URL
PORTNo-Enable HTTP mode when set

Source: README.md, src/api-client.ts:6

HTTP Server Middleware

When running in HTTP mode, the server configures Express with CORS and JSON parsing middleware:

const app = express();
app.use(cors());
app.use(express.json());

Endpoints:

EndpointMethodPurpose
/healthGETHealth check with version info
/mcpPOSTMCP request handling
/mcpGET/DELETEMethod not allowed (405)

Source: src/index.ts:27-45

Package Metadata

PropertyValue
Package Name@templatefox/mcp-server
Version1.10.1
Node.js Requirement>=18.0.0
LicenseMIT
MCP Nameio.github.TemplateFoxPDF/mcp-server

Source: package.json:1-25

Core Dependencies

PackageVersionPurpose
@modelcontextprotocol/sdk^1.29.0MCP protocol implementation
express^5.2.1HTTP server framework
cors^2.8.6Cross-origin resource sharing

Source: package.json:26-32

Quick Start Workflow

graph TD
    A["Configure MCP Client"] --> B["Add to Claude Desktop config"]
    A --> C["Or use claude mcp add command"]
    B --> D["Set TEMPLATEFOX_API_KEY"]
    C --> D
    D --> E["Ask AI to generate PDF"]
    E --> F["list_templates"]
    F --> G["get_template_fields"]
    G --> H["generate_pdf"]
    H --> I["Return download URL"]

Example AI prompt:

"List my PDF templates and generate an invoice using the Invoice Template with customer name 'John Doe' and amount 150.00"

Source: README.md

Next Steps

For detailed information about specific features, refer to:

  • Tool Reference: Detailed documentation for each MCP tool
  • API Client: HTTP request handling and authentication
  • Deployment: Cloud Run and Docker deployment configurations

Source: https://github.com/TemplateFoxPDF/mcp-server / Human Manual

Project Structure

Related topics: Introduction, Server Initialization, API Client

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Core Components Overview

Continue reading this section for the full explanation and source context.

Section Entry Point (src/index.ts)

Continue reading this section for the full explanation and source context.

Section API Client (src/api-client.ts)

Continue reading this section for the full explanation and source context.

Related topics: Introduction, Server Initialization, API Client

Project Structure

The TemplateFox MCP Server is a Model Context Protocol (MCP) server implementation that bridges AI assistants with the TemplateFox PDF generation API. This document provides a comprehensive overview of the project's architecture, source code organization, and build configuration.

Repository Overview

The repository is a Node.js TypeScript project published as @templatefox/mcp-server on npm. It enables AI assistants such as Claude, Cursor, and Windsurf to generate PDFs from templates through natural language interactions.

PropertyValue
Package Name@templatefox/mcp-server
Version1.10.1
LicenseMIT
Node.js Requirement>=18.0.0
Module TypeESM (ECMAScript Modules)
MCP SDK Version^1.29.0
Source: package.json:1-18

Directory Structure

mcp-server/
├── src/
│   ├── index.ts        # Main entry point with transport handling
│   ├── tools.ts        # MCP tool definitions
│   └── api-client.ts   # API communication layer
├── dist/               # Compiled JavaScript output
├── package.json        # Package configuration
├── tsconfig.json        # TypeScript configuration
├── Dockerfile           # Container deployment
└── README.md            # Documentation

Source Code Architecture

Core Components Overview

graph TD
    A[MCP Client<br/>Claude/Cursor] -->|JSON-RPC| B[Transport Layer]
    B --> C{Mode Detection}
    C -->|No PORT env| D[StdioServerTransport]
    C -->|PORT defined| E[StreamableHTTPServerTransport]
    D --> F[McpServer Instance]
    E --> G[Express HTTP Server]
    G --> F
    F --> H[registerTools]
    H --> I[API Client]
    I --> J[TemplateFox API]
    J -->|PDF/Response| I
    I --> F
    F --> B

Entry Point (`src/index.ts`)

The main entry point handles dual-mode operation based on environment configuration:

Key Responsibilities:

  • Initialize the McpServer instance with name and version
  • Detect transport mode via the PORT environment variable
  • Set up Express server with CORS for HTTP mode
  • Extract API keys from request headers for per-request authentication
Transport ModeTriggerUse Case
StdioNo PORT variableLocal AI assistant integration
HTTPPORT definedCloud Run, remote deployments

Source: src/index.ts:1-28

#### HTTP Transport Configuration

const port = process.env.PORT ? parseInt(process.env.PORT, 10) : undefined;

if (port) {
  // HTTP mode: Streamable HTTP transport
  const app = express();
  app.use(cors());
  app.use(express.json());
  // ... route handlers
}

Source: src/index.ts:24-32

#### API Key Extraction

The HTTP transport extracts API keys from incoming requests using two methods:

HeaderFormatPriority
AuthorizationBearer sk_xxxPrimary
x-api-keysk_xxxFallback

Source: src/index.ts:47-53

API Client (`src/api-client.ts`)

The API client module handles all communication with the TemplateFox API endpoint at https://api.templatefox.com.

#### API Key Management Strategy

graph TD
    A[apiRequest called] --> B{AsyncLocalStorage<br/>has key?}
    B -->|Yes| C[Return context key]
    B -->|No| D{Environment<br/>TEMPLATEFOX_API_KEY?}
    D -->|Yes| E[Return env key]
    D -->|No| F[Throw Error]
    C --> G[Make API Request]
    E --> G
    F --> H[Error: API key required]

The client implements a two-tier API key resolution strategy:

  1. Per-request context via AsyncLocalStorage (HTTP transport mode)
  2. Environment variable fallback (TEMPLATEFOX_API_KEY) for stdio mode

Source: src/api-client.ts:1-31

#### Request Building

The apiRequest function constructs HTTP requests with the following components:

ComponentValue
Base URLTEMPLATEFOX_BASE_URL or https://api.templatefox.com
MethodGET or POST
Authenticationx-api-key header
Content-Typeapplication/json (for POST)
Acceptapplication/json

Source: src/api-client.ts:49-78

MCP Tools (`src/tools.ts`)

The tools module defines all MCP tools exposed to AI assistants. Each tool corresponds to a TemplateFox API endpoint.

#### Tool Categories

CategoryToolsOperations
PDF Generationgenerate_pdf, generate_pdf_asyncCreate PDFs synchronously or asynchronously
Job Managementget_pdf_job_status, list_pdf_jobsMonitor and list async jobs
Templateslist_templates, get_template_fieldsDiscover available templates
Accountget_account_info, list_transactionsView credits and history

Source: src/tools.ts:1-200

#### Tool Definition Pattern

Each MCP tool follows this schema:

server.tool(
  "tool_name",                    // Tool identifier
  "Description for AI assistant", // Human-readable description
  { /* Zod schema parameters */}, // Input validation schema
  { /* Hints */ },                // Read/destructive hints
  async ({ params }) => {          // Handler function
    const url = "/v1/endpoint";
    const result = await apiRequest("METHOD", url, body);
    return {
      content: [{ type: "text", text: JSON.stringify(result.data) }],
      isError: !result.ok,
    };
  }
);

Source: src/tools.ts:7-22

#### Available Tools Reference

ToolHTTP MethodEndpointCreditsAsync Support
generate_pdfPOST/v1/pdf/create1No
generate_pdf_asyncPOST/v1/pdf/create-async1Yes
get_pdf_job_statusGET/v1/pdf/jobs/{job_id}0-
list_pdf_jobsGET/v1/pdf/jobs0-
list_templatesGET/v1/templates0-
get_template_fieldsGET/v1/templates/{id}/fields0-
get_account_infoGET/v1/account0-
list_transactionsGET/v1/account/transactions0-

Source: src/tools.ts

Build Configuration

Package Scripts

ScriptCommandPurpose
buildtscCompile TypeScript to JavaScript
startnode dist/index.jsRun the compiled server

Source: package.json:12-15

Dependencies

#### Production Dependencies

PackageVersionPurpose
@modelcontextprotocol/sdk^1.29.0MCP protocol implementation
express^5.2.1HTTP server framework
cors^2.8.6Cross-origin resource sharing

Source: package.json:16-20

#### Development Dependencies

PackageVersionPurpose
typescript^5.8.0TypeScript compiler
@types/node^22.0.0Node.js type definitions
@types/express^5.0.0Express type definitions
@types/cors^2.8.0CORS type definitions

Source: package.json:21-25

Binary Configuration

The package exposes a CLI binary for global installation:

{
  "bin": {
    "templatefox-mcp-server": "./dist/index.js"
  }
}

Source: package.json:9-11

Deployment Modes

Stdio Mode (Local)

Default mode for AI assistant integration via npx:

npx -y @templatefox/mcp-server

Requires TEMPLATEFOX_API_KEY environment variable.

Source: README.md:15-24

HTTP Mode (Cloud)

Enabled by setting the PORT environment variable:

PORT=8080 TEMPLATEFOX_API_KEY=sk_your_key node dist/index.js
EndpointMethodPurpose
/healthGETHealth check
/mcpPOSTMCP request handler

Source: src/index.ts:35-39

Docker Deployment

The project includes Dockerfile support for containerized deployments:

docker build -t templatefox-mcp .
docker run -p 8080:8080 templatefox-mcp

Source: README.md:66-70

Data Flow Architecture

Synchronous PDF Generation

sequenceDiagram
    participant AI as AI Assistant
    participant MCP as MCP Server
    participant API as TemplateFox API
    AI->>MCP: generate_pdf(template_id, data)
    MCP->>MCP: apiRequest(POST, /v1/pdf/create)
    MCP->>API: HTTP POST with JSON body
    API->>API: Generate PDF
    API-->>MCP: PDF URL or binary
    MCP-->>AI: JSON-RPC response

Asynchronous PDF Generation

sequenceDiagram
    participant AI as AI Assistant
    participant MCP as MCP Server
    participant API as TemplateFox API
    participant Webhook as Webhook URL
    AI->>MCP: generate_pdf_async(template_id, data, webhook_url)
    MCP->>MCP: apiRequest(POST, /v1/pdf/create-async)
    MCP->>API: HTTP POST
    API-->>MCP: { job_id, status: "pending" }
    MCP-->>AI: job_id
    loop Poll or Webhook
        API->>Webhook: POST when completed
        alt Polling Mode
            AI->>MCP: get_pdf_job_status(job_id)
            MCP-->>AI: { status, pdf_url }
        end
    end

Configuration Reference

Environment Variables

VariableRequiredDefaultDescription
TEMPLATEFOX_API_KEYYes (stdio) / No (HTTP)-API key starting with sk_
TEMPLATEFOX_BASE_URLNohttps://api.templatefox.comOverride API base URL
PORTNoundefinedEnable HTTP mode on specified port

Source: README.md:42-47

Workflow Example

A typical AI-assisted PDF generation workflow:

graph TD
    A[User Request] --> B[list_templates]
    B --> C[Choose Template]
    C --> D[get_template_fields]
    D --> E[Prepare Data]
    E --> F{Size/Complexity}
    F -->|Small Doc| G[generate_pdf]
    F -->|Large Doc| H[generate_pdf_async]
    H --> I[Poll get_pdf_job_status]
    I -->|Not Ready| I
    I -->|Ready| J[Return PDF URL]
    G --> J

Source: README.md:71-79

Keywords and Metadata

The package includes comprehensive metadata for discoverability:

{
  "keywords": [
    "mcp",
    "mcp-server", 
    "model-context-protocol",
    "pdf",
    "templatefox",
    "pdf-generation",
    "ai",
    "claude"
  ],
  "mcpName": "io.github.TemplateFoxPDF/mcp-server"
}

Source: package.json:26-34

Source: https://github.com/TemplateFoxPDF/mcp-server / Human Manual

Transport Modes

Related topics: Server Initialization, Installation and Setup, Docker Deployment

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Configuration

Continue reading this section for the full explanation and source context.

Section How It Works

Continue reading this section for the full explanation and source context.

Section API Key Handling in Stdio Mode

Continue reading this section for the full explanation and source context.

Related topics: Server Initialization, Installation and Setup, Docker Deployment

Transport Modes

The TemplateFox MCP Server supports two distinct transport modes for communication between AI assistants and the server. These modes determine how requests are routed, how API keys are authenticated, and where the server can be deployed.

Overview

The server implements the Model Context Protocol (MCP) and can operate in two primary transport configurations:

Transport ModeUse CaseDeploymentDefault
StdioLocal development, desktop AI assistantsSame machine as clientYes
Streamable HTTPRemote/cloud deployments, web servicesSeparate serverNo (when PORT is set)

Source: src/index.ts:1-50

Architecture

graph TD
    A[MCP Client] -->|Transport Choice| B
    B{Transport Mode?}
    B -->|stdio| C[StdioServerTransport]
    B -->|http| D[StreamableHTTPServerTransport]
    C --> E[Local Process Communication]
    D --> F[Express.js HTTP Server]
    F --> G[/health Endpoint]
    F --> H[/mcp Endpoint]
    E --> I[McpServer Instance]
    F --> I

Stdio Transport Mode

Stdio (Standard Input/Output) is the default transport mode when the PORT environment variable is not set. This mode uses the MCP SDK's StdioServerTransport class for synchronous, process-based communication.

Configuration

Stdio mode requires no additional configuration beyond the essential environment variable:

TEMPLATEFOX_API_KEY=sk_your_api_key_here npx -y @templatefox/mcp-server

Or with a global installation:

templatefox-mcp-server

How It Works

  1. The server initializes an McpServer instance with the server name and version. Source: src/index.ts:18-24
  1. A StdioServerTransport is created to handle stdio communication. Source: src/index.ts:30
  1. The server connects to the transport and awaits requests from stdin. Source: src/index.ts:31-32

API Key Handling in Stdio Mode

In stdio mode, the API key is retrieved from the TEMPLATEFOX_API_KEY environment variable at server startup. This key remains constant throughout the server's lifetime.

The getApiKey() function in api-client.ts implements a two-tier lookup:

function getApiKey(): string {
  // 1. Per-request key from HTTP transport (AsyncLocalStorage)
  const contextKey = apiKeyStore.getStore();
  if (contextKey) return contextKey;

  // 2. Environment variable (stdio mode)
  const key = process.env.TEMPLATEFOX_API_KEY;
  if (!key) {
    throw new Error(
      "TEMPLATEFOX_API_KEY is required. " +
      "Set it as an environment variable or pass it via the Authorization header. " +
      "Get your API key at https://app.templatefox.com/dashboard/api-keys"
    );
  }
  return key;
}

Source: src/api-client.ts:44-60

Streamable HTTP Transport Mode

HTTP transport mode enables remote deployments where the MCP server runs as a standalone web service. This mode uses the MCP SDK's StreamableHTTPServerTransport combined with Express.js for HTTP handling.

Enabling HTTP Mode

HTTP mode is activated by setting the PORT environment variable:

PORT=8080 TEMPLATEFOX_API_KEY=sk_your_key node dist/index.js

Source: src/index.ts:34

Express.js Server Setup

The HTTP transport relies on Express.js for request handling:

const express = (await import("express")).default;
const cors = (await import("cors")).default;

const app = express();
app.use(cors());
app.use(express.json());

Source: src/index.ts:36-40

Endpoints

EndpointMethodPurpose
/healthGETHealth check for monitoring
/mcpPOSTMCP request handling

Source: src/index.ts:42-44 and src/index.ts:68-88

Health Check Endpoint

app.get("/health", (_req, res) => {
  res.json({ status: "ok", version: SERVER_VERSION });
});

Source: src/index.ts:42-44

MCP Request Handling

The /mcp POST endpoint extracts the API key from request headers, creates a new server instance, and routes the request through the streamable HTTP transport:

app.post("/mcp", async (req, res) => {
  const authHeader = req.headers.authorization;
  const apiKey = authHeader?.startsWith("Bearer ")
    ? authHeader.slice(7)
    : (req.headers["x-api-key"] as string | undefined);

Source: src/index.ts:70-75

API Key Extraction in HTTP Mode

HTTP transport supports two header formats for API key authentication:

Header FormatExample
Authorization: Bearer <key>Authorization: Bearer sk_your_api_key_here
x-api-key: <key>x-api-key: sk_your_api_key_here

Source: src/index.ts:70-75

Per-Request API Key Handling

HTTP mode uses AsyncLocalStorage to maintain per-request API key context:

import { AsyncLocalStorage } from "node:async_hooks";

const apiKeyStore = new AsyncLocalStorage<string>();

export function runWithApiKey<T>(apiKey: string, fn: () => T): T {
  return apiKeyStore.run(apiKey, fn);
}

Source: src/api-client.ts:11-17

This allows different API keys to be used for different requests on the same server instance. The key is stored in an async local context and retrieved by getApiKey() when making API calls.

Session Management

The HTTP transport is configured with stateless request handling:

const transport = new StreamableHTTPServerTransport({
  sessionIdGenerator: undefined,
});

Source: src/index.ts:80-82

Setting sessionIdGenerator to undefined disables session tracking, making each request independent.

Error Handling

HTTP mode includes comprehensive error responses:

// 401 Unauthorized - Missing API key
res.status(401).json({
  jsonrpc: "2.0",
  error: {
    code: -32001,
    message: "API key required. Pass it via Authorization: Bearer <key> or x-api-key header.",
  },
  id: null,
});

// 405 Method Not Allowed
res.status(405).json({
  jsonrpc: "2.0",
  error: { code: -32000, message: "Method not allowed. Use POST for MCP requests." },
  id: null,
});

// 500 Internal Server Error
res.status(500).json({
  jsonrpc: "2.0",
  error: { code: -32603, message: "Internal server error" },
  id: null,
});

Source: src/index.ts:77-88 and src/index.ts:95-99

Method Restriction

The server explicitly blocks inappropriate HTTP methods on the MCP endpoint:

app.get("/mcp", (_req, res) => {
  res.status(405).json({...});
});

app.delete("/mcp", (_req, res) => {
  res.status(405).json({...});
});

Source: src/index.ts:90-99

Deployment Options

Docker Deployment

For containerized HTTP deployments:

docker build -t templatefox-mcp .
docker run -p 8080:8080 templatefox-mcp

Source: README.md

Cloud Run Deployment

The server is pre-deployed and accessible at:

https://mcp-server-599407781746.us-central1.run.app/mcp

Source: README.md

Claude Desktop Configuration

{
  "mcpServers": {
    "templatefox": {
      "command": "npx",
      "args": ["-y", "@templatefox/mcp-server"],
      "env": {
        "TEMPLATEFOX_API_KEY": "sk_your_api_key_here"
      }
    }
  }
}

Source: README.md

Claude Code Configuration

claude mcp add templatefox -- npx -y @templatefox/mcp-server

Source: README.md

Environment Variables

VariableRequiredDefaultDescription
TEMPLATEFOX_API_KEYYes-API key (starts with sk_)
TEMPLATEFOX_BASE_URLNohttps://api.templatefox.comOverride API base URL
PORTNo-Enables HTTP mode when set

Source: src/index.ts:34 and README.md

Dependencies

The transport implementation relies on these packages:

PackageVersionPurpose
@modelcontextprotocol/sdk^1.29.0MCP protocol and transport classes
express^5.2.1HTTP server framework
cors^2.8.6Cross-origin resource sharing

Source: package.json

Comparison: Stdio vs HTTP

AspectStdioStreamable HTTP
StartupImmediateRequires PORT variable
ConnectionProcess-basedTCP/HTTP
API Key SourceEnvironment variablePer-request header
ScalabilitySingle clientMultiple clients
Use CaseDesktop integrationsCloud deployments
Session SupportNative (process)Stateless (no sessions)
AsyncLocalStorageNot usedUsed for per-request context

Request Flow Comparison

graph LR
    subgraph "Stdio Mode"
        A1[Stdin Request] --> B1[StdioServerTransport]
        B1 --> C1[McpServer]
        C1 --> D1[Stdout Response]
    end
    
    subgraph "HTTP Mode"
        A2[HTTP POST] --> B2[Express App]
        B2 --> C2[StreamableHTTPServerTransport]
        C2 --> D2[McpServer]
        D2 --> E2[HTTP Response]
    end

Tool Registration

Regardless of transport mode, all tools are registered identically:

export function registerTools(server: McpServer): void {
  // Tools are registered once at server creation
  server.tool("generate_pdf", {...});
  server.tool("generate_pdf_async", {...});
  server.tool("get_pdf_job_status", {...});
  server.tool("list_pdf_jobs", {...});
  server.tool("list_templates", {...});
  server.tool("get_template_fields", {...});
  server.tool("get_account_info", {...});
  server.tool("list_transactions", {...});
}

Source: src/tools.ts:3-20

Source: https://github.com/TemplateFoxPDF/mcp-server / Human Manual

Server Initialization

Related topics: Transport Modes, PDF Generation Tools

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Stdio Transport Mode

Continue reading this section for the full explanation and source context.

Section HTTP Transport Mode

Continue reading this section for the full explanation and source context.

Section Server Instance Creation

Continue reading this section for the full explanation and source context.

Related topics: Transport Modes, PDF Generation Tools

Server Initialization

Overview

The TemplateFox MCP Server is a Model Context Protocol (MCP) server that bridges AI assistants with the TemplateFox PDF generation API. The server initialization process configures the MCP server, registers available tools, and sets up either stdio-based local communication or HTTP-based remote access.

Source: src/index.ts:1-5

#!/usr/bin/env node
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import { registerTools } from "./tools.js";
import { runWithApiKey } from "./api-client.js";

Transport Modes

The server supports two distinct transport mechanisms determined by environment configuration.

ModeTriggerUse Case
StdioNo PORT env varLocal CLI usage via npx, Claude Desktop
HTTPPORT env var setRemote/cloud deployment, self-hosted

Source: src/index.ts:25-26

const port = process.env.PORT ? parseInt(process.env.PORT, 10) : undefined;

Stdio Transport Mode

When running without a PORT environment variable, the server uses stdio (standard input/output) transport, which is the default mode for local AI assistant integration.

Source: src/index.ts:54-56

// stdio mode: default for npx / local usage
const server = createServer();
const transport = new StdioServerTransport();
await server.connect(transport);

HTTP Transport Mode

When PORT is defined, the server launches an Express.js application with CORS support and Streamable HTTP transport for remote deployments.

Source: src/index.ts:28-31

// HTTP mode: Streamable HTTP transport (stateless, for Cloud Run / remote)
const express = (await import("express")).default;
const cors = (await import("cors")).default;

const app = express();
app.use(cors());
app.use(express.json());

Server Creation Flow

The createServer() function initializes the MCP server with version metadata and registers all available tools.

graph TD
    A[Start] --> B[Check PORT Environment Variable]
    B -->|PORT defined| C[HTTP Mode Setup]
    B -->|No PORT| D[Stdio Mode Setup]
    C --> E[Create Express App]
    E --> F[Configure CORS & JSON middleware]
    F --> G[Setup Health Endpoint /mcp]
    G --> H[Start Listening]
    D --> I[createServer]
    I --> J[Register Tools via registerTools]
    J --> K[new McpServer]
    K --> L[new StdioServerTransport]
    L --> M[Connect and Await Requests]

Server Instance Creation

Source: src/index.ts:10-18

function createServer(): McpServer {
  const server = new McpServer({
    name: SERVER_NAME,
    version: SERVER_VERSION,
  });
  registerTools(server);
  return server;
}

The server configuration constants are defined as:

ConstantValuePurpose
SERVER_NAME"templatefox"Server identifier for MCP protocol
SERVER_VERSION"1.8.2"Semantic version of the server

Source: src/index.ts:6-8

HTTP Server Endpoints

The HTTP transport mode exposes two endpoints:

Health Check Endpoint

Source: src/index.ts:33-36

app.get("/health", (_req, res) => {
  res.json({ status: "ok", version: SERVER_VERSION });
});

MCP Request Endpoint

Source: src/index.ts:38-68

app.post("/mcp", async (req, res) => {
  // Extract API key from Authorization header or x-api-key
  const authHeader = req.headers.authorization;
  const apiKey = authHeader?.startsWith("Bearer ")
    ? authHeader.slice(7)
    : (req.headers["x-api-key"] as string | undefined);

  if (!apiKey) {
    res.status(401).json({
      jsonrpc: "2.0",
      error: {
        code: -32001,
        message: "API key required. Pass it via Authorization: Bearer <key> or x-api-key header.",
      },
      id: null,
    });
    return;
  }
  // ... server initialization continues
});

Error Handling Endpoints

The server returns 405 Method Not Allowed for incorrect HTTP methods:

app.get("/mcp", (_req, res) => {
  res.status(405).json({
    jsonrpc: "2.0",
    error: { code: -32000, message: "Method not allowed. Use POST for MCP requests." },
    id: null,
  });
});

app.delete("/mcp", (_req, res) => {
  res.status(405).json({
    jsonrpc: "2.0",
    error: { code: -32000, message: "Method not allowed. Sessions are not supported." },
    id: null,
  });
});

Source: src/index.ts:70-82

API Key Handling

The server implements a multi-tier API key resolution strategy:

graph LR
    A[API Key Request] --> B{HTTP Transport?}
    B -->|Yes| C[Extract from Header]
    B -->|No| D{Check Environment}
    C --> E[AsyncLocalStorage Context]
    D -->|Found| F[Use TEMPLATEFOX_API_KEY]
    D -->|Not Found| G[Throw Error]
    E --> H[API Request with Key]
    F --> H

Key Resolution Priority

Source: src/api-client.ts:28-43

function getApiKey(): string {
  // 1. Per-request key from HTTP transport (AsyncLocalStorage)
  const contextKey = apiKeyStore.getStore();
  if (contextKey) return contextKey;

  // 2. Environment variable (stdio mode)
  const key = process.env.TEMPLATEFOX_API_KEY;
  if (!key) {
    throw new Error(
      "TEMPLATEFOX_API_KEY is required. " +
      "Set it as an environment variable or pass it via the Authorization header. " +
      "Get your API key at https://app.templatefox.com/dashboard/api-keys"
    );
  }
  return key;
}

HTTP Transport Key Injection

For HTTP mode, the API key is extracted from request headers and stored in AsyncLocalStorage context:

Source: src/index.ts:40-43

const authHeader = req.headers.authorization;
const apiKey = authHeader?.startsWith("Bearer ")
  ? authHeader.slice(7)
  : (req.headers["x-api-key"] as string | undefined);

The key is then passed to the request handler:

Source: src/index.ts:53-58

const server = createServer();
const transport = new StreamableHTTPServerTransport({
  sessionIdGenerator: undefined,
});
await server.connect(transport);
await runWithApiKey(apiKey, () => transport.handleRequest(req, res, req.body));

AsyncLocalStorage Context

Source: src/api-client.ts:20-26

import { AsyncLocalStorage } from "node:async_hooks";

const apiKeyStore = new AsyncLocalStorage<string>();

/**
 * Run a function with a specific API key in context.
 * Used by HTTP transport to pass per-request API keys.
 */
export function runWithApiKey<T>(apiKey: string, fn: () => T): T {
  return apiKeyStore.run(apiKey, fn);
}

Tool Registration

All MCP tools are registered during server initialization via the registerTools() function.

Source: src/tools.ts:4-7

export function registerTools(server: McpServer): void {
  // Tool registrations...
}

Available Tools

ToolDescriptionCreditsRead-Only
generate_pdfGenerate PDF from template1No
generate_pdf_asyncQueue async PDF generation1No
get_pdf_job_statusCheck async job status-Yes
list_pdf_jobsList async jobs-Yes
list_templatesList available templates-Yes
get_template_fieldsGet template field definitions-Yes
get_account_infoGet account and credit info-Yes
list_transactionsView credit transaction history-Yes

Source: src/tools.ts

Configuration Options

Environment Variables

VariableRequiredDefaultDescription
TEMPLATEFOX_API_KEYYes (Stdio) / Via Header (HTTP)-API key starting with sk_
TEMPLATEFOX_BASE_URLNohttps://api.templatefox.comOverride API base URL
PORTNo-Enable HTTP mode on specified port

Source: src/api-client.ts:15

Build and Runtime Scripts

Source: package.json

ScriptCommandPurpose
buildtscCompile TypeScript to JavaScript
startnode dist/index.jsRun the compiled server

Server Binaries

{
  "bin": {
    "templatefox-mcp-server": "./dist/index.js"
  }
}

Startup Sequence

sequenceDiagram
    participant CLI as CLI/npm
    participant Server as MCP Server
    participant MCP as MCP SDK
    participant Express as Express App

    CLI->>Server: node dist/index.js
    Server->>Server: Check PORT env var
    alt Stdio Mode
        Server->>MCP: createServer()
        MCP->>Server: McpServer instance
        Server->>MCP: registerTools()
        Server->>MCP: new StdioServerTransport()
        Server->>MCP: connect(transport)
        Note over Server,MCP: Await stdio requests
    else HTTP Mode
        Server->>Express: new Express()
        Express->>Server: app configured
        Server->>Server: app.listen(port)
        Note over Server,Express: /health, /mcp endpoints ready
    end

Error Handling

HTTP Mode Error Handler

Source: src/index.ts:59-67

} catch (error) {
  if (!res.headersSent) {
    res.status(500).json({
      jsonrpc: "2.0",
      error: { code: -32603, message: "Internal server error" },
      id: null,
    });
  }
}

Session Cleanup

Source: src/index.ts:55-57

res.on("close", () => {
  transport.close();
  server.close();
});

Version Information

The server reports its version through:

  1. HTTP Health Endpoint: Returns { status: "ok", version: SERVER_VERSION }
  2. Package Version: 1.10.1 in package.json
  3. Runtime Version: 1.8.2 defined as SERVER_VERSION constant

Source: package.json:4 Source: src/index.ts:8

Dependencies

The server initialization relies on these core dependencies:

PackageVersionPurpose
@modelcontextprotocol/sdk^1.29.0MCP protocol implementation
express^5.2.1HTTP server framework
cors^2.8.6Cross-origin resource sharing
typescript^5.8.0TypeScript compilation
@types/node^22.0.0Node.js type definitions

Source: package.json:24-35

Source: https://github.com/TemplateFoxPDF/mcp-server / Human Manual

PDF Generation Tools

Related topics: Template Management Tools, Account Management Tools, API Client

Section Related Pages

Continue reading this section for the full explanation and source context.

Section generatepdf

Continue reading this section for the full explanation and source context.

Section generatepdfasync

Continue reading this section for the full explanation and source context.

Section getpdfjobstatus

Continue reading this section for the full explanation and source context.

Related topics: Template Management Tools, Account Management Tools, API Client

PDF Generation Tools

The PDF Generation Tools module provides a comprehensive set of MCP (Model Context Protocol) tools that enable AI assistants to interact with the TemplateFox PDF generation API. This module serves as the bridge between AI assistants (such as Claude, Cursor, and Windsurf) and the TemplateFox service, allowing users to generate professional PDF documents from templates with dynamic data.

Architecture Overview

The PDF Generation Tools are built on the Model Context Protocol SDK, which provides a standardized interface for exposing server-side capabilities to AI assistants. The architecture consists of three primary layers:

graph TD
    A["AI Assistant<br/>(Claude, Cursor, Windsurf)"] --> B["MCP SDK<br/>StdioServerTransport / StreamableHTTPServerTransport"]
    B --> C["MCP Server (index.ts)"]
    C --> D["Tool Registry (tools.ts)"]
    D --> E["API Client (api-client.ts)"]
    E --> F["TemplateFox API<br/>https://api.templatefox.com"]
    
    style A fill:#e1f5fe
    style F fill:#fff3e0
    style D fill:#f3e5f5

The server supports two transport modes:

  • Stdio Transport: Default mode for local/cli usage via npx
  • Streamable HTTP Transport: For cloud deployments and remote access

Source: src/index.ts:1-95, src/api-client.ts:1-15

Tool Registration

All tools are registered using the registerTools() function from src/tools.ts. This function accepts an McpServer instance and defines each tool with its name, description, input schema, and handler function.

graph LR
    A["registerTools(server)"] --> B["generate_pdf"]
    A --> C["generate_pdf_async"]
    A --> D["get_pdf_job_status"]
    A --> C --> D
    A --> E["list_pdf_jobs"]
    A --> F["list_templates"]
    A --> G["get_template_fields"]
    A --> H["get_account_info"]
    A --> I["list_transactions"]

Source: src/tools.ts:1-10

Core PDF Generation Tools

generate_pdf

The generate_pdf tool is the primary synchronous PDF generation tool. It creates a PDF document from a specified template with dynamic data and returns either a URL to download the PDF or the raw binary content.

Tool Name: generate_pdf API Endpoint: POST /v1/pdf/create Cost: 1 credit per generation Source: src/tools.ts:20-60

#### Input Parameters

ParameterTypeRequiredDescription
template_idstringYesTemplate short ID (12 characters)
dataRecord<string, unknown>YesKey-value data to render in the template. Keys must match template variables.
export_typeenumNoExport format: url (upload to CDN, return URL) or binary (return raw PDF bytes)
expirationnumberNoURL expiration in seconds (60-604800, i.e., 1 min to 7 days). Only applies to url export type.
filenamestringNoCustom filename for the PDF (without .pdf extension). Defaults to 'document'.
store_s3booleanNoUpload to configured S3 bucket instead of CDN
s3_filepathstringNoCustom path prefix in S3 bucket
s3_bucketstringNoOverride the default S3 bucket configured in S3 integration
pdf_variantenumNoStandards-compliant PDF variant: pdf/a-1b, pdf/a-2b, or pdf/a-3b
versionstringNoOptional version tag (e.g., prod) or version number (e.g., 3). Uses current draft if omitted.

#### PDF/A Variants

The tool supports generating PDF/A variants for archival and compliance purposes:

VariantUse Case
pdf/a-1bBasic archival compliance
pdf/a-2bMost common for archival compliance
pdf/a-3bRequired for documents with file attachments (e.g., Factur-X, ZUGFeRD invoices)

#### Hints

HintValueDescription
destructiveHintfalseIndicates this tool does not delete data

Source: src/tools.ts:20-60

generate_pdf_async

The generate_pdf_async tool queues an asynchronous PDF generation job for long-running or batch operations. It returns a job ID for status polling and supports webhook notifications.

Tool Name: generate_pdf_async API Endpoint: POST /v1/pdf/create-async Cost: 1 credit per generation Source: src/tools.ts:65-120

#### Input Parameters

ParameterTypeRequiredDescription
template_idstringYesTemplate short ID (12 characters)
dataRecord<string, unknown>YesKey-value data to render in the template
export_typeenumNoExport format. Currently only url is supported for async.
expirationnumberNoURL expiration in seconds (60-604800). Default: 86400 (24 hours)
filenamestringNoCustom filename for the PDF
store_s3booleanNoUpload to configured S3 bucket
s3_filepathstringNoCustom path prefix in S3 bucket
s3_bucketstringNoOverride the default S3 bucket
webhook_urlstringNoHTTPS URL to receive POST notification when job completes or fails
webhook_secretstringNoSecret for HMAC-SHA256 signing of webhook payloads (minimum 16 characters)
pdf_variantenumNoPDF/A variant for compliance
versionstringNoVersion tag or number

#### Async Workflow

graph TD
    A["Call generate_pdf_async"] --> B["Receive job_id (UUID)"]
    B --> C["Poll with get_pdf_job_status"]
    C --> D{"Status = completed?"}
    D -->|Yes| E["Receive PDF URL"]
    D -->|No| F["Continue polling"]
    F --> C
    D -->|Failed| G["Handle error"]
    B --> H["Optional: Configure webhook"]
    H --> I["Receive POST to webhook_url"]
    I --> E

Source: src/tools.ts:65-120

Job Management Tools

get_pdf_job_status

The get_pdf_job_status tool retrieves the current status of an asynchronous PDF generation job.

Tool Name: get_pdf_job_status API Endpoint: GET /v1/pdf/jobs/{job_id} Source: src/tools.ts:125-145

#### Input Parameters

ParameterTypeRequiredDescription
job_idstringYesAsync job ID (UUID returned by the create-async endpoint)

#### Job Status Values

StatusDescription
pendingJob is queued but not yet processing
processingPDF generation is in progress
completedPDF generation finished successfully; PDF URL available
failedPDF generation failed; check error details

#### Hints

HintValueDescription
readOnlyHinttrueThis tool only reads data, no modifications

Source: src/tools.ts:125-145

list_pdf_jobs

The list_pdf_jobs tool retrieves a list of asynchronous PDF generation jobs with pagination and status filtering.

Tool Name: list_pdf_jobs API Endpoint: GET /v1/pdf/jobs Source: src/tools.ts:150-175

#### Input Parameters

ParameterTypeRequiredDescription
limitnumberNoMaximum number of results to return
offsetnumberNoNumber of results to skip (for pagination)
statusenumNoFilter jobs by status: pending, processing, completed, or failed

#### Hints

HintValueDescription
readOnlyHinttrueThis tool only reads data

Source: src/tools.ts:150-175

Template Discovery Tools

list_templates

The list_templates tool returns all available PDF templates in the user's account.

Tool Name: list_templates API Endpoint: GET /v1/templates Source: src/tools.ts:180-200

#### Hints

HintValueDescription
readOnlyHinttrueThis tool only reads data

#### Usage Pattern

graph LR
    A["list_templates"] --> B["Get list of templates<br/>with IDs and names"]
    B --> C["Select template_id"]
    C --> D["get_template_fields"]
    D --> E["Discover required fields"]
    E --> F["generate_pdf with complete data"]

Source: src/tools.ts:180-200

get_template_fields

The get_template_fields tool retrieves the dynamic fields defined for a specific template, including field names, types, and whether they are required.

Tool Name: get_template_fields API Endpoint: GET /v1/templates/{template_id}/fields Source: src/tools.ts:205-230

#### Input Parameters

ParameterTypeRequiredDescription
template_idstringYesTemplate short ID (12 characters)

#### Hints

HintValueDescription
readOnlyHinttrueThis tool only reads data

#### Return Value

The tool returns field metadata including:

  • Field names (must match when providing data to generate_pdf)
  • Field types (string, number, boolean, etc.)
  • Required vs optional fields

Source: src/tools.ts:205-230

Account Management Tools

get_account_info

The get_account_info tool retrieves account information including remaining credits and email address.

Tool Name: get_account_info API Endpoint: GET /v1/account Source: src/tools.ts:235-255

#### Hints

HintValueDescription
readOnlyHinttrueThis tool only reads data

Source: src/tools.ts:235-255

list_transactions

The list_transactions tool provides access to credit transaction history, showing PDF generations, purchases, and refunds.

Tool Name: list_transactions API Endpoint: GET /v1/account/transactions Source: src/tools.ts:260-285

#### Input Parameters

ParameterTypeRequiredDescription
limitnumberNoNumber of records to return (1-1000)
offsetnumberNoNumber of records to skip for pagination

#### Hints

HintValueDescription
readOnlyHinttrueThis tool only reads data

Source: src/tools.ts:260-285

API Client Integration

The tools utilize the apiRequest function from src/api-client.ts to communicate with the TemplateFox API. The API client handles:

  • Base URL Configuration: Defaults to https://api.templatefox.com, configurable via TEMPLATEFOX_BASE_URL environment variable
  • API Key Management: Supports two modes:
  1. Per-request key from HTTP transport via AsyncLocalStorage
  2. Environment variable TEMPLATEFOX_API_KEY for stdio mode
  • Request Building: Constructs URLs with query parameters and request bodies
  • Response Handling: Parses JSON or text responses based on Content-Type header
graph TD
    A["Tool Handler"] --> B["apiRequest(method, path, body, query)"]
    B --> C["Construct URL with BASE_URL + path"]
    C --> D["Add query parameters if provided"]
    D --> E["Set headers<br/>x-api-key, Content-Type, Accept"]
    E --> F["Make fetch request"]
    F --> G["Parse response by Content-Type"]
    G --> H["Return ApiResponse<br/>{ok, status, data}"]

API Key Resolution

The getApiKey() function implements a fallback chain for API key resolution:

  1. Per-request key from HTTP transport - Uses AsyncLocalStorage context
  2. Environment variable - Falls back to TEMPLATEFOX_API_KEY
  3. Error - Throws if no key is available
graph TD
    A["getApiKey called"] --> B{"AsyncLocalStorage<br/>has context?"}
    B -->|Yes| C["Return context key"]
    B -->|No| D{"TEMPLATEFOX_API_KEY<br/>env var set?"}
    D -->|Yes| E["Return env var value"]
    D -->|No| F["Throw error:<br/>API key required"]

Source: src/api-client.ts:1-75

Configuration

Environment Variables

VariableRequiredDefaultDescription
TEMPLATEFOX_API_KEYYes (stdio mode)-API key starting with sk_
TEMPLATEFOX_BASE_URLNohttps://api.templatefox.comOverride API base URL
PORTNo-Enable HTTP mode when set

HTTP Transport Configuration

When running in HTTP mode (by setting PORT), the server requires API key authentication via HTTP headers:

HeaderFormatExample
AuthorizationBearer <key>Authorization: Bearer sk_abc123...
x-api-key<key>x-api-key: sk_abc123...

Source: src/index.ts:35-55, README.md:1-80

Complete Tool Summary

ToolNamePurposeRead-Only
generate_pdfSynchronous PDF GenerationCreate PDF from template with dataNo
generate_pdf_asyncAsync PDF GenerationQueue PDF job with webhook supportNo
get_pdf_job_statusJob Status CheckPoll async job status by IDYes
list_pdf_jobsJob ListList jobs with pagination/filteringYes
list_templatesTemplate DiscoveryList available templatesYes
get_template_fieldsField DiscoveryGet template variable definitionsYes
get_account_infoAccount InfoView credits and account detailsYes
list_transactionsTransaction HistoryView credit transaction logYes

Source: src/tools.ts

Version Information

ComponentVersion
Package@templatefox/mcp-server
Server1.8.2
Package.json1.10.1
MCP SDK^1.29.0
Node.js Requirement>=18.0.0

Source: package.json:1-20, src/index.ts:10

Source: https://github.com/TemplateFoxPDF/mcp-server / Human Manual

Template Management Tools

Related topics: PDF Generation Tools, Introduction

Section Related Pages

Continue reading this section for the full explanation and source context.

Section System Components

Continue reading this section for the full explanation and source context.

Section Data Flow

Continue reading this section for the full explanation and source context.

Section API Communication

Continue reading this section for the full explanation and source context.

Related topics: PDF Generation Tools, Introduction

Template Management Tools

Overview

Template Management Tools are MCP (Model Context Protocol) tools that enable AI assistants to interact with the TemplateFox PDF template system. These tools allow users to discover available templates and understand the data fields required for each template before generating PDFs. The tools operate as part of the broader MCP server infrastructure that bridges AI assistants with the TemplateFox API for PDF generation.

The template management functionality consists of two primary tools: list_templates for discovering available templates and get_template_fields for inspecting the required input parameters of a specific template.

Architecture

System Components

The template management system integrates several components within the MCP server architecture:

ComponentFileResponsibility
MCP Serversrc/index.tsInitializes the MCP server and registers tools
Tool Registrationsrc/tools.tsDefines and registers template management tools
API Clientsrc/api-client.tsHandles HTTP communication with TemplateFox API

Data Flow

graph TD
    A[AI Assistant] -->|MCP Protocol| B[MCP Server]
    B -->|registerTools| C[Template Management Tools]
    C -->|apiRequest| D[TemplateFox API]
    D -->|Template List| B
    B -->|Formatted Response| A
    
    E[TemplateFox API] -->|Field Schema| B

API Communication

The API client establishes communication with the TemplateFox API at https://api.templatefox.com. The base URL can be overridden via the TEMPLATEFOX_BASE_URL environment variable for testing or custom deployments. Authentication is handled through the API key stored in TEMPLATEFOX_API_KEY, which the client retrieves from either an AsyncLocalStorage context for HTTP transport or from environment variables for stdio mode.

Source: src/api-client.ts:8-9 Source: src/api-client.ts:19-35

Available Tools

list_templates

The list_templates tool retrieves all available PDF templates from the TemplateFox account. This is typically the first step in the PDF generation workflow, allowing users to discover which templates are available for their use case.

Tool Definition:

server.tool(
  "list_templates",
  "List all available PDF templates. Returns template IDs and names. Use this to discover which templates are available before generating a PDF.",
  {},
  { readOnlyHint: true },
  async () => {
    const url = "/v1/templates";
    const result = await apiRequest("GET", url);
    return {
      content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }],
      isError: !result.ok,
    };
  },
);

Source: src/tools.ts:115-128

Parameters: None required

Return Value: JSON object containing an array of template objects with their IDs and names

Characteristics:

  • Read-only operation (marked with readOnlyHint: true)
  • Calls the /v1/templates endpoint via GET request
  • No pagination parameters supported

get_template_fields

The get_template_fields tool retrieves the schema of dynamic fields for a specific template. This tool is essential for understanding what data must be provided when generating a PDF from a template.

Tool Definition:

server.tool(
  "get_template_fields",
  "Get the dynamic fields for a specific template. Use this to know what data to provide when generating a PDF. Returns field names, types, and whether they are required.",
  {
    template_id: z.string().describe("Template short ID (12 characters)"),
  },
  { readOnlyHint: true },
  async ({ template_id }) => {
    const url = `/v1/templates/${template_id}/fields`;
    const result = await apiRequest("GET", url);
    return {
      content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }],
      isError: !result.ok,
    };
  },
);

Source: src/tools.ts:130-145

Parameters:

ParameterTypeRequiredDescription
template_idstringYesTemplate short ID (12 characters)

Return Value: JSON object containing field names, types, and required status for each dynamic field in the template

Characteristics:

  • Read-only operation (marked with readOnlyHint: true)
  • Calls the /v1/templates/{template_id}/fields endpoint via GET request
  • Template ID must be a valid 12-character string

Integration with PDF Generation

Template management tools are integral to the PDF generation workflow. The typical workflow follows a discovery-then-generation pattern:

graph LR
    A[list_templates] -->|Discover template ID| B[get_template_fields]
    B -->|Understand required fields| C[generate_pdf]
    B -->|Job ID returned| D[generate_pdf_async]
    D -->|Poll status| E[get_pdf_job_status]

Workflow Example

  1. List Available Templates: Use list_templates to retrieve all templates and identify the desired template by name or ID
  2. Inspect Template Schema: Use get_template_fields with the template ID to understand required data fields, their types, and which are mandatory
  3. Generate PDF: Pass the template ID and properly structured data object to generate_pdf for synchronous generation or generate_pdf_async for background processing

Source: README.md:58-70

Configuration Requirements

Environment Variables

VariableRequiredDefaultDescription
TEMPLATEFOX_API_KEYYesAPI key starting with sk_
TEMPLATEFOX_BASE_URLNohttps://api.templatefox.comOverride API base URL

Source: README.md:38-47

Transport Modes

The MCP server supports two transport modes, both of which work with template management tools:

ModeCommandUse Case
Stdionpx -y @templatefox/mcp-serverLocal desktop integration (Claude Desktop, Cursor, Windsurf)
HTTPPORT=8080 + server binaryRemote/cloud deployments

For HTTP transport, API key authentication is handled via HTTP headers:

Authorization: Bearer sk_your_api_key_here

or:

x-api-key: sk_your_api_key_here

Source: README.md:45-56 Source: src/index.ts:32-50

Tool Registration Mechanism

The registerTools function in src/tools.ts handles the registration of all MCP tools including template management tools. This function is called during server initialization in src/index.ts:

function createServer(): McpServer {
  const server = new McpServer({
    name: SERVER_NAME,
    version: SERVER_VERSION,
  });
  registerTools(server);
  return server;
}

Source: src/index.ts:16-23

Each tool is registered using the @modelcontextprotocol/sdk library's server.tool() method with the following signature:

server.tool(
  name: string,           // Tool identifier
  description: string,    // Human-readable description for AI
  inputSchema: object,    // Zod schema for validation
  annotations: object,    // Tool hints (readOnlyHint, destructiveHint)
  handler: function       // Async function executing the tool
)

Source: src/tools.ts:4-11

Error Handling

Template management tools return errors when API requests fail. The isError flag is set based on the response.ok property from the API client:

return {
  content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }],
  isError: !result.ok,
};

Source: src/tools.ts:123-128

Common error scenarios include:

ErrorCauseResolution
401 UnauthorizedMissing or invalid API keyEnsure TEMPLATEFOX_API_KEY is set correctly
404 Not FoundInvalid template IDVerify the template ID is 12 characters and exists
500 Internal Server ErrorTemplateFox API issueCheck TemplateFox status page

Package Information

PropertyValue
Package Name@templatefox/mcp-server
Version1.10.1
LicenseMIT
Node Engine>=18.0.0
SDK@modelcontextprotocol/sdk ^1.29.0

Source: package.json:2-10

Source: https://github.com/TemplateFoxPDF/mcp-server / Human Manual

Account Management Tools

Related topics: PDF Generation Tools

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Parameters

Continue reading this section for the full explanation and source context.

Section Implementation

Continue reading this section for the full explanation and source context.

Section Response Format

Continue reading this section for the full explanation and source context.

Related topics: PDF Generation Tools

Account Management Tools

The TemplateFox MCP Server provides two Account Management Tools that enable AI assistants and applications to monitor account resources and track usage history. These tools are essential for managing credits, auditing PDF generation activity, and maintaining visibility into account expenditures.

Overview

Account Management Tools provide read-only access to account metadata and transaction history. They allow users to:

  • Check remaining credits and account details
  • Review credit transaction history with pagination support
  • Monitor PDF generation usage patterns

All Account Management Tools are marked with readOnlyHint: true, indicating they do not modify any data on the server. These tools communicate with the TemplateFox API's /v1/account endpoints.

graph TD
    A[MCP Client] -->|get_account_info| B[Account Info Tool]
    A -->|list_transactions| C[Transaction History Tool]
    B -->|GET /v1/account| D[TemplateFox API]
    C -->|GET /v1/account/transactions| D
    D -->|JSON Response| A

Available Tools

Tool NameDescriptionEndpoint
get_account_infoRetrieve account details and remaining creditsGET /v1/account
list_transactionsFetch paginated credit transaction historyGET /v1/account/transactions

get_account_info

Retrieves comprehensive account information including remaining credits, email address, and account status. This tool is useful for checking resource availability before initiating PDF generation operations.

Parameters

ParameterTypeRequiredDescription
(none)--This tool accepts no input parameters

Implementation

// getAccount -> get_account_info
server.tool(
  "get_account_info",
  "Get account information including remaining credits and email address.",
  {
  },
  { readOnlyHint: true },
  async () => {
    const url = "/v1/account";
    const result = await apiRequest("GET", url);
    return {
      content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }],
      isError: !result.ok,
    };
  },
);

*Source: src/tools.ts:104-119*

Response Format

The tool returns a JSON object containing account metadata. The typical response structure includes:

  • credits: Remaining credit balance for PDF generation
  • email: Account email address
  • account status: Active/suspended state

Use Cases

  • Verify sufficient credits before batch PDF generation
  • Display account dashboard information to users
  • Check if account is active before processing requests

list_transactions

Retrieves a paginated list of credit transactions showing PDF generations, purchases, and refunds. This tool supports filtering and pagination for efficient data retrieval in high-volume scenarios.

Parameters

ParameterTypeRequiredDefaultDescription
limitnumber (integer)No-Number of records to return (1-1000)
offsetnumber (integer)No0Number of records to skip for pagination
statusenumNo-Filter by transaction status

Implementation

// listTransactions -> list_transactions
server.tool(
  "list_transactions",
  "List credit transaction history showing PDF generations, purchases, and refunds. Supports pagination.",
  {
    limit: z.number().int().min(1).max(1000).optional().describe("Number of records to return"),
    offset: z.number().int().min(0).optional().describe("Number of records to skip"),
  },
  { readOnlyHint: true },
  async ({ limit, offset }) => {
    const url = "/v1/account/transactions";
    const result = await apiRequest("GET", url, undefined, { limit, offset });
    return {
      content: [{ type: "text", JSON.stringify(result.data, null, 2) }],
      isError: !result.ok,
    };
  },
);

*Source: src/tools.ts:144-162*

Pagination Behavior

The pagination implementation in api-client.ts processes query parameters and appends them to the request URL:

if (query) {
  for (const [key, value] of Object.entries(query)) {
    if (value !== undefined && value !== null) {
      url.searchParams.set(key, String(value));
    }
  }
}

*Source: src/api-client.ts:42-47*

Response Format

The transactions endpoint returns an array of transaction objects with:

  • type: Transaction type (generation, purchase, refund)
  • amount: Credit amount (positive for additions, negative for usage)
  • timestamp: When the transaction occurred
  • description: Human-readable transaction description

Use Cases

  • Audit trail for compliance and reporting
  • Track monthly PDF generation costs
  • Identify refund transactions
  • Monitor credit usage patterns

API Key Handling

Account Management Tools require a valid API key for authentication. The MCP server supports two authentication modes:

graph LR
    A[Request] --> B{Transport Mode}
    B -->|stdio| C[Environment Variable<br/>TEMPLATEFOX_API_KEY]
    B -->|HTTP| D[Authorization Header<br/>or x-api-key]

Stdio Mode (Environment Variable)

const key = process.env.TEMPLATEFOX_API_KEY;
if (!key) {
  throw new Error(
    "TEMPLATEFOX_API_KEY is required. " +
    "Set it as an environment variable or pass it via the Authorization header."
  );
}

*Source: src/api-client.ts:20-28*

HTTP Mode (Request Headers)

For HTTP transport, the API key is extracted from request headers:

const authHeader = req.headers.authorization;
const apiKey = authHeader?.startsWith("Bearer ")
  ? authHeader.slice(7)
  : (req.headers["x-api-key"] as string | undefined);

*Source: src/index.ts:52-56*

Configuration

Environment VariableRequiredDefaultDescription
TEMPLATEFOX_API_KEYYes-API key starting with sk_
TEMPLATEFOX_BASE_URLNohttps://api.templatefox.comOverride API base URL

*Source: README.md*

Error Handling

Both Account Management Tools include standardized error handling:

return {
  content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }],
  isError: !result.ok,
};

The isError flag is set based on the API response status, allowing MCP clients to handle errors appropriately. Common error scenarios include:

  • 401 Unauthorized: Invalid or missing API key
  • 403 Forbidden: API key lacks necessary permissions
  • 429 Too Many Requests: Rate limit exceeded
  • 500 Internal Server Error: TemplateFox API issues

Example Usage

Checking Account Credits

Tool: get_account_info

Response:

{
  "credits": 150,
  "email": "[email protected]",
  "status": "active"
}

Retrieving Transaction History

Tool: list_transactions
Parameters: {
  "limit": 10,
  "offset": 0
}

Response:

{
  "transactions": [
    { "type": "generation", "amount": -1, "description": "Invoice Template", "timestamp": "2024-01-15T10:30:00Z" },
    { "type": "purchase", "amount": 100, "description": "Credit pack purchase", "timestamp": "2024-01-10T08:00:00Z" }
  ],
  "total": 2
}
ToolCategoryPurpose
generate_pdfPDF GenerationCreate PDFs (consumes credits)
generate_pdf_asyncPDF GenerationAsync PDF creation with webhooks
list_templatesTemplate DiscoveryBrowse available templates
get_template_fieldsTemplate DiscoveryGet template field definitions

Source: https://github.com/TemplateFoxPDF/mcp-server / Human Manual

API Client

Related topics: PDF Generation Tools

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Request Flow

Continue reading this section for the full explanation and source context.

Section Dual Transport Support

Continue reading this section for the full explanation and source context.

Section ApiResponse Interface

Continue reading this section for the full explanation and source context.

Related topics: PDF Generation Tools

API Client

The API Client is the core HTTP communication layer in the TemplateFox MCP Server. It handles all outbound requests to the TemplateFox PDF generation API, manages authentication credentials, and provides a unified interface for tool implementations.

Overview

The MCP server acts as a bridge between AI assistants (Claude, Cursor, Windsurf) and the TemplateFox PDF generation API. The API Client module is responsible for:

  • Establishing authenticated connections to the TemplateFox API
  • Managing API credentials from multiple sources (environment variables, per-request headers)
  • Serializing and sending HTTP requests with proper content types
  • Handling JSON responses and error states
  • Supporting both synchronous (stdio) and asynchronous (HTTP) transport modes

Base URL Configuration:

const BASE_URL = process.env.TEMPLATEFOX_BASE_URL || "https://api.templatefox.com";

Source: src/api-client.ts:11

Architecture

Request Flow

graph TD
    A[Tool Call] --> B[registerTools in tools.ts]
    B --> C[apiRequest function]
    C --> D{Transport Mode?}
    D -->|Stdio| E[getApiKey from env]
    D -->|HTTP| F[runWithApiKey with AsyncLocalStorage]
    E --> G[Fetch API call]
    F --> G
    G --> H[Parse Response]
    H --> I[Return ApiResponse]

Dual Transport Support

The API Client supports two distinct transport modes:

Transport ModeTriggerAPI Key SourceUse Case
StdioNo PORT env varprocess.env.TEMPLATEFOX_API_KEYLocal Claude Desktop, npx usage
HTTPPORT env var setPer-request Authorization headerCloud Run, self-hosted, remote clients

Source: src/index.ts:22-23

Core Components

ApiResponse Interface

interface ApiResponse {
  ok: boolean;
  status: number;
  data: unknown;
}
PropertyTypeDescription
okbooleanIndicates if the HTTP response status was in the 2xx range
statusnumberHTTP status code from the API
dataunknownParsed response body (JSON object or raw string)

Source: src/api-client.ts:58-62

The `apiRequest` Function

The central function for making API calls:

export async function apiRequest(
  method: string,
  path: string,
  body?: Record<string, unknown>,
  query?: Record<string, string | number | undefined>,
): Promise<ApiResponse>

Parameters:

ParameterTypeRequiredDescription
methodstringYesHTTP method (GET, POST, etc.)
pathstringYesAPI endpoint path (e.g., /v1/pdf/create)
bodyRecord<string, unknown>NoJSON request body for POST requests
query`Record<string, string \number \undefined>`NoQuery string parameters

Request Processing:

  1. Constructs full URL by combining BASE_URL with the provided path
  2. Appends query parameters to URL
  3. Sets required headers including API key and Content-Type
  4. Executes fetch request
  5. Parses response based on Content-Type header

Source: src/api-client.ts:64-101

API Key Management

#### AsyncLocalStorage for Per-Request Keys

import { AsyncLocalStorage } from "node:async_hooks";

const apiKeyStore = new AsyncLocalStorage<string>();

The module uses Node.js AsyncLocalStorage to maintain per-request API key context in HTTP transport mode. This enables:

  • Stateless request handling (no session management required)
  • Isolation of API keys between concurrent requests
  • Clean middleware-style API key injection

Source: src/api-client.ts:4,7

#### The runWithApiKey Function

export function runWithApiKey<T>(apiKey: string, fn: () => T): T {
  return apiKeyStore.run(apiKey, fn);
}

Wraps a function execution within a specific API key context. Used by the HTTP transport layer to inject the per-request API key.

Source: src/api-client.ts:17-20

#### The getApiKey Function

function getApiKey(): string {
  // 1. Per-request key from HTTP transport (AsyncLocalStorage)
  const contextKey = apiKeyStore.getStore();
  if (contextKey) return contextKey;

  // 2. Environment variable (stdio mode)
  const key = process.env.TEMPLATEFOX_API_KEY;
  if (!key) {
    throw new Error(
      "TEMPLATEFOX_API_KEY is required. " +
      "Set it as an environment variable or pass it via the Authorization header. " +
      "Get your API key at https://app.templatefox.com/dashboard/api-keys"
    );
  }
  return key;
}

Priority Order:

  1. Per-request key from AsyncLocalStorage (HTTP transport mode)
  2. Environment variable TEMPLATEFOX_API_KEY (stdio transport mode)

If neither is available, throws a descriptive error with setup instructions.

Source: src/api-client.ts:22-40

Usage in Tools

All MCP tools in src/tools.ts consume the API Client through apiRequest:

import { apiRequest } from "./api-client.js";

// Example: List templates
async () => {
  const url = "/v1/templates";
  const result = await apiRequest("GET", url);
  return {
    content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }],
    isError: !result.ok,
  };
}

Tools Using the API Client:

ToolMethodEndpointPurpose
generate_pdfPOST/v1/pdf/createSynchronous PDF generation
generate_pdf_asyncPOST/v1/pdf/create-asyncAsync PDF generation with webhooks
get_pdf_job_statusGET/v1/pdf/jobs/{job_id}Check async job status
list_pdf_jobsGET/v1/pdf/jobsList all async jobs
list_templatesGET/v1/templatesList available templates
get_template_fieldsGET/v1/templates/{template_id}/fieldsGet template schema
get_account_infoGET/v1/accountAccount and credit info
list_transactionsGET/v1/account/transactionsCredit transaction history

Source: src/tools.ts

HTTP Transport Integration

Request Handling in Express

app.post("/mcp", async (req, res) => {
  const authHeader = req.headers.authorization;
  const apiKey = authHeader?.startsWith("Bearer ")
    ? authHeader.slice(7)
    : (req.headers["x-api-key"] as string | undefined);

  if (!apiKey) {
    res.status(401).json({
      jsonrpc: "2.0",
      error: {
        code: -32001,
        message: "API key required. Pass it via Authorization: Bearer <key> or x-api-key header.",
      },
      id: null,
    });
    return;
  }

  try {
    const server = createServer();
    const transport = new StreamableHTTPServerTransport({
      sessionIdGenerator: undefined,
    });
    await server.connect(transport);
    await runWithApiKey(apiKey, () => transport.handleRequest(req, res, req.body));
  } catch (error) {
    // Error handling
  }
});

Source: src/index.ts:47-82

Supported Authentication Headers

HeaderFormatExample
AuthorizationBearer <api_key>Authorization: Bearer sk_live_abc123...
x-api-key<api_key>x-api-key: sk_live_abc123...

Configuration

Environment Variables

VariableRequiredDefaultDescription
TEMPLATEFOX_API_KEYYes (Stdio) / No (HTTP)-API key starting with sk_
TEMPLATEFOX_BASE_URLNohttps://api.templatefox.comOverride API base URL
PORTNo-If set, enables HTTP transport mode

Source: package.json and README.md

Dependencies

The API Client relies on these npm packages:

PackageVersionPurpose
@modelcontextprotocol/sdk^1.29.0MCP server framework
express^5.2.1HTTP server for remote transport
cors^5.2.6CORS middleware for HTTP mode

Source: package.json

Error Handling

The API Client propagates errors through the tool layer. Each tool checks result.ok and sets isError: true when the API returns a non-success status:

const result = await apiRequest("GET", url);
return {
  content: [{ type: "text", text: JSON.stringify(result.data, null, 2) }],
  isError: !result.ok,
};

The response data typically contains error details from the TemplateFox API, including:

  • HTTP status codes
  • JSON-RPC error objects
  • Descriptive error messages

Health Check Endpoint

When running in HTTP mode, a health check endpoint is available:

app.get("/health", (_req, res) => {
  res.json({ status: "ok", version: SERVER_VERSION });
});

This endpoint does not require authentication and is suitable for load balancer health checks.

Source: src/index.ts:35-38

Source: https://github.com/TemplateFoxPDF/mcp-server / Human Manual

Installation and Setup

Related topics: Docker Deployment, Transport Modes

Section Related Pages

Continue reading this section for the full explanation and source context.

Section System Requirements

Continue reading this section for the full explanation and source context.

Section Required Credentials

Continue reading this section for the full explanation and source context.

Section Method 1: Direct npx (Recommended for Claude Desktop)

Continue reading this section for the full explanation and source context.

Related topics: Docker Deployment, Transport Modes

Installation and Setup

Overview

The TemplateFox MCP Server provides an integration layer between AI assistants (Claude, Cursor, Windsurf) and the TemplateFox PDF generation API. This page covers all installation methods, configuration options, and deployment scenarios for setting up the MCP server in various environments.

The server acts as a bridge that translates MCP (Model Context Protocol) tool calls into TemplateFox API requests, enabling AI assistants to generate PDFs from templates on behalf of users.

Source: README.md:1-5

Prerequisites

System Requirements

RequirementSpecification
Node.js Version>= 18.0.0
Package Managernpm, yarn, or pnpm
Network AccessOutbound HTTPS to api.templatefox.com

Source: package.json:17-19

Required Credentials

You must obtain an API key from the TemplateFox dashboard before using the server:

  1. Visit app.templatefox.com/dashboard/api-keys
  2. Generate a new API key (keys start with sk_)
  3. Store the key securely for configuration

Source: README.md:33-35

Installation Methods

No upfront installation required. Claude Desktop automatically downloads and runs the package.

Source: README.md:21-28

Method 2: Global npm Installation

For command-line usage or custom MCP configurations:

npm install -g @templatefox/mcp-server

After global installation, use the CLI directly:

templatefox-mcp-server

Source: README.md:29-31

Method 3: Docker Deployment

Build and run the server in a container:

docker build -t templatefox-mcp .
docker run -p 8080:8080 templatefox-mcp

Source: README.md:66-67

Claude Desktop Configuration

Configuration File Location

Operating SystemConfig File Path
macOS~/Library/Application Support/Claude/claude_desktop_config.json
Windows%APPDATA%\Claude\claude_desktop_config.json
Linux~/.config/Claude/claude_desktop_config.json

Source: README.md:14-16

Configuration Format

Add the following to your Claude Desktop config:

{
  "mcpServers": {
    "templatefox": {
      "command": "npx",
      "args": ["-y", "@templatefox/mcp-server"],
      "env": {
        "TEMPLATEFOX_API_KEY": "sk_your_api_key_here"
      }
    }
  }
}

Source: README.md:17-27

Claude Code Configuration

CLI Installation

Use the Claude Code MCP management command:

claude mcp add templatefox -- npx -y @templatefox/mcp-server

Set the TEMPLATEFOX_API_KEY environment variable in your shell configuration:

export TEMPLATEFOX_API_KEY=sk_your_api_key_here

Source: README.md:37-45

Cursor and Windsurf Configuration

Both Cursor and Windsurf support the same MCP server configuration. Use the npx command with environment variable injection:

{
  "mcpServers": {
    "templatefox": {
      "command": "npx",
      "args": ["-y", "@templatefox/mcp-server"],
      "env": {
        "TEMPLATEFOX_API_KEY": "sk_your_api_key_here"
      }
    }
  }
}

Source: README.md:47-52

Environment Variables

Configuration Reference

VariableRequiredDefaultDescription
TEMPLATEFOX_API_KEYYes-Your API key (starts with sk_)
TEMPLATEFOX_BASE_URLNohttps://api.templatefox.comOverride API base URL
PORTNo-Enable HTTP mode on specified port

Source: README.md:57-63

API Key Resolution Order

The server resolves the API key in the following priority order:

graph TD
    A[API Key Request] --> B{Per-Request Header?}
    B -->|Yes| C[Use Authorization or x-api-key header]
    B -->|No| D{Environment Variable?}
    D -->|Yes| E[Use TEMPLATEFOX_API_KEY]
    D -->|No| F[Throw Error]
    C --> G[Process Request]
    E --> G
    F --> H[Error: API key required]

Source: src/api-client.ts:25-38

HTTP Transport Mode

The MCP server supports HTTP transport via Streamable HTTP, enabling remote and cloud deployments.

Server Architecture

graph LR
    A[MCP Client] -->|HTTPS POST /mcp| B[Express Server]
    A -->|Authorization Header| B
    B --> C[StreamableHTTPServerTransport]
    C --> D[McpServer Instance]
    D --> E[API Request to TemplateFox]
    E --> F[api.templatefox.com]

Running in HTTP Mode

Set the PORT environment variable to enable HTTP transport:

PORT=8080 TEMPLATEFOX_API_KEY=sk_your_key node dist/index.js

Source: README.md:69-70

Remote Server Endpoint

TemplateFox hosts a public MCP server for remote access:

https://mcp-server-599407781746.us-central1.run.app/mcp

Source: README.md:73-77

HTTP Authentication

MCP clients must pass the API key via HTTP header:

Authorization: Bearer sk_your_api_key_here

Or alternatively:

x-api-key: sk_your_api_key_here

Source: README.md:79-86

HTTP Server Endpoints

EndpointMethodDescription
/healthGETHealth check endpoint
/mcpPOSTMCP request endpoint
/mcpGETReturns 405 Method Not Allowed
/mcpDELETEReturns 405 (sessions not supported)

Source: src/index.ts:42-56

Per-Request API Key Handling

In HTTP mode, the server extracts the API key from incoming requests using AsyncLocalStorage to maintain request isolation:

sequenceDiagram
    participant Client
    participant Express
    participant Transport
    participant Server
    participant API

    Client->>Express: POST /mcp with Authorization header
    Express->>Transport: Extract apiKey
    Transport->>Server: Handle request with apiKey context
    Server->>API: Make TemplateFox API call
    API-->>Server: Response
    Server-->>Transport: Tool result
    Transport-->>Express: JSON-RPC response
    Express-->>Client: HTTP Response

Source: src/api-client.ts:8-14

Stdio Transport Mode (Default)

When PORT is not set, the server runs in stdio mode, which is the default for npx and local CLI usage:

graph TD
    A[AI Assistant] -->|stdio| B[StdioServerTransport]
    B --> C[McpServer]
    C --> D[Tool Handler]
    D --> E[TemplateFox API]

Source: src/index.ts:67-71

Build from Source

For development or custom deployments:

# Clone the repository
git clone https://github.com/TemplateFoxPDF/mcp-server.git
cd mcp-server

# Install dependencies
npm install

# Build TypeScript
npm run build

# Run the server
npm start

Build Scripts

ScriptCommandDescription
buildtscCompiles TypeScript to JavaScript
startnode dist/index.jsRuns the compiled server

Source: package.json:8-11

Transport Selection Flow

graph TD
    A[Start] --> B{PORT environment variable set?}
    B -->|Yes| C[HTTP Mode]
    B -->|No| D[Stdio Mode]
    C --> E[Initialize Express + StreamableHTTP]
    D --> F[Initialize StdioServerTransport]
    E --> G[Listen on configured port]
    F --> H[Connect to stdio]

Source: src/index.ts:32-71

Package Metadata

PropertyValue
Package Name@templatefox/mcp-server
Version1.10.1
LicenseMIT
MCP Server Nameio.github.TemplateFoxPDF/mcp-server
Homepagehttps://templatefox.com

Source: package.json:2-9

Dependencies

DependencyVersionPurpose
@modelcontextprotocol/sdk^1.29.0MCP protocol implementation
express^5.2.1HTTP server framework
cors^2.8.6Cross-origin resource sharing

Source: package.json:12-15

Next Steps

After successful installation and setup:

  1. List Templates - Discover available PDF templates using the list_templates tool
  2. Get Template Fields - Understand required data fields using get_template_fields
  3. Generate PDFs - Use generate_pdf to create PDFs with dynamic data
  4. Check Credits - Monitor remaining credits with get_account_info

Source: README.md:91-101

Source: https://github.com/TemplateFoxPDF/mcp-server / Human Manual

Docker Deployment

Related topics: Installation and Setup, Transport Modes

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Prerequisites

Continue reading this section for the full explanation and source context.

Section Build Command

Continue reading this section for the full explanation and source context.

Section Build Script Configuration

Continue reading this section for the full explanation and source context.

Related topics: Installation and Setup, Transport Modes

Docker Deployment

The TemplateFox MCP Server supports containerized deployment via Docker, enabling developers to self-host the server in isolated environments. This deployment mode activates HTTP transport, making the server accessible via REST API endpoints rather than stdio.

Overview

Docker deployment provides a self-contained runtime environment for the MCP server, ideal for production environments, cloud hosting, or scenarios requiring network-accessible MCP services. The containerized approach ensures consistent behavior across different host systems and simplifies dependency management.

Key characteristics:

  • HTTP-based transport mode (Streamable HTTP)
  • Stateless request handling
  • Health check endpoint for monitoring
  • Environment-based configuration
  • API key authentication via HTTP headers

Source: README.md

Architecture

graph TD
    A[Docker Container] --> B[Express HTTP Server]
    B --> C[/health Endpoint]
    B --> D[/mcp Endpoint]
    D --> E[MCP SDK Server]
    E --> F[API Client]
    F --> G[TemplateFox API]
    
    H[External Client] -->|POST /mcp| D
    H -->|GET /health| C
    
    style A fill:#e1f5fe
    style G fill:#fff3e0

The Docker container runs an Express.js HTTP server that handles incoming requests. The MCP SDK integrates with Express to process JSON-RPC requests at the /mcp endpoint, while the /health endpoint provides readiness checks.

Source: src/index.ts:1-95

Building the Docker Image

Prerequisites

Build Command

docker build -t templatefox-mcp .

The build process executes the following steps:

  1. Base image setup (Node.js runtime)
  2. Dependency installation via npm
  3. TypeScript compilation
  4. Production artifact preparation

Source: package.json (build script)

Build Script Configuration

{
  "scripts": {
    "build": "tsc",
    "start": "node dist/index.js"
  }
}

Source: package.json

Running the Container

Basic Usage

docker run -p 8080:8080 -e TEMPLATEFOX_API_KEY=sk_your_api_key templatefox-mcp

This command:

  • Maps container port 8080 to host port 8080
  • Passes the API key via environment variable
  • Starts the MCP server in HTTP mode

Source: README.md

Environment Variables

VariableRequiredDefaultDescription
TEMPLATEFOX_API_KEYYes-API key for TemplateFox API (starts with sk_)
PORTNoundefined (stdio mode)Set to enable HTTP transport mode
TEMPLATEFOX_BASE_URLNohttps://api.templatefox.comOverride API base URL

Source: src/index.ts:27-28, src/api-client.ts:6

Port Configuration

When the PORT environment variable is set, the server automatically switches from stdio mode to HTTP mode:

const port = process.env.PORT ? parseInt(process.env.PORT, 10) : undefined;

if (port) {
  // HTTP mode: Streamable HTTP transport
  const express = (await import("express")).default;
  // ... Express setup
  app.listen(port, "0.0.0.0", () => {
    console.error(`TemplateFox MCP server (HTTP) listening on http://0.0.0.0:${port}/mcp`);
  });
}

Source: src/index.ts:27-35

HTTP Endpoints

Health Check

GET /health

Returns server status and version information:

{
  "status": "ok",
  "version": "1.8.2"
}

Source: src/index.ts:42-45

MCP Endpoint

POST /mcp

Handles all MCP JSON-RPC requests. Supports the complete MCP protocol including:

  • initialize
  • tools/list
  • tools/call
  • ping

Request Headers:

HeaderRequiredDescription
AuthorizationYes*Bearer sk_your_api_key_here
x-api-keyYes*sk_your_api_key_here (alternative)
Content-TypeYesapplication/json for POST requests

*Either Authorization or x-api-key header is required.

Source: src/index.ts:47-62

Method Not Allowed Responses

{
  "jsonrpc": "2.0",
  "error": { "code": -32000, "message": "Method not allowed. Use POST for MCP requests." },
  "id": null
}

Both GET /mcp and DELETE /mcp return 405 Method Not Allowed responses since MCP requires POST.

Source: src/index.ts:81-92

API Key Authentication

The server implements per-request API key authentication for HTTP transport:

sequenceDiagram
    participant Client
    participant Docker as Docker Container
    participant MCP as MCP Server
    participant API as TemplateFox API
    
    Client->>Docker: POST /mcp with API key header
    Docker->>MCP: Extract API key from header
    MCP->>API: Forward request with API key
    API-->>MCP: Response data
    MCP-->>Client: JSON-RPC response

Key Extraction Logic

const authHeader = req.headers.authorization;
const apiKey = authHeader?.startsWith("Bearer ")
  ? authHeader.slice(7)
  : (req.headers["x-api-key"] as string | undefined);

Source: src/index.ts:47-53

Key Resolution Priority

  1. Per-request key from HTTP transport via AsyncLocalStorage
  2. Environment variable TEMPLATEFOX_API_KEY (stdio mode fallback)
function getApiKey(): string {
  const contextKey = apiKeyStore.getStore();
  if (contextKey) return contextKey;
  
  const key = process.env.TEMPLATEFOX_API_KEY;
  if (!key) {
    throw new Error("TEMPLATEFOX_API_KEY is required...");
  }
  return key;
}

Source: src/api-client.ts:18-30

Request Handling Flow

graph TD
    A[POST /mcp] --> B{API Key Present?}
    B -->|No| C[401 Unauthorized]
    B -->|Yes| D[Create MCP Server]
    D --> E[Create HTTP Transport]
    E --> F[Connect Server to Transport]
    F --> G[Handle Request with API Key Context]
    G --> H[Process JSON-RPC]
    H --> I[Return Response]
    I --> J[Close Transport & Server]
    
    style C fill:#ffcdd2
    style I fill:#c8e6c9

The server creates a fresh MCP server instance for each request to ensure stateless operation in cloud environments.

Source: src/index.ts:64-79

MCP Tools Available

Once deployed, the following tools are accessible via the MCP protocol:

ToolPurposeCredits
generate_pdfSynchronous PDF generation1
generate_pdf_asyncAsynchronous PDF generation with webhooks1
get_pdf_job_statusCheck async job status-
list_pdf_jobsList async PDF jobs-
list_templatesList available templates-
get_template_fieldsGet template field definitions-
get_account_infoCheck account credits-
list_transactionsView transaction history-

Source: src/tools.ts

Remote Server Deployment

Cloud Run Example

The server can be deployed to Google Cloud Run using the provided Dockerfile:

# Build and deploy
gcloud builds submit --tag gcr.io/PROJECT_ID/templatefox-mcp
gcloud run deploy templatefox-mcp --image gcr.io/PROJECT_ID/templatefox-mcp --port 8080

Connecting via URL

External MCP clients can connect to the deployed server:

https://mcp-server-599407781746.us-central1.run.app/mcp

Source: README.md

Container Networking

graph LR
    subgraph Host
        A[localhost:8080] --> B[Container:8080]
    end
    
    subgraph Container
        B --> C[Express Server]
        C --> D[MCP Handler]
        D --> E[TemplateFox API]
    end
    
    E -->|HTTPS| F[api.templatefox.com]

The container listens on all network interfaces (0.0.0.0) to accept external connections when deployed to cloud environments.

Source: src/index.ts:34

Dependencies

Production Dependencies

PackageVersionPurpose
@modelcontextprotocol/sdk^1.29.0MCP protocol implementation
express^5.2.1HTTP server framework
cors^2.8.6Cross-origin resource sharing

Source: package.json

Runtime Requirements

  • Node.js >= 18.0.0
  • Network access to api.templatefox.com
  • Valid TemplateFox API key

Source: package.json

Troubleshooting

Container Exits Immediately

Cause: Missing PORT environment variable.

Solution: Set PORT environment variable to enable HTTP mode:

docker run -p 8080:8080 -e PORT=8080 -e TEMPLATEFOX_API_KEY=sk_xxx templatefox-mcp

401 Unauthorized Errors

Cause: Missing or invalid API key in request headers.

Solution: Include API key via Authorization: Bearer header or x-api-key header.

Connection Refused

Cause: Port not mapped correctly or container not running.

Solution: Verify container is running and port mapping is correct:

docker ps | grep templatefox-mcp
docker port templatefox-mcp

Security Considerations

  • API keys are passed via HTTP headers; always use HTTPS in production
  • Container runs as non-root (recommended for production deployments)
  • Network isolation is handled by Docker's container networking
  • Environment variables should be managed via secrets in production orchestration systems

Source: src/index.ts:47-62

Source: https://github.com/TemplateFoxPDF/mcp-server / Human Manual

Doramagic Pitfall Log

Source-linked risks stay visible on the manual page so the preview does not read like a recommendation.

medium darkzodchi en X: "Top MCP Servers That Turn Claude Into a Productivity Machine" / X

First-time setup may fail or require extra isolation and rollback planning.

medium README/documentation is current enough for a first validation pass.

The project should not be treated as fully validated until this signal is reviewed.

medium Adding Github MCP to Claude Code Error : r/ClaudeAI - Reddit

The project should not be treated as fully validated until this signal is reviewed.

medium you need somewhere between 1-10 Claude skills depending on what ...

The project should not be treated as fully validated until this signal is reviewed.

Doramagic Pitfall Log

Doramagic extracted 9 source-linked risk signals. Review them before installing or handing real data to the project.

1. Installation risk: darkzodchi en X: "Top MCP Servers That Turn Claude Into a Productivity Machine" / X

  • Severity: medium
  • Finding: darkzodchi en X: "Top MCP Servers That Turn Claude Into a Productivity Machine" / X Each session returns a live browser URL your agent controls. Free: 100 sessions/mo · https://github.com/browserbase/mcp-server-browserbase · 12 — GitHub — PRs, issues, code search, CI/CD workflows. The first MCP server every developer…
  • User impact: First-time setup may fail or require extra isolation and rollback planning.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: social_signal:x | ssig_9df635b2db4e49dc88b24ae5e8230ed4 | https://x.com/zodchiii/status/2041804097628582294 | darkzodchi en X: "Top MCP Servers That Turn Claude Into a Productivity Machine" / X

2. Capability assumption: README/documentation is current enough for a first validation pass.

  • Severity: medium
  • Finding: README/documentation is current enough for a first validation pass.
  • User impact: The project should not be treated as fully validated until this signal is reviewed.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: capability.assumptions | mcp_registry:io.github.TemplateFoxPDF/mcp-server:1.9.7 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.TemplateFoxPDF%2Fmcp-server/versions/1.9.7 | README/documentation is current enough for a first validation pass.

3. Project risk: Adding Github MCP to Claude Code Error : r/ClaudeAI - Reddit

  • Severity: medium
  • Finding: Adding Github MCP to Claude Code Error : r/ClaudeAI - Reddit 22 Jun 2025 · Source of solution: https://github.com/github/github-mcp-server ... New in Claude Code: agent view. r/ClaudeAI - New in Claude Code ...
  • User impact: The project should not be treated as fully validated until this signal is reviewed.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: social_signal:reddit | ssig_928f35e76c1442709ae4143bf1ef6218 | https://www.reddit.com/r/ClaudeAI/comments/1li0v90/adding_github_mcp_to_claude_code_error/ | Adding Github MCP to Claude Code Error : r/ClaudeAI - Reddit

4. Project risk: you need somewhere between 1-10 Claude skills depending on what ...

  • Severity: medium
  • Finding: you need somewhere between 1-10 Claude skills depending on what ... 20 Mar 2026 · https://github.com/haris-musa/excel-mcp-server ... Claude Inspector — See hidden Claude Code prompt mechanics https://github.com/kangraemin/claude ...
  • User impact: The project should not be treated as fully validated until this signal is reviewed.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: social_signal:x | ssig_504e57203f64433a83bf7ec96631f94c | https://x.com/Hesamation/status/2035136966719582695 | you need somewhere between 1-10 Claude skills depending on what ...

5. Maintenance risk: Maintainer activity is unknown

  • Severity: medium
  • Finding: Maintenance risk is backed by a source signal: Maintainer activity is unknown. Treat it as a review item until the current version is checked.
  • User impact: Users cannot judge support quality until recent activity, releases, and issue response are checked.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: evidence.maintainer_signals | mcp_registry:io.github.TemplateFoxPDF/mcp-server:1.9.7 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.TemplateFoxPDF%2Fmcp-server/versions/1.9.7 | last_activity_observed missing

6. Security or permission risk: no_demo

  • Severity: medium
  • Finding: no_demo
  • User impact: The project may affect permissions, credentials, data exposure, or host boundaries.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: downstream_validation.risk_items | mcp_registry:io.github.TemplateFoxPDF/mcp-server:1.9.7 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.TemplateFoxPDF%2Fmcp-server/versions/1.9.7 | no_demo; severity=medium

7. Security or permission risk: no_demo

  • Severity: medium
  • Finding: no_demo
  • User impact: The project may affect permissions, credentials, data exposure, or host boundaries.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: risks.scoring_risks | mcp_registry:io.github.TemplateFoxPDF/mcp-server:1.9.7 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.TemplateFoxPDF%2Fmcp-server/versions/1.9.7 | no_demo; severity=medium

8. Maintenance risk: issue_or_pr_quality=unknown

  • Severity: low
  • Finding: issue_or_pr_quality=unknown。
  • User impact: Users cannot judge support quality until recent activity, releases, and issue response are checked.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: evidence.maintainer_signals | mcp_registry:io.github.TemplateFoxPDF/mcp-server:1.9.7 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.TemplateFoxPDF%2Fmcp-server/versions/1.9.7 | issue_or_pr_quality=unknown

9. Maintenance risk: release_recency=unknown

  • Severity: low
  • Finding: release_recency=unknown。
  • User impact: Users cannot judge support quality until recent activity, releases, and issue response are checked.
  • Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
  • Evidence: evidence.maintainer_signals | mcp_registry:io.github.TemplateFoxPDF/mcp-server:1.9.7 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.TemplateFoxPDF%2Fmcp-server/versions/1.9.7 | release_recency=unknown

Source: Doramagic discovery, validation, and Project Pack records

Community Discussion Evidence

These external discussion links are review inputs, not standalone proof that the project is production-ready.

Sources 12

Count of project-level external discussion links exposed on this manual page.

Use Review before install

Open the linked issues or discussions before treating the pack as ready for your environment.

Community Discussion Evidence

Doramagic exposes project-level community discussion separately from official documentation. Review these links before using mcp-server with real data or production workflows.

Source: Project Pack community evidence and pitfall evidence