# https://github.com/TemplateFoxPDF/mcp-server Project Manual

Generated on: 2026-05-22 15:16:53 UTC

## Table of Contents

- [Introduction](#page-introduction)
- [Project Structure](#page-project-structure)
- [Transport Modes](#page-transport-modes)
- [Server Initialization](#page-server-initialization)
- [PDF Generation Tools](#page-pdf-generation-tools)
- [Template Management Tools](#page-template-management-tools)
- [Account Management Tools](#page-account-management-tools)
- [API Client](#page-api-client)
- [Installation and Setup](#page-installation)
- [Docker Deployment](#page-docker-deployment)

<a id='page-introduction'></a>

## Introduction

### Related Pages

Related topics: [Project Structure](#page-project-structure), [PDF Generation Tools](#page-pdf-generation-tools), [Installation and Setup](#page-installation)

<details>
<summary>Relevant source files</summary>

The following source files were used to generate this page:

- [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)
- [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)
- [src/tools.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)
- [src/api-client.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)
- [src/index.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)
</details>

# 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:

| Tool | Purpose |
|------|---------|
| `generate_pdf` | Synchronous PDF generation from templates |
| `generate_pdf_async` | Asynchronous PDF generation with job queuing |
| `get_pdf_job_status` | Poll status of async generation jobs |
| `list_pdf_jobs` | List and filter async job history |
| `list_templates` | Discover available PDF templates |
| `get_template_fields` | Retrieve template variable definitions |
| `get_account_info` | Check account credits and status |
| `list_transactions` | View 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

```mermaid
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

| File | Responsibility |
|------|----------------|
| `src/index.ts` | Server initialization, transport configuration, HTTP middleware |
| `src/tools.ts` | MCP tool definitions using Zod schemas for validation |
| `src/api-client.ts` | HTTP 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]()

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

**Activation:**
```bash
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:**
```bash
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.

```mermaid
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]()

```typescript
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:

```typescript
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

| Hint | Description |
|------|-------------|
| `readOnlyHint: true` | Read-only operation (GET requests) |
| `destructiveHint: false` | Non-destructive operation |

Source: [src/tools.ts:50-60]()

## Server Configuration

### Environment Variables

| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `TEMPLATEFOX_API_KEY` | Yes (Stdio) | - | API key starting with `sk_` |
| `TEMPLATEFOX_BASE_URL` | No | `https://api.templatefox.com` | Override API base URL |
| `PORT` | No | - | 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:

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

**Endpoints:**

| Endpoint | Method | Purpose |
|----------|--------|---------|
| `/health` | GET | Health check with version info |
| `/mcp` | POST | MCP request handling |
| `/mcp` | GET/DELETE | Method not allowed (405) |

Source: [src/index.ts:27-45]()

## Package Metadata

| Property | Value |
|----------|-------|
| **Package Name** | `@templatefox/mcp-server` |
| **Version** | `1.10.1` |
| **Node.js Requirement** | `>=18.0.0` |
| **License** | MIT |
| **MCP Name** | `io.github.TemplateFoxPDF/mcp-server` |

Source: [package.json:1-25]()

### Core Dependencies

| Package | Version | Purpose |
|---------|---------|---------|
| `@modelcontextprotocol/sdk` | `^1.29.0` | MCP protocol implementation |
| `express` | `^5.2.1` | HTTP server framework |
| `cors` | `^2.8.6` | Cross-origin resource sharing |

Source: [package.json:26-32]()

## Quick Start Workflow

```mermaid
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

---

<a id='page-project-structure'></a>

## Project Structure

### Related Pages

Related topics: [Introduction](#page-introduction), [Server Initialization](#page-server-initialization), [API Client](#page-api-client)

<details>
<summary>Relevant source files</summary>

The following source files were used to generate this page:

- [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)
- [src/index.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)
- [src/tools.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)
- [src/api-client.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)
- [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)
</details>

# 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.

| Property | Value |
|----------|-------|
| **Package Name** | `@templatefox/mcp-server` |
| **Version** | 1.10.1 |
| **License** | MIT |
| **Node.js Requirement** | >=18.0.0 |
| **Module Type** | ESM (ECMAScript Modules) |
| **MCP SDK Version** | ^1.29.0 |
| Source: [package.json:1-18](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json) |

## 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

```mermaid
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 Mode | Trigger | Use Case |
|----------------|---------|----------|
| **Stdio** | No `PORT` variable | Local AI assistant integration |
| **HTTP** | `PORT` defined | Cloud Run, remote deployments |

Source: [src/index.ts:1-28](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

#### HTTP Transport Configuration

```typescript
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

#### API Key Extraction

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

| Header | Format | Priority |
|--------|--------|----------|
| `Authorization` | `Bearer sk_xxx` | Primary |
| `x-api-key` | `sk_xxx` | Fallback |

Source: [src/index.ts:47-53](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

### 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

```mermaid
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)

#### Request Building

The `apiRequest` function constructs HTTP requests with the following components:

| Component | Value |
|-----------|-------|
| **Base URL** | `TEMPLATEFOX_BASE_URL` or `https://api.templatefox.com` |
| **Method** | GET or POST |
| **Authentication** | `x-api-key` header |
| **Content-Type** | `application/json` (for POST) |
| **Accept** | `application/json` |

Source: [src/api-client.ts:49-78](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)

### 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

| Category | Tools | Operations |
|----------|-------|------------|
| **PDF Generation** | `generate_pdf`, `generate_pdf_async` | Create PDFs synchronously or asynchronously |
| **Job Management** | `get_pdf_job_status`, `list_pdf_jobs` | Monitor and list async jobs |
| **Templates** | `list_templates`, `get_template_fields` | Discover available templates |
| **Account** | `get_account_info`, `list_transactions` | View credits and history |

Source: [src/tools.ts:1-200](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)

#### Tool Definition Pattern

Each MCP tool follows this schema:

```typescript
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)

#### Available Tools Reference

| Tool | HTTP Method | Endpoint | Credits | Async Support |
|------|-------------|----------|---------|---------------|
| `generate_pdf` | POST | `/v1/pdf/create` | 1 | No |
| `generate_pdf_async` | POST | `/v1/pdf/create-async` | 1 | Yes |
| `get_pdf_job_status` | GET | `/v1/pdf/jobs/{job_id}` | 0 | - |
| `list_pdf_jobs` | GET | `/v1/pdf/jobs` | 0 | - |
| `list_templates` | GET | `/v1/templates` | 0 | - |
| `get_template_fields` | GET | `/v1/templates/{id}/fields` | 0 | - |
| `get_account_info` | GET | `/v1/account` | 0 | - |
| `list_transactions` | GET | `/v1/account/transactions` | 0 | - |

Source: [src/tools.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)

## Build Configuration

### Package Scripts

| Script | Command | Purpose |
|--------|---------|---------|
| `build` | `tsc` | Compile TypeScript to JavaScript |
| `start` | `node dist/index.js` | Run the compiled server |

Source: [package.json:12-15](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)

### Dependencies

#### Production Dependencies

| Package | Version | Purpose |
|---------|---------|---------|
| `@modelcontextprotocol/sdk` | ^1.29.0 | MCP protocol implementation |
| `express` | ^5.2.1 | HTTP server framework |
| `cors` | ^2.8.6 | Cross-origin resource sharing |

Source: [package.json:16-20](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)

#### Development Dependencies

| Package | Version | Purpose |
|---------|---------|---------|
| `typescript` | ^5.8.0 | TypeScript compiler |
| `@types/node` | ^22.0.0 | Node.js type definitions |
| `@types/express` | ^5.0.0 | Express type definitions |
| `@types/cors` | ^2.8.0 | CORS type definitions |

Source: [package.json:21-25](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)

### Binary Configuration

The package exposes a CLI binary for global installation:

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

Source: [package.json:9-11](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)

## Deployment Modes

### Stdio Mode (Local)

Default mode for AI assistant integration via npx:

```bash
npx -y @templatefox/mcp-server
```

Requires `TEMPLATEFOX_API_KEY` environment variable.

Source: [README.md:15-24](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)

### HTTP Mode (Cloud)

Enabled by setting the `PORT` environment variable:

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

| Endpoint | Method | Purpose |
|----------|--------|---------|
| `/health` | GET | Health check |
| `/mcp` | POST | MCP request handler |

Source: [src/index.ts:35-39](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

### Docker Deployment

The project includes Dockerfile support for containerized deployments:

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

Source: [README.md:66-70](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)

## Data Flow Architecture

### Synchronous PDF Generation

```mermaid
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

```mermaid
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

| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `TEMPLATEFOX_API_KEY` | Yes (stdio) / No (HTTP) | - | API key starting with `sk_` |
| `TEMPLATEFOX_BASE_URL` | No | `https://api.templatefox.com` | Override API base URL |
| `PORT` | No | undefined | Enable HTTP mode on specified port |

Source: [README.md:42-47](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)

## Workflow Example

A typical AI-assisted PDF generation workflow:

```mermaid
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)

## Keywords and Metadata

The package includes comprehensive metadata for discoverability:

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

Source: [package.json:26-34](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)

---

<a id='page-transport-modes'></a>

## Transport Modes

### Related Pages

Related topics: [Server Initialization](#page-server-initialization), [Installation and Setup](#page-installation), [Docker Deployment](#page-docker-deployment)

<details>
<summary>Relevant source files</summary>

The following source files were used to generate this page:

- [src/index.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)
- [src/api-client.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)
- [src/tools.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)
- [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)
- [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)
</details>

# 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 Mode | Use Case | Deployment | Default |
|---------------|----------|------------|---------|
| **Stdio** | Local development, desktop AI assistants | Same machine as client | Yes |
| **Streamable HTTP** | Remote/cloud deployments, web services | Separate server | No (when PORT is set) |

Source: [src/index.ts:1-50](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

## Architecture

```mermaid
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:

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

Or with a global installation:

```bash
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

2. A `StdioServerTransport` is created to handle stdio communication. Source: [src/index.ts:30](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

3. The server connects to the transport and awaits requests from stdin. Source: [src/index.ts:31-32](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

### 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:

```typescript
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)

## 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:

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

Source: [src/index.ts:34](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

### Express.js Server Setup

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

```typescript
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

### Endpoints

| Endpoint | Method | Purpose |
|----------|--------|---------|
| `/health` | GET | Health check for monitoring |
| `/mcp` | POST | MCP request handling |

Source: [src/index.ts:42-44](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts) and [src/index.ts:68-88](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

### Health Check Endpoint

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

Source: [src/index.ts:42-44](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

### 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:

```typescript
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

### API Key Extraction in HTTP Mode

HTTP transport supports two header formats for API key authentication:

| Header Format | Example |
|--------------|---------|
| `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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

### Per-Request API Key Handling

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

```typescript
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)

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:

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

Source: [src/index.ts:80-82](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

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

### Error Handling

HTTP mode includes comprehensive error responses:

```typescript
// 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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts) and [src/index.ts:95-99](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

### Method Restriction

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

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

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

Source: [src/index.ts:90-99](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

## Deployment Options

### Docker Deployment

For containerized HTTP deployments:

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

Source: [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)

### Claude Desktop Configuration

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

Source: [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)

### Claude Code Configuration

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

Source: [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)

## Environment Variables

| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `TEMPLATEFOX_API_KEY` | Yes | - | API key (starts with `sk_`) |
| `TEMPLATEFOX_BASE_URL` | No | `https://api.templatefox.com` | Override API base URL |
| `PORT` | No | - | Enables HTTP mode when set |

Source: [src/index.ts:34](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts) and [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)

## Dependencies

The transport implementation relies on these packages:

| Package | Version | Purpose |
|---------|---------|---------|
| `@modelcontextprotocol/sdk` | ^1.29.0 | MCP protocol and transport classes |
| `express` | ^5.2.1 | HTTP server framework |
| `cors` | ^2.8.6 | Cross-origin resource sharing |

Source: [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)

## Comparison: Stdio vs HTTP

| Aspect | Stdio | Streamable HTTP |
|--------|-------|-----------------|
| **Startup** | Immediate | Requires PORT variable |
| **Connection** | Process-based | TCP/HTTP |
| **API Key Source** | Environment variable | Per-request header |
| **Scalability** | Single client | Multiple clients |
| **Use Case** | Desktop integrations | Cloud deployments |
| **Session Support** | Native (process) | Stateless (no sessions) |
| **AsyncLocalStorage** | Not used | Used for per-request context |

## Request Flow Comparison

```mermaid
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:

```typescript
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)

---

<a id='page-server-initialization'></a>

## Server Initialization

### Related Pages

Related topics: [Transport Modes](#page-transport-modes), [PDF Generation Tools](#page-pdf-generation-tools)

<details>
<summary>Relevant source files</summary>

The following source files were used to generate this page:

- [src/index.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)
- [src/tools.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)
- [src/api-client.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)
- [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)
- [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)
</details>

# 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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

```typescript
#!/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.

| Mode | Trigger | Use Case |
|------|---------|----------|
| **Stdio** | No `PORT` env var | Local CLI usage via npx, Claude Desktop |
| **HTTP** | `PORT` env var set | Remote/cloud deployment, self-hosted |

Source: [src/index.ts:25-26](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

```typescript
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

```typescript
// 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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

```typescript
// 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.

```mermaid
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

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

The server configuration constants are defined as:

| Constant | Value | Purpose |
|----------|-------|---------|
| `SERVER_NAME` | `"templatefox"` | Server identifier for MCP protocol |
| `SERVER_VERSION` | `"1.8.2"` | Semantic version of the server |

Source: [src/index.ts:6-8](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

## HTTP Server Endpoints

The HTTP transport mode exposes two endpoints:

### Health Check Endpoint

Source: [src/index.ts:33-36](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

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

### MCP Request Endpoint

Source: [src/index.ts:38-68](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

```typescript
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:

```typescript
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

## API Key Handling

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

```mermaid
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)

```typescript
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

```typescript
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

```typescript
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)

```typescript
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)

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

### Available Tools

| Tool | Description | Credits | Read-Only |
|------|-------------|---------|-----------|
| `generate_pdf` | Generate PDF from template | 1 | No |
| `generate_pdf_async` | Queue async PDF generation | 1 | No |
| `get_pdf_job_status` | Check async job status | - | Yes |
| `list_pdf_jobs` | List async jobs | - | Yes |
| `list_templates` | List available templates | - | Yes |
| `get_template_fields` | Get template field definitions | - | Yes |
| `get_account_info` | Get account and credit info | - | Yes |
| `list_transactions` | View credit transaction history | - | Yes |

Source: [src/tools.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)

## Configuration Options

### Environment Variables

| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `TEMPLATEFOX_API_KEY` | Yes (Stdio) / Via Header (HTTP) | - | API key starting with `sk_` |
| `TEMPLATEFOX_BASE_URL` | No | `https://api.templatefox.com` | Override API base URL |
| `PORT` | No | - | Enable HTTP mode on specified port |

Source: [src/api-client.ts:15](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)

### Build and Runtime Scripts

Source: [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)

| Script | Command | Purpose |
|--------|---------|---------|
| `build` | `tsc` | Compile TypeScript to JavaScript |
| `start` | `node dist/index.js` | Run the compiled server |

### Server Binaries

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

## Startup Sequence

```mermaid
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

```typescript
} 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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

```typescript
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)
Source: [src/index.ts:8](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

## Dependencies

The server initialization relies on these core dependencies:

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

Source: [package.json:24-35](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)

---

<a id='page-pdf-generation-tools'></a>

## PDF Generation Tools

### Related Pages

Related topics: [Template Management Tools](#page-template-management-tools), [Account Management Tools](#page-account-management-tools), [API Client](#page-api-client)

<details>
<summary>Relevant source files</summary>

The following source files were used to generate this page:

- [src/tools.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)
- [src/api-client.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)
- [src/index.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)
- [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)
- [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)
</details>

# 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:

```mermaid
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts), [src/api-client.ts:1-15](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)

## 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.

```mermaid
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)

## 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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)

#### Input Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `template_id` | string | Yes | Template short ID (12 characters) |
| `data` | Record<string, unknown> | Yes | Key-value data to render in the template. Keys must match template variables. |
| `export_type` | enum | No | Export format: `url` (upload to CDN, return URL) or `binary` (return raw PDF bytes) |
| `expiration` | number | No | URL expiration in seconds (60-604800, i.e., 1 min to 7 days). Only applies to `url` export type. |
| `filename` | string | No | Custom filename for the PDF (without .pdf extension). Defaults to 'document'. |
| `store_s3` | boolean | No | Upload to configured S3 bucket instead of CDN |
| `s3_filepath` | string | No | Custom path prefix in S3 bucket |
| `s3_bucket` | string | No | Override the default S3 bucket configured in S3 integration |
| `pdf_variant` | enum | No | Standards-compliant PDF variant: `pdf/a-1b`, `pdf/a-2b`, or `pdf/a-3b` |
| `version` | string | No | Optional 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:

| Variant | Use Case |
|---------|----------|
| `pdf/a-1b` | Basic archival compliance |
| `pdf/a-2b` | Most common for archival compliance |
| `pdf/a-3b` | Required for documents with file attachments (e.g., Factur-X, ZUGFeRD invoices) |

#### Hints

| Hint | Value | Description |
|------|-------|-------------|
| `destructiveHint` | false | Indicates this tool does not delete data |

Source: [src/tools.ts:20-60](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)

### 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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)

#### Input Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `template_id` | string | Yes | Template short ID (12 characters) |
| `data` | Record<string, unknown> | Yes | Key-value data to render in the template |
| `export_type` | enum | No | Export format. Currently only `url` is supported for async. |
| `expiration` | number | No | URL expiration in seconds (60-604800). Default: 86400 (24 hours) |
| `filename` | string | No | Custom filename for the PDF |
| `store_s3` | boolean | No | Upload to configured S3 bucket |
| `s3_filepath` | string | No | Custom path prefix in S3 bucket |
| `s3_bucket` | string | No | Override the default S3 bucket |
| `webhook_url` | string | No | HTTPS URL to receive POST notification when job completes or fails |
| `webhook_secret` | string | No | Secret for HMAC-SHA256 signing of webhook payloads (minimum 16 characters) |
| `pdf_variant` | enum | No | PDF/A variant for compliance |
| `version` | string | No | Version tag or number |

#### Async Workflow

```mermaid
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)

## 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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)

#### Input Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `job_id` | string | Yes | Async job ID (UUID returned by the create-async endpoint) |

#### Job Status Values

| Status | Description |
|--------|-------------|
| `pending` | Job is queued but not yet processing |
| `processing` | PDF generation is in progress |
| `completed` | PDF generation finished successfully; PDF URL available |
| `failed` | PDF generation failed; check error details |

#### Hints

| Hint | Value | Description |
|------|-------|-------------|
| `readOnlyHint` | true | This tool only reads data, no modifications |

Source: [src/tools.ts:125-145](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)

### 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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)

#### Input Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `limit` | number | No | Maximum number of results to return |
| `offset` | number | No | Number of results to skip (for pagination) |
| `status` | enum | No | Filter jobs by status: `pending`, `processing`, `completed`, or `failed` |

#### Hints

| Hint | Value | Description |
|------|-------|-------------|
| `readOnlyHint` | true | This tool only reads data |

Source: [src/tools.ts:150-175](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)

## 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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)

#### Hints

| Hint | Value | Description |
|------|-------|-------------|
| `readOnlyHint` | true | This tool only reads data |

#### Usage Pattern

```mermaid
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)

### 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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)

#### Input Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `template_id` | string | Yes | Template short ID (12 characters) |

#### Hints

| Hint | Value | Description |
|------|-------|-------------|
| `readOnlyHint` | true | This 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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)

## 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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)

#### Hints

| Hint | Value | Description |
|------|-------|-------------|
| `readOnlyHint` | true | This tool only reads data |

Source: [src/tools.ts:235-255](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)

### 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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)

#### Input Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `limit` | number | No | Number of records to return (1-1000) |
| `offset` | number | No | Number of records to skip for pagination |

#### Hints

| Hint | Value | Description |
|------|-------|-------------|
| `readOnlyHint` | true | This tool only reads data |

Source: [src/tools.ts:260-285](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)

## 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

```mermaid
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

```mermaid
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)

## Configuration

### Environment Variables

| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `TEMPLATEFOX_API_KEY` | Yes (stdio mode) | - | API key starting with `sk_` |
| `TEMPLATEFOX_BASE_URL` | No | `https://api.templatefox.com` | Override API base URL |
| `PORT` | No | - | 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:

| Header | Format | Example |
|--------|--------|---------|
| `Authorization` | `Bearer <key>` | `Authorization: Bearer sk_abc123...` |
| `x-api-key` | `<key>` | `x-api-key: sk_abc123...` |

Source: [src/index.ts:35-55](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts), [README.md:1-80](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)

## Complete Tool Summary

| Tool | Name | Purpose | Read-Only |
|------|------|---------|-----------|
| `generate_pdf` | Synchronous PDF Generation | Create PDF from template with data | No |
| `generate_pdf_async` | Async PDF Generation | Queue PDF job with webhook support | No |
| `get_pdf_job_status` | Job Status Check | Poll async job status by ID | Yes |
| `list_pdf_jobs` | Job List | List jobs with pagination/filtering | Yes |
| `list_templates` | Template Discovery | List available templates | Yes |
| `get_template_fields` | Field Discovery | Get template variable definitions | Yes |
| `get_account_info` | Account Info | View credits and account details | Yes |
| `list_transactions` | Transaction History | View credit transaction log | Yes |

Source: [src/tools.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)

## Version Information

| Component | Version |
|-----------|---------|
| Package | `@templatefox/mcp-server` |
| Server | 1.8.2 |
| Package.json | 1.10.1 |
| MCP SDK | ^1.29.0 |
| Node.js Requirement | >=18.0.0 |

Source: [package.json:1-20](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json), [src/index.ts:10](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

---

<a id='page-template-management-tools'></a>

## Template Management Tools

### Related Pages

Related topics: [PDF Generation Tools](#page-pdf-generation-tools), [Introduction](#page-introduction)

<details>
<summary>Relevant source files</summary>

The following source files were used to generate this page:

- [src/tools.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)
- [src/api-client.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)
- [src/index.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)
- [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)
- [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)
</details>

# 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:

| Component | File | Responsibility |
|-----------|------|----------------|
| MCP Server | `src/index.ts` | Initializes the MCP server and registers tools |
| Tool Registration | `src/tools.ts` | Defines and registers template management tools |
| API Client | `src/api-client.ts` | Handles HTTP communication with TemplateFox API |

### Data Flow

```mermaid
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts#L8-L9)
Source: [src/api-client.ts:19-35](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts#L19-L35)

## 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:**

```typescript
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts#L115-L128)

**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:**

```typescript
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts#L130-L145)

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `template_id` | string | Yes | Template 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:

```mermaid
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md#L58-L70)

## Configuration Requirements

### Environment Variables

| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `TEMPLATEFOX_API_KEY` | Yes | — | API key starting with `sk_` |
| `TEMPLATEFOX_BASE_URL` | No | `https://api.templatefox.com` | Override API base URL |

Source: [README.md:38-47](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md#L38-L47)

### Transport Modes

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

| Mode | Command | Use Case |
|------|---------|----------|
| Stdio | `npx -y @templatefox/mcp-server` | Local desktop integration (Claude Desktop, Cursor, Windsurf) |
| HTTP | `PORT=8080` + server binary | Remote/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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md#L45-L56)
Source: [src/index.ts:32-50](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts#L32-L50)

## 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`:

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

Source: [src/index.ts:16-23](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts#L16-L23)

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

```typescript
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts#L4-L11)

## 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:

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

Source: [src/tools.ts:123-128](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts#L123-L128)

Common error scenarios include:

| Error | Cause | Resolution |
|-------|-------|------------|
| 401 Unauthorized | Missing or invalid API key | Ensure `TEMPLATEFOX_API_KEY` is set correctly |
| 404 Not Found | Invalid template ID | Verify the template ID is 12 characters and exists |
| 500 Internal Server Error | TemplateFox API issue | Check TemplateFox status page |

## Package Information

| Property | Value |
|----------|-------|
| Package Name | `@templatefox/mcp-server` |
| Version | `1.10.1` |
| License | MIT |
| Node Engine | `>=18.0.0` |
| SDK | `@modelcontextprotocol/sdk` ^1.29.0 |

Source: [package.json:2-10](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json#L2-L10)

---

<a id='page-account-management-tools'></a>

## Account Management Tools

### Related Pages

Related topics: [PDF Generation Tools](#page-pdf-generation-tools)

<details>
<summary>Relevant source files</summary>

The following source files were used to generate this page:

- [src/tools.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)
- [src/api-client.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)
- [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)
- [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)
</details>

# 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.

```mermaid
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 Name | Description | Endpoint |
|-----------|-------------|----------|
| `get_account_info` | Retrieve account details and remaining credits | `GET /v1/account` |
| `list_transactions` | Fetch paginated credit transaction history | `GET /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

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| (none) | - | - | This tool accepts no input parameters |

### Implementation

```typescript
// 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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)*

### 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

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `limit` | number (integer) | No | - | Number of records to return (1-1000) |
| `offset` | number (integer) | No | 0 | Number of records to skip for pagination |
| `status` | enum | No | - | Filter by transaction status |

### Implementation

```typescript
// 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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)*

### Pagination Behavior

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

```typescript
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)*

### 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:

```mermaid
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)

```typescript
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)*

### HTTP Mode (Request Headers)

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

```typescript
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)*

## Configuration

| Environment Variable | Required | Default | Description |
|---------------------|----------|---------|-------------|
| `TEMPLATEFOX_API_KEY` | Yes | - | API key starting with `sk_` |
| `TEMPLATEFOX_BASE_URL` | No | `https://api.templatefox.com` | Override API base URL |

*Source: [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)*

## Error Handling

Both Account Management Tools include standardized error handling:

```typescript
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:
```json
{
  "credits": 150,
  "email": "user@example.com",
  "status": "active"
}
```

### Retrieving Transaction History

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

Response:
```json
{
  "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
}
```

## Related Tools

| Tool | Category | Purpose |
|------|----------|---------|
| `generate_pdf` | PDF Generation | Create PDFs (consumes credits) |
| `generate_pdf_async` | PDF Generation | Async PDF creation with webhooks |
| `list_templates` | Template Discovery | Browse available templates |
| `get_template_fields` | Template Discovery | Get template field definitions |

---

<a id='page-api-client'></a>

## API Client

### Related Pages

Related topics: [PDF Generation Tools](#page-pdf-generation-tools)

<details>
<summary>Relevant source files</summary>

The following source files were used to generate this page:

- [src/api-client.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)
- [src/tools.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)
- [src/index.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)
- [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)
- [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)
</details>

# 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:**
```typescript
const BASE_URL = process.env.TEMPLATEFOX_BASE_URL || "https://api.templatefox.com";
```
Source: [`src/api-client.ts:11`](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)

## Architecture

### Request Flow

```mermaid
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 Mode | Trigger | API Key Source | Use Case |
|----------------|---------|-----------------|----------|
| **Stdio** | No `PORT` env var | `process.env.TEMPLATEFOX_API_KEY` | Local Claude Desktop, npx usage |
| **HTTP** | `PORT` env var set | Per-request Authorization header | Cloud Run, self-hosted, remote clients |

Source: [`src/index.ts:22-23`](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

## Core Components

### ApiResponse Interface

```typescript
interface ApiResponse {
  ok: boolean;
  status: number;
  data: unknown;
}
```

| Property | Type | Description |
|----------|------|-------------|
| `ok` | `boolean` | Indicates if the HTTP response status was in the 2xx range |
| `status` | `number` | HTTP status code from the API |
| `data` | `unknown` | Parsed response body (JSON object or raw string) |

Source: [`src/api-client.ts:58-62`](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)

### The `apiRequest` Function

The central function for making API calls:

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

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `method` | `string` | Yes | HTTP method (GET, POST, etc.) |
| `path` | `string` | Yes | API endpoint path (e.g., `/v1/pdf/create`) |
| `body` | `Record<string, unknown>` | No | JSON request body for POST requests |
| `query` | `Record<string, string \| number \| undefined>` | No | Query 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`](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)

### API Key Management

#### AsyncLocalStorage for Per-Request Keys

```typescript
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`](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)

#### The `runWithApiKey` Function

```typescript
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`](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)

#### The `getApiKey` Function

```typescript
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`](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)

## Usage in Tools

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

```typescript
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:**

| Tool | Method | Endpoint | Purpose |
|------|--------|----------|---------|
| `generate_pdf` | POST | `/v1/pdf/create` | Synchronous PDF generation |
| `generate_pdf_async` | POST | `/v1/pdf/create-async` | Async PDF generation with webhooks |
| `get_pdf_job_status` | GET | `/v1/pdf/jobs/{job_id}` | Check async job status |
| `list_pdf_jobs` | GET | `/v1/pdf/jobs` | List all async jobs |
| `list_templates` | GET | `/v1/templates` | List available templates |
| `get_template_fields` | GET | `/v1/templates/{template_id}/fields` | Get template schema |
| `get_account_info` | GET | `/v1/account` | Account and credit info |
| `list_transactions` | GET | `/v1/account/transactions` | Credit transaction history |

Source: [`src/tools.ts`](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)

## HTTP Transport Integration

### Request Handling in Express

```typescript
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`](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

### Supported Authentication Headers

| Header | Format | Example |
|--------|--------|---------|
| `Authorization` | `Bearer <api_key>` | `Authorization: Bearer sk_live_abc123...` |
| `x-api-key` | `<api_key>` | `x-api-key: sk_live_abc123...` |

## Configuration

### Environment Variables

| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `TEMPLATEFOX_API_KEY` | Yes (Stdio) / No (HTTP) | - | API key starting with `sk_` |
| `TEMPLATEFOX_BASE_URL` | No | `https://api.templatefox.com` | Override API base URL |
| `PORT` | No | - | If set, enables HTTP transport mode |

Source: [`package.json`](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json) and [`README.md`](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)

## Dependencies

The API Client relies on these npm packages:

| Package | Version | Purpose |
|---------|---------|---------|
| `@modelcontextprotocol/sdk` | `^1.29.0` | MCP server framework |
| `express` | `^5.2.1` | HTTP server for remote transport |
| `cors` | `^5.2.6` | CORS middleware for HTTP mode |

Source: [`package.json`](https://github.com/TemplateFoxPDF/mcp-server/blob/main/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:

```typescript
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:

```typescript
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`](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

---

<a id='page-installation'></a>

## Installation and Setup

### Related Pages

Related topics: [Docker Deployment](#page-docker-deployment), [Transport Modes](#page-transport-modes)

<details>
<summary>Relevant source files</summary>

The following source files were used to generate this page:

- [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)
- [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)
- [src/index.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)
- [src/api-client.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)
</details>

# 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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)

## Prerequisites

### System Requirements

| Requirement | Specification |
|-------------|---------------|
| Node.js Version | `>= 18.0.0` |
| Package Manager | npm, yarn, or pnpm |
| Network Access | Outbound HTTPS to `api.templatefox.com` |

**Source:** [package.json:17-19](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)

### Required Credentials

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

1. Visit [app.templatefox.com/dashboard/api-keys](https://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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)

## Installation Methods

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

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

**Source:** [README.md:21-28](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)

### Method 2: Global npm Installation

For command-line usage or custom MCP configurations:

```bash
npm install -g @templatefox/mcp-server
```

After global installation, use the CLI directly:

```bash
templatefox-mcp-server
```

**Source:** [README.md:29-31](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)

### Method 3: Docker Deployment

Build and run the server in a container:

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

**Source:** [README.md:66-67](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)

## Claude Desktop Configuration

### Configuration File Location

| Operating System | Config 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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)

### Configuration Format

Add the following to your Claude Desktop config:

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

**Source:** [README.md:17-27](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)

## Claude Code Configuration

### CLI Installation

Use the Claude Code MCP management command:

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

Set the `TEMPLATEFOX_API_KEY` environment variable in your shell configuration:

```bash
export TEMPLATEFOX_API_KEY=sk_your_api_key_here
```

**Source:** [README.md:37-45](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)

## Cursor and Windsurf Configuration

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

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

**Source:** [README.md:47-52](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)

## Environment Variables

### Configuration Reference

| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `TEMPLATEFOX_API_KEY` | Yes | - | Your API key (starts with `sk_`) |
| `TEMPLATEFOX_BASE_URL` | No | `https://api.templatefox.com` | Override API base URL |
| `PORT` | No | - | Enable HTTP mode on specified port |

**Source:** [README.md:57-63](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)

### API Key Resolution Order

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

```mermaid
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)

## HTTP Transport Mode

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

### Server Architecture

```mermaid
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:

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

**Source:** [README.md:69-70](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)

### 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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)

### HTTP Authentication

MCP clients must pass the API key via HTTP header:

```http
Authorization: Bearer sk_your_api_key_here
```

Or alternatively:

```http
x-api-key: sk_your_api_key_here
```

**Source:** [README.md:79-86](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)

### HTTP Server Endpoints

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/health` | GET | Health check endpoint |
| `/mcp` | POST | MCP request endpoint |
| `/mcp` | GET | Returns 405 Method Not Allowed |
| `/mcp` | DELETE | Returns 405 (sessions not supported) |

**Source:** [src/index.ts:42-56](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

### Per-Request API Key Handling

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

```mermaid
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)

## 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:

```mermaid
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

## Build from Source

For development or custom deployments:

```bash
# 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

| Script | Command | Description |
|--------|---------|-------------|
| `build` | `tsc` | Compiles TypeScript to JavaScript |
| `start` | `node dist/index.js` | Runs the compiled server |

**Source:** [package.json:8-11](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)

## Transport Selection Flow

```mermaid
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

## Package Metadata

| Property | Value |
|----------|-------|
| Package Name | `@templatefox/mcp-server` |
| Version | `1.10.1` |
| License | MIT |
| MCP Server Name | `io.github.TemplateFoxPDF/mcp-server` |
| Homepage | `https://templatefox.com` |

**Source:** [package.json:2-9](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)

## Dependencies

| Dependency | Version | Purpose |
|------------|---------|---------|
| `@modelcontextprotocol/sdk` | `^1.29.0` | MCP protocol implementation |
| `express` | `^5.2.1` | HTTP server framework |
| `cors` | `^2.8.6` | Cross-origin resource sharing |

**Source:** [package.json:12-15](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)

## 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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)

---

<a id='page-docker-deployment'></a>

## Docker Deployment

### Related Pages

Related topics: [Installation and Setup](#page-installation), [Transport Modes](#page-transport-modes)

<details>
<summary>Relevant source files</summary>

The following source files were used to generate this page:

- [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)
- [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)
- [src/index.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)
- [src/api-client.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)
- [src/tools.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)
</details>

# 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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)

## Architecture

```mermaid
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

## Building the Docker Image

### Prerequisites

- Docker Engine 20.10+
- TemplateFox API key (obtained from [app.templatefox.com/dashboard/api-keys](https://app.templatefox.com/dashboard/api-keys))

### Build Command

```bash
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json) (build script)

### Build Script Configuration

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

Source: [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)

## Running the Container

### Basic Usage

```bash
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)

### Environment Variables

| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `TEMPLATEFOX_API_KEY` | Yes | - | API key for TemplateFox API (starts with `sk_`) |
| `PORT` | No | undefined (stdio mode) | Set to enable HTTP transport mode |
| `TEMPLATEFOX_BASE_URL` | No | `https://api.templatefox.com` | Override API base URL |

Source: [src/index.ts:27-28](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts), [src/api-client.ts:6](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)

### Port Configuration

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

```typescript
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

## HTTP Endpoints

### Health Check

```
GET /health
```

Returns server status and version information:

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

Source: [src/index.ts:42-45](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

### MCP Endpoint

```
POST /mcp
```

Handles all MCP JSON-RPC requests. Supports the complete MCP protocol including:
- `initialize`
- `tools/list`
- `tools/call`
- `ping`

**Request Headers:**

| Header | Required | Description |
|--------|----------|-------------|
| `Authorization` | Yes* | `Bearer sk_your_api_key_here` |
| `x-api-key` | Yes* | `sk_your_api_key_here` (alternative) |
| `Content-Type` | Yes | `application/json` for POST requests |

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

Source: [src/index.ts:47-62](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

### Method Not Allowed Responses

```json
{
  "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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

## API Key Authentication

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

```mermaid
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

```typescript
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

### Key Resolution Priority

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

```typescript
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)

## Request Handling Flow

```mermaid
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

## MCP Tools Available

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

| Tool | Purpose | Credits |
|------|---------|---------|
| `generate_pdf` | Synchronous PDF generation | 1 |
| `generate_pdf_async` | Asynchronous PDF generation with webhooks | 1 |
| `get_pdf_job_status` | Check async job status | - |
| `list_pdf_jobs` | List async PDF jobs | - |
| `list_templates` | List available templates | - |
| `get_template_fields` | Get template field definitions | - |
| `get_account_info` | Check account credits | - |
| `list_transactions` | View transaction history | - |

Source: [src/tools.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)

## Remote Server Deployment

### Cloud Run Example

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

```bash
# 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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)

## Container Networking

```mermaid
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

## Dependencies

### Production Dependencies

| Package | Version | Purpose |
|---------|---------|---------|
| `@modelcontextprotocol/sdk` | ^1.29.0 | MCP protocol implementation |
| `express` | ^5.2.1 | HTTP server framework |
| `cors` | ^2.8.6 | Cross-origin resource sharing |

Source: [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)

### Runtime Requirements

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

Source: [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)

## Troubleshooting

### Container Exits Immediately

**Cause:** Missing `PORT` environment variable.

**Solution:** Set `PORT` environment variable to enable HTTP mode:
```bash
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:
```bash
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](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)

---

---

## Doramagic Pitfall Log

Project: templatefoxpdf/mcp-server

Summary: Found 9 potential pitfall items; 0 are high/blocking. Highest priority: installation - 社区讨论暴露的待验证问题：darkzodchi en X: "Top MCP Servers That Turn Claude Into a Productivity Machine" / X.

## 1. installation · 社区讨论暴露的待验证问题：darkzodchi en X: "Top MCP Servers That Turn Claude Into a Productivity Machine" / X

- Severity: medium
- Evidence strength: source_linked
- 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: 这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。
- Suggested check: Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。
- 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 · 能力判断依赖假设

- Severity: medium
- Evidence strength: source_linked
- Finding: README/documentation is current enough for a first validation pass.
- User impact: 假设不成立时，用户拿不到承诺的能力。
- Suggested check: 将假设转成下游验证清单。
- Guardrail action: 假设必须转成验证项；没有验证结果前不能写成事实。
- 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. runtime · 社区讨论暴露的待验证问题：Adding Github MCP to Claude Code Error : r/ClaudeAI - Reddit

- Severity: medium
- Evidence strength: source_linked
- 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: 这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。
- Suggested check: Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。
- 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. runtime · 社区讨论暴露的待验证问题：you need somewhere between 1-10 Claude skills depending on what ...

- Severity: medium
- Evidence strength: source_linked
- 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: 这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。
- Suggested check: Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。
- 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 · 维护活跃度未知

- Severity: medium
- Evidence strength: source_linked
- Finding: 未记录 last_activity_observed。
- User impact: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- Suggested check: 补 GitHub 最近 commit、release、issue/PR 响应信号。
- Guardrail action: 维护活跃度未知时，推荐强度不能标为高信任。
- 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_permissions · 下游验证发现风险项

- Severity: medium
- Evidence strength: source_linked
- Finding: no_demo
- User impact: 下游已经要求复核，不能在页面中弱化。
- Suggested check: 进入安全/权限治理复核队列。
- Guardrail action: 下游风险存在时必须保持 review/recommendation 降级。
- 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_permissions · 存在评分风险

- Severity: medium
- Evidence strength: source_linked
- Finding: no_demo
- User impact: 风险会影响是否适合普通用户安装。
- Suggested check: 把风险写入边界卡，并确认是否需要人工复核。
- Guardrail action: 评分风险必须进入边界卡，不能只作为内部分数。
- 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 · issue/PR 响应质量未知

- Severity: low
- Evidence strength: source_linked
- Finding: issue_or_pr_quality=unknown。
- User impact: 用户无法判断遇到问题后是否有人维护。
- Suggested check: 抽样最近 issue/PR，判断是否长期无人处理。
- Guardrail action: issue/PR 响应未知时，必须提示维护风险。
- 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 · 发布节奏不明确

- Severity: low
- Evidence strength: source_linked
- Finding: release_recency=unknown。
- User impact: 安装命令和文档可能落后于代码，用户踩坑概率升高。
- Suggested check: 确认最近 release/tag 和 README 安装命令是否一致。
- Guardrail action: 发布节奏未知或过期时，安装说明必须标注可能漂移。
- 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

<!-- canonical_name: templatefoxpdf/mcp-server; human_manual_source: deepwiki_human_wiki -->
