{
  "canonical_name": "templatefoxpdf/mcp-server",
  "compilation_id": "pack_74c38cc35d51450f9513fe21fd47eb51",
  "created_at": "2026-05-22T15:18:18.990095+00:00",
  "created_by": "project-pack-compiler",
  "feedback": {
    "carrier_selection_notes": [
      "viable_asset_types=mcp_config, recipe, host_instruction, eval, preflight",
      "recommended_asset_types=mcp_config, recipe, host_instruction, eval, preflight"
    ],
    "evidence_delta": {
      "confirmed_claims": [
        "identity_anchor_present",
        "capability_and_host_targets_present",
        "install_path_declared_or_better"
      ],
      "missing_required_fields": [],
      "must_verify_forwarded": [
        "Run or inspect `npx @templatefox/mcp-server` in an isolated environment.",
        "Confirm the project exposes the claimed capability to at least one target host."
      ],
      "quickstart_execution_scope": "allowlisted_sandbox_smoke",
      "sandbox_command": "npx @templatefox/mcp-server",
      "sandbox_container_image": "node:22-slim",
      "sandbox_execution_backend": "docker",
      "sandbox_planner_decision": "llm_execute_isolated_install",
      "sandbox_validation_id": "sbx_32ef1729f00e462ab98927d25901432a"
    },
    "feedback_event_type": "project_pack_compilation_feedback",
    "learning_candidate_reasons": [],
    "template_gaps": []
  },
  "identity": {
    "canonical_id": "project_d2d503a56629255845637eff2649f963",
    "canonical_name": "templatefoxpdf/mcp-server",
    "homepage_url": null,
    "license": "unknown",
    "repo_url": "https://github.com/TemplateFoxPDF/mcp-server",
    "slug": "mcp-server",
    "source_packet_id": "phit_ee4e7d6cbac146e5ac844cd2d6fc8aed",
    "source_validation_id": "dval_1b1d97a0b5c040a48b42d3dd5dcaac8c"
  },
  "merchandising": {
    "best_for": "需要工具连接与集成能力，并使用 mcp_host的用户",
    "github_forks": null,
    "github_stars": null,
    "one_liner_en": "MCP server for TemplateFox PDF generation API - Generate PDFs from templates via AI assistants",
    "one_liner_zh": "MCP server for TemplateFox PDF generation API - Generate PDFs from templates via AI assistants",
    "primary_category": {
      "category_id": "tool-integrations",
      "confidence": "high",
      "name_en": "Tool Integrations",
      "name_zh": "工具连接与集成",
      "reason": "matched_keywords:mcp, api, server"
    },
    "target_user": "使用 mcp_host 等宿主 AI 的用户",
    "title_en": "mcp-server",
    "title_zh": "mcp-server 能力包",
    "visible_tags": [
      {
        "label_en": "MCP Tools",
        "label_zh": "MCP 工具",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "product_domain-mcp-tools",
        "type": "product_domain"
      },
      {
        "label_en": "Knowledge Base Q&A",
        "label_zh": "知识库问答",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "user_job-knowledge-base-q-a",
        "type": "user_job"
      },
      {
        "label_en": "Structured Data Extraction",
        "label_zh": "结构化数据提取",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "core_capability-structured-data-extraction",
        "type": "core_capability"
      },
      {
        "label_en": "Node-based Workflow",
        "label_zh": "节点式流程编排",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "workflow_pattern-node-based-workflow",
        "type": "workflow_pattern"
      },
      {
        "label_en": "Open Source Tool",
        "label_zh": "开源工具",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "selection_signal-open-source-tool",
        "type": "selection_signal"
      }
    ]
  },
  "packet_id": "phit_ee4e7d6cbac146e5ac844cd2d6fc8aed",
  "page_model": {
    "artifacts": {
      "artifact_slug": "mcp-server",
      "files": [
        "PROJECT_PACK.json",
        "QUICK_START.md",
        "PROMPT_PREVIEW.md",
        "HUMAN_MANUAL.md",
        "AI_CONTEXT_PACK.md",
        "BOUNDARY_RISK_CARD.md",
        "PITFALL_LOG.md",
        "REPO_INSPECTION.json",
        "REPO_INSPECTION.md",
        "CAPABILITY_CONTRACT.json",
        "EVIDENCE_INDEX.json",
        "CLAIM_GRAPH.json"
      ],
      "required_files": [
        "PROJECT_PACK.json",
        "QUICK_START.md",
        "PROMPT_PREVIEW.md",
        "HUMAN_MANUAL.md",
        "AI_CONTEXT_PACK.md",
        "BOUNDARY_RISK_CARD.md",
        "PITFALL_LOG.md",
        "REPO_INSPECTION.json"
      ]
    },
    "detail": {
      "capability_source": "Project Hit Packet + DownstreamValidationResult",
      "commands": [
        {
          "command": "npx @templatefox/mcp-server",
          "label": "Node.js / npx · 官方安装入口",
          "source": "https://registry.modelcontextprotocol.io/v0.1/servers/io.github.TemplateFoxPDF%2Fmcp-server/versions/1.9.7",
          "verified": true
        }
      ],
      "display_tags": [
        "MCP 工具",
        "知识库问答",
        "结构化数据提取",
        "节点式流程编排",
        "开源工具"
      ],
      "eyebrow": "工具连接与集成",
      "glance": [
        {
          "body": "判断自己是不是目标用户。",
          "label": "最适合谁",
          "value": "需要工具连接与集成能力，并使用 mcp_host的用户"
        },
        {
          "body": "先理解能力边界，再决定是否继续。",
          "label": "核心价值",
          "value": "MCP server for TemplateFox PDF generation API - Generate PDFs from templates via AI assistants"
        },
        {
          "body": "未完成验证前保持审慎。",
          "label": "继续前",
          "value": "publish to Doramagic.ai project surfaces"
        }
      ],
      "guardrail_source": "Boundary & Risk Card",
      "guardrails": [
        {
          "body": "Prompt Preview 只展示流程，不证明项目已安装或运行。",
          "label": "Check 1",
          "value": "不要把试用当真实运行"
        },
        {
          "body": "mcp_host",
          "label": "Check 2",
          "value": "确认宿主兼容"
        },
        {
          "body": "publish to Doramagic.ai project surfaces",
          "label": "Check 3",
          "value": "先隔离验证"
        }
      ],
      "mode": "mcp_config, recipe, host_instruction, eval, preflight",
      "pitfall_log": {
        "items": [
          {
            "body": "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…",
            "category": "安装坑",
            "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"
            ],
            "severity": "medium",
            "suggested_check": "Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。",
            "title": "社区讨论暴露的待验证问题：darkzodchi en X: \"Top MCP Servers That Turn Claude Into a Productivity Machine\" / X",
            "user_impact": "这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。"
          },
          {
            "body": "README/documentation is current enough for a first validation pass.",
            "category": "能力坑",
            "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."
            ],
            "severity": "medium",
            "suggested_check": "将假设转成下游验证清单。",
            "title": "能力判断依赖假设",
            "user_impact": "假设不成立时，用户拿不到承诺的能力。"
          },
          {
            "body": "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 ...",
            "category": "运行坑",
            "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"
            ],
            "severity": "medium",
            "suggested_check": "Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。",
            "title": "社区讨论暴露的待验证问题：Adding Github MCP to Claude Code Error : r/ClaudeAI - Reddit",
            "user_impact": "这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。"
          },
          {
            "body": "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 ...",
            "category": "运行坑",
            "evidence": [
              "social_signal:x | ssig_504e57203f64433a83bf7ec96631f94c | https://x.com/Hesamation/status/2035136966719582695 | you need somewhere between 1-10 Claude skills depending on what ..."
            ],
            "severity": "medium",
            "suggested_check": "Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。",
            "title": "社区讨论暴露的待验证问题：you need somewhere between 1-10 Claude skills depending on what ...",
            "user_impact": "这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。"
          },
          {
            "body": "未记录 last_activity_observed。",
            "category": "维护坑",
            "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"
            ],
            "severity": "medium",
            "suggested_check": "补 GitHub 最近 commit、release、issue/PR 响应信号。",
            "title": "维护活跃度未知",
            "user_impact": "新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。"
          },
          {
            "body": "no_demo",
            "category": "安全/权限坑",
            "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"
            ],
            "severity": "medium",
            "suggested_check": "进入安全/权限治理复核队列。",
            "title": "下游验证发现风险项",
            "user_impact": "下游已经要求复核，不能在页面中弱化。"
          },
          {
            "body": "no_demo",
            "category": "安全/权限坑",
            "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"
            ],
            "severity": "medium",
            "suggested_check": "把风险写入边界卡，并确认是否需要人工复核。",
            "title": "存在评分风险",
            "user_impact": "风险会影响是否适合普通用户安装。"
          },
          {
            "body": "issue_or_pr_quality=unknown。",
            "category": "维护坑",
            "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"
            ],
            "severity": "low",
            "suggested_check": "抽样最近 issue/PR，判断是否长期无人处理。",
            "title": "issue/PR 响应质量未知",
            "user_impact": "用户无法判断遇到问题后是否有人维护。"
          },
          {
            "body": "release_recency=unknown。",
            "category": "维护坑",
            "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"
            ],
            "severity": "low",
            "suggested_check": "确认最近 release/tag 和 README 安装命令是否一致。",
            "title": "发布节奏不明确",
            "user_impact": "安装命令和文档可能落后于代码，用户踩坑概率升高。"
          }
        ],
        "source": "ProjectPitfallLog + ProjectHitPacket + validation + community signals",
        "summary": "发现 9 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：安装坑 - 社区讨论暴露的待验证问题：darkzodchi en X: \"Top MCP Servers That Turn Claude Into a Productivity Machine\" / X。",
        "title": "踩坑日志"
      },
      "snapshot": {
        "contributors": null,
        "forks": null,
        "license": "unknown",
        "note": "站点快照，非实时质量证明；用于开工前背景判断。",
        "stars": null
      },
      "source_url": "https://github.com/TemplateFoxPDF/mcp-server",
      "steps": [
        {
          "body": "不安装项目，先体验能力节奏。",
          "code": "preview",
          "title": "先试 Prompt"
        },
        {
          "body": "理解输入、输出、失败模式和边界。",
          "code": "manual",
          "title": "读说明书"
        },
        {
          "body": "把上下文交给宿主 AI 继续工作。",
          "code": "context",
          "title": "带给 AI"
        },
        {
          "body": "进入主力环境前先完成安装入口与风险边界验证。",
          "code": "verify",
          "title": "沙箱验证"
        }
      ],
      "subtitle": "MCP server for TemplateFox PDF generation API - Generate PDFs from templates via AI assistants",
      "title": "mcp-server 能力包",
      "trial_prompt": "# mcp-server - Prompt Preview\n\n> Copy the prompt below into your AI host before installing anything.\n> Its purpose is to let you safely feel the project's workflow, not to claim the project has already run.\n\n## Copy this prompt\n\n```text\nYou are using an independent Doramagic capability pack for templatefoxpdf/mcp-server.\n\nProject:\n- Name: mcp-server\n- Repository: https://github.com/TemplateFoxPDF/mcp-server\n- Summary: MCP server for TemplateFox PDF generation API - Generate PDFs from templates via AI assistants\n- Host target: mcp_host\n\nGoal:\nHelp me evaluate this project for the following task without installing it yet: MCP server for TemplateFox PDF generation API - Generate PDFs from templates via AI assistants\n\nBefore taking action:\n1. Restate my task, success standard, and boundary.\n2. Identify whether the next step requires tools, browser access, network access, filesystem access, credentials, package installation, or host configuration.\n3. Use only the Doramagic Project Pack, the upstream repository, and the source-linked evidence listed below.\n4. If a real command, install step, API call, file write, or host integration is required, mark it as \"requires post-install verification\" and ask for approval first.\n5. If evidence is missing, say \"evidence is missing\" instead of filling the gap.\n\nPreviewable capabilities:\n- Capability 1: MCP server for TemplateFox PDF generation API - Generate PDFs from templates via AI assistants\n\nCapabilities that require post-install verification:\n- Capability 1: Use the source-backed project context to guide one small, checkable workflow step.\n\nCore service flow:\n1. page-introduction: Introduction. Produce one small intermediate artifact and wait for confirmation.\n2. page-project-structure: Project Structure. Produce one small intermediate artifact and wait for confirmation.\n3. page-transport-modes: Transport Modes. Produce one small intermediate artifact and wait for confirmation.\n4. page-pdf-generation-tools: PDF Generation Tools. Produce one small intermediate artifact and wait for confirmation.\n5. page-template-management-tools: Template Management Tools. Produce one small intermediate artifact and wait for confirmation.\n\nSource-backed evidence to keep in mind:\n- https://registry.modelcontextprotocol.io/v0.1/servers/io.github.TemplateFoxPDF%2Fmcp-server/versions/1.9.7\n- README.md\n- package.json\n- tsconfig.json\n- Dockerfile\n- src/index.ts\n- src/tools.ts\n\nFirst response rules:\n1. Start Step 1 only.\n2. Explain the one service action you will perform first.\n3. Ask exactly three questions about my target workflow, success standard, and sandbox boundary.\n4. Stop and wait for my answers.\n\nStep 1 follow-up protocol:\n- After I answer the first three questions, stay in Step 1.\n- Produce six parts only: clarified task, success standard, boundary conditions, two or three options, tradeoffs for each option, and one recommendation.\n- End by asking whether I confirm the recommendation.\n- Do not move to Step 2 until I explicitly confirm.\n\nConversation rules:\n- Advance one step at a time and wait for confirmation after each small artifact.\n- Write outputs as recommendations or planned checks, not as completed execution.\n- Do not claim tests passed, files changed, commands ran, APIs were called, or the project was installed.\n- If the user asks for execution, first provide the sandbox setup, expected output, rollback, and approval checkpoint.\n```\n",
      "voices": [
        {
          "body": "来源平台：github, x, reddit。github/github_release: v1.9.6（https://github.com/TemplateFoxPDF/mcp-server/releases/tag/v1.9.6）；github/github_release: v1.9.5（https://github.com/TemplateFoxPDF/mcp-server/releases/tag/v1.9.5）；github/github_release: v1.9.4（https://github.com/TemplateFoxPDF/mcp-server/releases/tag/v1.9.4）；github/github_release: v1.9.3（https://github.com/TemplateFoxPDF/mcp-server/releases/tag/v1.9.3）；x: you need somewhere between 1-10 Claude skills depending on what ...（https://x.com/Hesamation/status/2035136966719582695）；x: darkzodchi en X: \"Top MCP Servers That Turn Claude Into a Productivity M（https://x.com/zodchiii/status/2041804097628582294）；x: Madhav Singhal on X: \"anyone else using the zen mcp server with claude c（https://x.com/madhavsinghal_/status/1936604934184845529）；x: ミヤマ on X: \"Claude Codeなど、AIからイラレを直接操作できるMCPサーバーが！？ 👇\" / X（https://x.com/mmmiyama_D/status/2036575601566556241）；x: As melhores Skills do Claude Code Faltou alguma?（https://x.com/fabioricotta/status/2035357887438971171）；reddit: I Found a collection 300+ MCP servers! : r/ClaudeAI - Reddit（https://www.reddit.com/r/ClaudeAI/comments/1ju3ro6/i_found_a_collection_300_mcp_servers/）；x: me realizing that the only thing I had to do to completely fix Claude Co（https://x.com/kirillk_web3/status/2055099092745719890）；reddit: Adding Github MCP to Claude Code Error : r/ClaudeAI - Reddit（https://www.reddit.com/r/ClaudeAI/comments/1li0v90/adding_github_mcp_to_claude_code_error/）。这些是项目级外部声音，不作为单独质量证明。",
          "items": [
            {
              "kind": "github_release",
              "source": "github",
              "title": "v1.9.6",
              "url": "https://github.com/TemplateFoxPDF/mcp-server/releases/tag/v1.9.6"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "v1.9.5",
              "url": "https://github.com/TemplateFoxPDF/mcp-server/releases/tag/v1.9.5"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "v1.9.4",
              "url": "https://github.com/TemplateFoxPDF/mcp-server/releases/tag/v1.9.4"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "v1.9.3",
              "url": "https://github.com/TemplateFoxPDF/mcp-server/releases/tag/v1.9.3"
            },
            {
              "kind": "searxng_indexed",
              "source": "x",
              "title": "you need somewhere between 1-10 Claude skills depending on what ...",
              "url": "https://x.com/Hesamation/status/2035136966719582695"
            },
            {
              "kind": "searxng_indexed",
              "source": "x",
              "title": "darkzodchi en X: \"Top MCP Servers That Turn Claude Into a Productivity M",
              "url": "https://x.com/zodchiii/status/2041804097628582294"
            },
            {
              "kind": "searxng_indexed",
              "source": "x",
              "title": "Madhav Singhal on X: \"anyone else using the zen mcp server with claude c",
              "url": "https://x.com/madhavsinghal_/status/1936604934184845529"
            },
            {
              "kind": "searxng_indexed",
              "source": "x",
              "title": "ミヤマ on X: \"Claude Codeなど、AIからイラレを直接操作できるMCPサーバーが！？ 👇\" / X",
              "url": "https://x.com/mmmiyama_D/status/2036575601566556241"
            },
            {
              "kind": "searxng_indexed",
              "source": "x",
              "title": "As melhores Skills do Claude Code Faltou alguma?",
              "url": "https://x.com/fabioricotta/status/2035357887438971171"
            },
            {
              "kind": "searxng_indexed",
              "source": "reddit",
              "title": "I Found a collection 300+ MCP servers! : r/ClaudeAI - Reddit",
              "url": "https://www.reddit.com/r/ClaudeAI/comments/1ju3ro6/i_found_a_collection_300_mcp_servers/"
            },
            {
              "kind": "searxng_indexed",
              "source": "x",
              "title": "me realizing that the only thing I had to do to completely fix Claude Co",
              "url": "https://x.com/kirillk_web3/status/2055099092745719890"
            },
            {
              "kind": "searxng_indexed",
              "source": "reddit",
              "title": "Adding Github MCP to Claude Code Error : r/ClaudeAI - Reddit",
              "url": "https://www.reddit.com/r/ClaudeAI/comments/1li0v90/adding_github_mcp_to_claude_code_error/"
            }
          ],
          "status": "已收录 16 条来源",
          "title": "社区讨论"
        }
      ]
    },
    "homepage_card": {
      "category": "工具连接与集成",
      "desc": "MCP server for TemplateFox PDF generation API - Generate PDFs from templates via AI assistants",
      "effort": "安装已验证",
      "forks": null,
      "icon": "link",
      "name": "mcp-server 能力包",
      "risk": "可发布",
      "slug": "mcp-server",
      "stars": null,
      "tags": [
        "MCP 工具",
        "知识库问答",
        "结构化数据提取",
        "节点式流程编排",
        "开源工具"
      ],
      "thumb": "gray",
      "type": "MCP 配置"
    },
    "manual": {
      "markdown": "# https://github.com/TemplateFoxPDF/mcp-server Project Manual\n\nGenerated on: 2026-05-22 15:16:53 UTC\n\n## Table of Contents\n\n- [Introduction](#page-introduction)\n- [Project Structure](#page-project-structure)\n- [Transport Modes](#page-transport-modes)\n- [Server Initialization](#page-server-initialization)\n- [PDF Generation Tools](#page-pdf-generation-tools)\n- [Template Management Tools](#page-template-management-tools)\n- [Account Management Tools](#page-account-management-tools)\n- [API Client](#page-api-client)\n- [Installation and Setup](#page-installation)\n- [Docker Deployment](#page-docker-deployment)\n\n<a id='page-introduction'></a>\n\n## Introduction\n\n### Related Pages\n\nRelated topics: [Project Structure](#page-project-structure), [PDF Generation Tools](#page-pdf-generation-tools), [Installation and Setup](#page-installation)\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following source files were used to generate this page:\n\n- [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n- [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n- [src/tools.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n- [src/api-client.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n- [src/index.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n</details>\n\n# Introduction\n\nTemplateFox 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]()\n\n## Overview\n\nThe 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]()\n\n### Core Functionality\n\nThe server exposes eight primary tools that cover the complete PDF generation workflow:\n\n| Tool | Purpose |\n|------|---------|\n| `generate_pdf` | Synchronous PDF generation from templates |\n| `generate_pdf_async` | Asynchronous PDF generation with job queuing |\n| `get_pdf_job_status` | Poll status of async generation jobs |\n| `list_pdf_jobs` | List and filter async job history |\n| `list_templates` | Discover available PDF templates |\n| `get_template_fields` | Retrieve template variable definitions |\n| `get_account_info` | Check account credits and status |\n| `list_transactions` | View credit transaction history |\n\nSource: [README.md]()\n\n## Architecture\n\nThe server follows a modular architecture with clear separation of concerns across three main source files.\n\n### Component Overview\n\n```mermaid\ngraph TD\n    A[\"AI Assistant<br/>(Claude, Cursor, Windsurf)\"] --> B[\"MCP Client\"]\n    B --> C[\"TemplateFox MCP Server\"]\n    C --> D[\"API Client<br/>(api-client.ts)\"]\n    C --> E[\"Tools Registry<br/>(tools.ts)\"]\n    D --> F[\"TemplateFox API<br/>api.templatefox.com\"]\n    E --> D\n    \n    subgraph \"Transport Modes\"\n        G[\"StdioServerTransport<br/>(Local/CLI)\"]\n        H[\"StreamableHTTPServerTransport<br/>(HTTP/Cloud)\"]\n    end\n    \n    C --> G\n    C --> H\n```\n\n### File Structure\n\n| File | Responsibility |\n|------|----------------|\n| `src/index.ts` | Server initialization, transport configuration, HTTP middleware |\n| `src/tools.ts` | MCP tool definitions using Zod schemas for validation |\n| `src/api-client.ts` | HTTP request handling, API key management, AsyncLocalStorage context |\n\nSource: [src/index.ts:1-60](), [src/tools.ts:1-50](), [src/api-client.ts:1-35]()\n\n## Transport Modes\n\nThe server supports two distinct transport mechanisms, automatically selected based on environment configuration.\n\n### Standard I/O Mode (Default)\n\nThe 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]()\n\n```mermaid\ngraph LR\n    A[\"AI Assistant\"] -->|\"stdio\"| B[\"StdioServerTransport\"]\n    B --> C[\"McpServer Instance\"]\n    C --> D[\"Tool Handler\"]\n    D --> E[\"TemplateFox API\"]\n```\n\n**Activation:**\n```bash\nnpx -y @templatefox/mcp-server\n```\n\n### HTTP Mode (Cloud/Remote)\n\nThe StreamableHTTPServerTransport enables remote deployments and cloud hosting. This mode activates when the `PORT` environment variable is set. Source: [src/index.ts:21-33]()\n\n**Activation:**\n```bash\nPORT=8080 TEMPLATEFOX_API_KEY=sk_your_key node dist/index.js\n```\n\n**Remote Endpoint:**\n```\nhttps://mcp-server-599407781746.us-central1.run.app/mcp\n```\n\nSource: [README.md]()\n\n## API Key Management\n\nThe server implements a dual-layer API key resolution strategy to support both local and HTTP transport modes.\n\n```mermaid\ngraph TD\n    A[\"API Request\"] --> B{Transport Type}\n    B -->|HTTP| C[\"Extract from Headers\"]\n    B -->|Stdio| D[\"Read from Environment\"]\n    C --> E{\"Key Present?\"}\n    D --> E\n    E -->|Yes| F[\"AsyncLocalStorage Context\"]\n    E -->|No| G[\"Throw Error\"]\n    F --> H[\"API Client\"]\n    G --> I[\"401 Unauthorized\"]\n```\n\n### Key Resolution Priority\n\n1. **HTTP Mode**: Per-request API key from `Authorization: Bearer` or `x-api-key` header via AsyncLocalStorage\n2. **Stdio Mode**: Environment variable `TEMPLATEFOX_API_KEY`\n\nSource: [src/api-client.ts:14-28]()\n\n### AsyncLocalStorage Context\n\nThe 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]()\n\n```typescript\nconst apiKeyStore = new AsyncLocalStorage<string>();\n\nexport function runWithApiKey<T>(apiKey: string, fn: () => T): T {\n  return apiKeyStore.run(apiKey, fn);\n}\n```\n\n## Tool Registration\n\nTools are registered using the `@modelcontextprotocol/sdk` package with Zod schema validation for all input parameters. Source: [src/tools.ts:1-10]()\n\n### Tool Configuration Pattern\n\nEach tool follows a consistent registration pattern:\n\n```typescript\nserver.tool(\n  \"tool_name\",                    // Tool identifier\n  \"Description text\",            // Human-readable description\n  { /* Zod schema */ },          // Input validation\n  { /* Hints */ },               // Read/destructive hints\n  async (params) => { ... }      // Handler function\n);\n```\n\n### Tool Hints\n\n| Hint | Description |\n|------|-------------|\n| `readOnlyHint: true` | Read-only operation (GET requests) |\n| `destructiveHint: false` | Non-destructive operation |\n\nSource: [src/tools.ts:50-60]()\n\n## Server Configuration\n\n### Environment Variables\n\n| Variable | Required | Default | Description |\n|----------|----------|---------|-------------|\n| `TEMPLATEFOX_API_KEY` | Yes (Stdio) | - | API key starting with `sk_` |\n| `TEMPLATEFOX_BASE_URL` | No | `https://api.templatefox.com` | Override API base URL |\n| `PORT` | No | - | Enable HTTP mode when set |\n\nSource: [README.md](), [src/api-client.ts:6]()\n\n### HTTP Server Middleware\n\nWhen running in HTTP mode, the server configures Express with CORS and JSON parsing middleware:\n\n```typescript\nconst app = express();\napp.use(cors());\napp.use(express.json());\n```\n\n**Endpoints:**\n\n| Endpoint | Method | Purpose |\n|----------|--------|---------|\n| `/health` | GET | Health check with version info |\n| `/mcp` | POST | MCP request handling |\n| `/mcp` | GET/DELETE | Method not allowed (405) |\n\nSource: [src/index.ts:27-45]()\n\n## Package Metadata\n\n| Property | Value |\n|----------|-------|\n| **Package Name** | `@templatefox/mcp-server` |\n| **Version** | `1.10.1` |\n| **Node.js Requirement** | `>=18.0.0` |\n| **License** | MIT |\n| **MCP Name** | `io.github.TemplateFoxPDF/mcp-server` |\n\nSource: [package.json:1-25]()\n\n### Core Dependencies\n\n| Package | Version | Purpose |\n|---------|---------|---------|\n| `@modelcontextprotocol/sdk` | `^1.29.0` | MCP protocol implementation |\n| `express` | `^5.2.1` | HTTP server framework |\n| `cors` | `^2.8.6` | Cross-origin resource sharing |\n\nSource: [package.json:26-32]()\n\n## Quick Start Workflow\n\n```mermaid\ngraph TD\n    A[\"Configure MCP Client\"] --> B[\"Add to Claude Desktop config\"]\n    A --> C[\"Or use claude mcp add command\"]\n    B --> D[\"Set TEMPLATEFOX_API_KEY\"]\n    C --> D\n    D --> E[\"Ask AI to generate PDF\"]\n    E --> F[\"list_templates\"]\n    F --> G[\"get_template_fields\"]\n    G --> H[\"generate_pdf\"]\n    H --> I[\"Return download URL\"]\n```\n\nExample AI prompt:\n> \"List my PDF templates and generate an invoice using the Invoice Template with customer name 'John Doe' and amount 150.00\"\n\nSource: [README.md]()\n\n## Next Steps\n\nFor detailed information about specific features, refer to:\n\n- **Tool Reference**: Detailed documentation for each MCP tool\n- **API Client**: HTTP request handling and authentication\n- **Deployment**: Cloud Run and Docker deployment configurations\n\n---\n\n<a id='page-project-structure'></a>\n\n## Project Structure\n\n### Related Pages\n\nRelated topics: [Introduction](#page-introduction), [Server Initialization](#page-server-initialization), [API Client](#page-api-client)\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following source files were used to generate this page:\n\n- [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n- [src/index.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n- [src/tools.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n- [src/api-client.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n- [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n</details>\n\n# Project Structure\n\nThe 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.\n\n## Repository Overview\n\nThe 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.\n\n| Property | Value |\n|----------|-------|\n| **Package Name** | `@templatefox/mcp-server` |\n| **Version** | 1.10.1 |\n| **License** | MIT |\n| **Node.js Requirement** | >=18.0.0 |\n| **Module Type** | ESM (ECMAScript Modules) |\n| **MCP SDK Version** | ^1.29.0 |\n| Source: [package.json:1-18](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json) |\n\n## Directory Structure\n\n```\nmcp-server/\n├── src/\n│   ├── index.ts        # Main entry point with transport handling\n│   ├── tools.ts        # MCP tool definitions\n│   └── api-client.ts   # API communication layer\n├── dist/               # Compiled JavaScript output\n├── package.json        # Package configuration\n├── tsconfig.json        # TypeScript configuration\n├── Dockerfile           # Container deployment\n└── README.md            # Documentation\n```\n\n## Source Code Architecture\n\n### Core Components Overview\n\n```mermaid\ngraph TD\n    A[MCP Client<br/>Claude/Cursor] -->|JSON-RPC| B[Transport Layer]\n    B --> C{Mode Detection}\n    C -->|No PORT env| D[StdioServerTransport]\n    C -->|PORT defined| E[StreamableHTTPServerTransport]\n    D --> F[McpServer Instance]\n    E --> G[Express HTTP Server]\n    G --> F\n    F --> H[registerTools]\n    H --> I[API Client]\n    I --> J[TemplateFox API]\n    J -->|PDF/Response| I\n    I --> F\n    F --> B\n```\n\n### Entry Point (`src/index.ts`)\n\nThe main entry point handles dual-mode operation based on environment configuration:\n\n**Key Responsibilities:**\n- Initialize the McpServer instance with name and version\n- Detect transport mode via the `PORT` environment variable\n- Set up Express server with CORS for HTTP mode\n- Extract API keys from request headers for per-request authentication\n\n| Transport Mode | Trigger | Use Case |\n|----------------|---------|----------|\n| **Stdio** | No `PORT` variable | Local AI assistant integration |\n| **HTTP** | `PORT` defined | Cloud Run, remote deployments |\n\nSource: [src/index.ts:1-28](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n#### HTTP Transport Configuration\n\n```typescript\nconst port = process.env.PORT ? parseInt(process.env.PORT, 10) : undefined;\n\nif (port) {\n  // HTTP mode: Streamable HTTP transport\n  const app = express();\n  app.use(cors());\n  app.use(express.json());\n  // ... route handlers\n}\n```\n\nSource: [src/index.ts:24-32](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n#### API Key Extraction\n\nThe HTTP transport extracts API keys from incoming requests using two methods:\n\n| Header | Format | Priority |\n|--------|--------|----------|\n| `Authorization` | `Bearer sk_xxx` | Primary |\n| `x-api-key` | `sk_xxx` | Fallback |\n\nSource: [src/index.ts:47-53](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n### API Client (`src/api-client.ts`)\n\nThe API client module handles all communication with the TemplateFox API endpoint at `https://api.templatefox.com`.\n\n#### API Key Management Strategy\n\n```mermaid\ngraph TD\n    A[apiRequest called] --> B{AsyncLocalStorage<br/>has key?}\n    B -->|Yes| C[Return context key]\n    B -->|No| D{Environment<br/>TEMPLATEFOX_API_KEY?}\n    D -->|Yes| E[Return env key]\n    D -->|No| F[Throw Error]\n    C --> G[Make API Request]\n    E --> G\n    F --> H[Error: API key required]\n```\n\nThe client implements a two-tier API key resolution strategy:\n\n1. **Per-request context** via `AsyncLocalStorage` (HTTP transport mode)\n2. **Environment variable fallback** (`TEMPLATEFOX_API_KEY`) for stdio mode\n\nSource: [src/api-client.ts:1-31](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n\n#### Request Building\n\nThe `apiRequest` function constructs HTTP requests with the following components:\n\n| Component | Value |\n|-----------|-------|\n| **Base URL** | `TEMPLATEFOX_BASE_URL` or `https://api.templatefox.com` |\n| **Method** | GET or POST |\n| **Authentication** | `x-api-key` header |\n| **Content-Type** | `application/json` (for POST) |\n| **Accept** | `application/json` |\n\nSource: [src/api-client.ts:49-78](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n\n### MCP Tools (`src/tools.ts`)\n\nThe tools module defines all MCP tools exposed to AI assistants. Each tool corresponds to a TemplateFox API endpoint.\n\n#### Tool Categories\n\n| Category | Tools | Operations |\n|----------|-------|------------|\n| **PDF Generation** | `generate_pdf`, `generate_pdf_async` | Create PDFs synchronously or asynchronously |\n| **Job Management** | `get_pdf_job_status`, `list_pdf_jobs` | Monitor and list async jobs |\n| **Templates** | `list_templates`, `get_template_fields` | Discover available templates |\n| **Account** | `get_account_info`, `list_transactions` | View credits and history |\n\nSource: [src/tools.ts:1-200](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n#### Tool Definition Pattern\n\nEach MCP tool follows this schema:\n\n```typescript\nserver.tool(\n  \"tool_name\",                    // Tool identifier\n  \"Description for AI assistant\", // Human-readable description\n  { /* Zod schema parameters */}, // Input validation schema\n  { /* Hints */ },                // Read/destructive hints\n  async ({ params }) => {          // Handler function\n    const url = \"/v1/endpoint\";\n    const result = await apiRequest(\"METHOD\", url, body);\n    return {\n      content: [{ type: \"text\", text: JSON.stringify(result.data) }],\n      isError: !result.ok,\n    };\n  }\n);\n```\n\nSource: [src/tools.ts:7-22](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n#### Available Tools Reference\n\n| Tool | HTTP Method | Endpoint | Credits | Async Support |\n|------|-------------|----------|---------|---------------|\n| `generate_pdf` | POST | `/v1/pdf/create` | 1 | No |\n| `generate_pdf_async` | POST | `/v1/pdf/create-async` | 1 | Yes |\n| `get_pdf_job_status` | GET | `/v1/pdf/jobs/{job_id}` | 0 | - |\n| `list_pdf_jobs` | GET | `/v1/pdf/jobs` | 0 | - |\n| `list_templates` | GET | `/v1/templates` | 0 | - |\n| `get_template_fields` | GET | `/v1/templates/{id}/fields` | 0 | - |\n| `get_account_info` | GET | `/v1/account` | 0 | - |\n| `list_transactions` | GET | `/v1/account/transactions` | 0 | - |\n\nSource: [src/tools.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n## Build Configuration\n\n### Package Scripts\n\n| Script | Command | Purpose |\n|--------|---------|---------|\n| `build` | `tsc` | Compile TypeScript to JavaScript |\n| `start` | `node dist/index.js` | Run the compiled server |\n\nSource: [package.json:12-15](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n\n### Dependencies\n\n#### Production Dependencies\n\n| Package | Version | Purpose |\n|---------|---------|---------|\n| `@modelcontextprotocol/sdk` | ^1.29.0 | MCP protocol implementation |\n| `express` | ^5.2.1 | HTTP server framework |\n| `cors` | ^2.8.6 | Cross-origin resource sharing |\n\nSource: [package.json:16-20](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n\n#### Development Dependencies\n\n| Package | Version | Purpose |\n|---------|---------|---------|\n| `typescript` | ^5.8.0 | TypeScript compiler |\n| `@types/node` | ^22.0.0 | Node.js type definitions |\n| `@types/express` | ^5.0.0 | Express type definitions |\n| `@types/cors` | ^2.8.0 | CORS type definitions |\n\nSource: [package.json:21-25](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n\n### Binary Configuration\n\nThe package exposes a CLI binary for global installation:\n\n```json\n{\n  \"bin\": {\n    \"templatefox-mcp-server\": \"./dist/index.js\"\n  }\n}\n```\n\nSource: [package.json:9-11](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n\n## Deployment Modes\n\n### Stdio Mode (Local)\n\nDefault mode for AI assistant integration via npx:\n\n```bash\nnpx -y @templatefox/mcp-server\n```\n\nRequires `TEMPLATEFOX_API_KEY` environment variable.\n\nSource: [README.md:15-24](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n### HTTP Mode (Cloud)\n\nEnabled by setting the `PORT` environment variable:\n\n```bash\nPORT=8080 TEMPLATEFOX_API_KEY=sk_your_key node dist/index.js\n```\n\n| Endpoint | Method | Purpose |\n|----------|--------|---------|\n| `/health` | GET | Health check |\n| `/mcp` | POST | MCP request handler |\n\nSource: [src/index.ts:35-39](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n### Docker Deployment\n\nThe project includes Dockerfile support for containerized deployments:\n\n```bash\ndocker build -t templatefox-mcp .\ndocker run -p 8080:8080 templatefox-mcp\n```\n\nSource: [README.md:66-70](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n## Data Flow Architecture\n\n### Synchronous PDF Generation\n\n```mermaid\nsequenceDiagram\n    participant AI as AI Assistant\n    participant MCP as MCP Server\n    participant API as TemplateFox API\n    AI->>MCP: generate_pdf(template_id, data)\n    MCP->>MCP: apiRequest(POST, /v1/pdf/create)\n    MCP->>API: HTTP POST with JSON body\n    API->>API: Generate PDF\n    API-->>MCP: PDF URL or binary\n    MCP-->>AI: JSON-RPC response\n```\n\n### Asynchronous PDF Generation\n\n```mermaid\nsequenceDiagram\n    participant AI as AI Assistant\n    participant MCP as MCP Server\n    participant API as TemplateFox API\n    participant Webhook as Webhook URL\n    AI->>MCP: generate_pdf_async(template_id, data, webhook_url)\n    MCP->>MCP: apiRequest(POST, /v1/pdf/create-async)\n    MCP->>API: HTTP POST\n    API-->>MCP: { job_id, status: \"pending\" }\n    MCP-->>AI: job_id\n    loop Poll or Webhook\n        API->>Webhook: POST when completed\n        alt Polling Mode\n            AI->>MCP: get_pdf_job_status(job_id)\n            MCP-->>AI: { status, pdf_url }\n        end\n    end\n```\n\n## Configuration Reference\n\n### Environment Variables\n\n| Variable | Required | Default | Description |\n|----------|----------|---------|-------------|\n| `TEMPLATEFOX_API_KEY` | Yes (stdio) / No (HTTP) | - | API key starting with `sk_` |\n| `TEMPLATEFOX_BASE_URL` | No | `https://api.templatefox.com` | Override API base URL |\n| `PORT` | No | undefined | Enable HTTP mode on specified port |\n\nSource: [README.md:42-47](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n## Workflow Example\n\nA typical AI-assisted PDF generation workflow:\n\n```mermaid\ngraph TD\n    A[User Request] --> B[list_templates]\n    B --> C[Choose Template]\n    C --> D[get_template_fields]\n    D --> E[Prepare Data]\n    E --> F{Size/Complexity}\n    F -->|Small Doc| G[generate_pdf]\n    F -->|Large Doc| H[generate_pdf_async]\n    H --> I[Poll get_pdf_job_status]\n    I -->|Not Ready| I\n    I -->|Ready| J[Return PDF URL]\n    G --> J\n```\n\nSource: [README.md:71-79](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n## Keywords and Metadata\n\nThe package includes comprehensive metadata for discoverability:\n\n```json\n{\n  \"keywords\": [\n    \"mcp\",\n    \"mcp-server\", \n    \"model-context-protocol\",\n    \"pdf\",\n    \"templatefox\",\n    \"pdf-generation\",\n    \"ai\",\n    \"claude\"\n  ],\n  \"mcpName\": \"io.github.TemplateFoxPDF/mcp-server\"\n}\n```\n\nSource: [package.json:26-34](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n\n---\n\n<a id='page-transport-modes'></a>\n\n## Transport Modes\n\n### Related Pages\n\nRelated topics: [Server Initialization](#page-server-initialization), [Installation and Setup](#page-installation), [Docker Deployment](#page-docker-deployment)\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following source files were used to generate this page:\n\n- [src/index.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n- [src/api-client.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n- [src/tools.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n- [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n- [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n</details>\n\n# Transport Modes\n\nThe 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.\n\n## Overview\n\nThe server implements the Model Context Protocol (MCP) and can operate in two primary transport configurations:\n\n| Transport Mode | Use Case | Deployment | Default |\n|---------------|----------|------------|---------|\n| **Stdio** | Local development, desktop AI assistants | Same machine as client | Yes |\n| **Streamable HTTP** | Remote/cloud deployments, web services | Separate server | No (when PORT is set) |\n\nSource: [src/index.ts:1-50](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[MCP Client] -->|Transport Choice| B\n    B{Transport Mode?}\n    B -->|stdio| C[StdioServerTransport]\n    B -->|http| D[StreamableHTTPServerTransport]\n    C --> E[Local Process Communication]\n    D --> F[Express.js HTTP Server]\n    F --> G[/health Endpoint]\n    F --> H[/mcp Endpoint]\n    E --> I[McpServer Instance]\n    F --> I\n```\n\n## Stdio Transport Mode\n\nStdio (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.\n\n### Configuration\n\nStdio mode requires no additional configuration beyond the essential environment variable:\n\n```bash\nTEMPLATEFOX_API_KEY=sk_your_api_key_here npx -y @templatefox/mcp-server\n```\n\nOr with a global installation:\n\n```bash\ntemplatefox-mcp-server\n```\n\n### How It Works\n\n1. 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)\n\n2. A `StdioServerTransport` is created to handle stdio communication. Source: [src/index.ts:30](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n3. 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)\n\n### API Key Handling in Stdio Mode\n\nIn 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.\n\nThe `getApiKey()` function in `api-client.ts` implements a two-tier lookup:\n\n```typescript\nfunction getApiKey(): string {\n  // 1. Per-request key from HTTP transport (AsyncLocalStorage)\n  const contextKey = apiKeyStore.getStore();\n  if (contextKey) return contextKey;\n\n  // 2. Environment variable (stdio mode)\n  const key = process.env.TEMPLATEFOX_API_KEY;\n  if (!key) {\n    throw new Error(\n      \"TEMPLATEFOX_API_KEY is required. \" +\n      \"Set it as an environment variable or pass it via the Authorization header. \" +\n      \"Get your API key at https://app.templatefox.com/dashboard/api-keys\"\n    );\n  }\n  return key;\n}\n```\n\nSource: [src/api-client.ts:44-60](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n\n## Streamable HTTP Transport Mode\n\nHTTP 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.\n\n### Enabling HTTP Mode\n\nHTTP mode is activated by setting the `PORT` environment variable:\n\n```bash\nPORT=8080 TEMPLATEFOX_API_KEY=sk_your_key node dist/index.js\n```\n\nSource: [src/index.ts:34](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n### Express.js Server Setup\n\nThe HTTP transport relies on Express.js for request handling:\n\n```typescript\nconst express = (await import(\"express\")).default;\nconst cors = (await import(\"cors\")).default;\n\nconst app = express();\napp.use(cors());\napp.use(express.json());\n```\n\nSource: [src/index.ts:36-40](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n### Endpoints\n\n| Endpoint | Method | Purpose |\n|----------|--------|---------|\n| `/health` | GET | Health check for monitoring |\n| `/mcp` | POST | MCP request handling |\n\nSource: [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)\n\n### Health Check Endpoint\n\n```typescript\napp.get(\"/health\", (_req, res) => {\n  res.json({ status: \"ok\", version: SERVER_VERSION });\n});\n```\n\nSource: [src/index.ts:42-44](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n### MCP Request Handling\n\nThe `/mcp` POST endpoint extracts the API key from request headers, creates a new server instance, and routes the request through the streamable HTTP transport:\n\n```typescript\napp.post(\"/mcp\", async (req, res) => {\n  const authHeader = req.headers.authorization;\n  const apiKey = authHeader?.startsWith(\"Bearer \")\n    ? authHeader.slice(7)\n    : (req.headers[\"x-api-key\"] as string | undefined);\n```\n\nSource: [src/index.ts:70-75](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n### API Key Extraction in HTTP Mode\n\nHTTP transport supports two header formats for API key authentication:\n\n| Header Format | Example |\n|--------------|---------|\n| `Authorization: Bearer <key>` | `Authorization: Bearer sk_your_api_key_here` |\n| `x-api-key: <key>` | `x-api-key: sk_your_api_key_here` |\n\nSource: [src/index.ts:70-75](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n### Per-Request API Key Handling\n\nHTTP mode uses `AsyncLocalStorage` to maintain per-request API key context:\n\n```typescript\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nconst apiKeyStore = new AsyncLocalStorage<string>();\n\nexport function runWithApiKey<T>(apiKey: string, fn: () => T): T {\n  return apiKeyStore.run(apiKey, fn);\n}\n```\n\nSource: [src/api-client.ts:11-17](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n\nThis 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.\n\n### Session Management\n\nThe HTTP transport is configured with stateless request handling:\n\n```typescript\nconst transport = new StreamableHTTPServerTransport({\n  sessionIdGenerator: undefined,\n});\n```\n\nSource: [src/index.ts:80-82](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\nSetting `sessionIdGenerator` to `undefined` disables session tracking, making each request independent.\n\n### Error Handling\n\nHTTP mode includes comprehensive error responses:\n\n```typescript\n// 401 Unauthorized - Missing API key\nres.status(401).json({\n  jsonrpc: \"2.0\",\n  error: {\n    code: -32001,\n    message: \"API key required. Pass it via Authorization: Bearer <key> or x-api-key header.\",\n  },\n  id: null,\n});\n\n// 405 Method Not Allowed\nres.status(405).json({\n  jsonrpc: \"2.0\",\n  error: { code: -32000, message: \"Method not allowed. Use POST for MCP requests.\" },\n  id: null,\n});\n\n// 500 Internal Server Error\nres.status(500).json({\n  jsonrpc: \"2.0\",\n  error: { code: -32603, message: \"Internal server error\" },\n  id: null,\n});\n```\n\nSource: [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)\n\n### Method Restriction\n\nThe server explicitly blocks inappropriate HTTP methods on the MCP endpoint:\n\n```typescript\napp.get(\"/mcp\", (_req, res) => {\n  res.status(405).json({...});\n});\n\napp.delete(\"/mcp\", (_req, res) => {\n  res.status(405).json({...});\n});\n```\n\nSource: [src/index.ts:90-99](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n## Deployment Options\n\n### Docker Deployment\n\nFor containerized HTTP deployments:\n\n```bash\ndocker build -t templatefox-mcp .\ndocker run -p 8080:8080 templatefox-mcp\n```\n\nSource: [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n### Cloud Run Deployment\n\nThe server is pre-deployed and accessible at:\n\n```\nhttps://mcp-server-599407781746.us-central1.run.app/mcp\n```\n\nSource: [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n### Claude Desktop Configuration\n\n```json\n{\n  \"mcpServers\": {\n    \"templatefox\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@templatefox/mcp-server\"],\n      \"env\": {\n        \"TEMPLATEFOX_API_KEY\": \"sk_your_api_key_here\"\n      }\n    }\n  }\n}\n```\n\nSource: [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n### Claude Code Configuration\n\n```bash\nclaude mcp add templatefox -- npx -y @templatefox/mcp-server\n```\n\nSource: [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n## Environment Variables\n\n| Variable | Required | Default | Description |\n|----------|----------|---------|-------------|\n| `TEMPLATEFOX_API_KEY` | Yes | - | API key (starts with `sk_`) |\n| `TEMPLATEFOX_BASE_URL` | No | `https://api.templatefox.com` | Override API base URL |\n| `PORT` | No | - | Enables HTTP mode when set |\n\nSource: [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)\n\n## Dependencies\n\nThe transport implementation relies on these packages:\n\n| Package | Version | Purpose |\n|---------|---------|---------|\n| `@modelcontextprotocol/sdk` | ^1.29.0 | MCP protocol and transport classes |\n| `express` | ^5.2.1 | HTTP server framework |\n| `cors` | ^2.8.6 | Cross-origin resource sharing |\n\nSource: [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n\n## Comparison: Stdio vs HTTP\n\n| Aspect | Stdio | Streamable HTTP |\n|--------|-------|-----------------|\n| **Startup** | Immediate | Requires PORT variable |\n| **Connection** | Process-based | TCP/HTTP |\n| **API Key Source** | Environment variable | Per-request header |\n| **Scalability** | Single client | Multiple clients |\n| **Use Case** | Desktop integrations | Cloud deployments |\n| **Session Support** | Native (process) | Stateless (no sessions) |\n| **AsyncLocalStorage** | Not used | Used for per-request context |\n\n## Request Flow Comparison\n\n```mermaid\ngraph LR\n    subgraph \"Stdio Mode\"\n        A1[Stdin Request] --> B1[StdioServerTransport]\n        B1 --> C1[McpServer]\n        C1 --> D1[Stdout Response]\n    end\n    \n    subgraph \"HTTP Mode\"\n        A2[HTTP POST] --> B2[Express App]\n        B2 --> C2[StreamableHTTPServerTransport]\n        C2 --> D2[McpServer]\n        D2 --> E2[HTTP Response]\n    end\n```\n\n## Tool Registration\n\nRegardless of transport mode, all tools are registered identically:\n\n```typescript\nexport function registerTools(server: McpServer): void {\n  // Tools are registered once at server creation\n  server.tool(\"generate_pdf\", {...});\n  server.tool(\"generate_pdf_async\", {...});\n  server.tool(\"get_pdf_job_status\", {...});\n  server.tool(\"list_pdf_jobs\", {...});\n  server.tool(\"list_templates\", {...});\n  server.tool(\"get_template_fields\", {...});\n  server.tool(\"get_account_info\", {...});\n  server.tool(\"list_transactions\", {...});\n}\n```\n\nSource: [src/tools.ts:3-20](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n---\n\n<a id='page-server-initialization'></a>\n\n## Server Initialization\n\n### Related Pages\n\nRelated topics: [Transport Modes](#page-transport-modes), [PDF Generation Tools](#page-pdf-generation-tools)\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following source files were used to generate this page:\n\n- [src/index.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n- [src/tools.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n- [src/api-client.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n- [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n- [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n</details>\n\n# Server Initialization\n\n## Overview\n\nThe 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.\n\nSource: [src/index.ts:1-5](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n```typescript\n#!/usr/bin/env node\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { StreamableHTTPServerTransport } from \"@modelcontextprotocol/sdk/server/streamableHttp.js\";\nimport { registerTools } from \"./tools.js\";\nimport { runWithApiKey } from \"./api-client.js\";\n```\n\n## Transport Modes\n\nThe server supports two distinct transport mechanisms determined by environment configuration.\n\n| Mode | Trigger | Use Case |\n|------|---------|----------|\n| **Stdio** | No `PORT` env var | Local CLI usage via npx, Claude Desktop |\n| **HTTP** | `PORT` env var set | Remote/cloud deployment, self-hosted |\n\nSource: [src/index.ts:25-26](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n```typescript\nconst port = process.env.PORT ? parseInt(process.env.PORT, 10) : undefined;\n```\n\n### Stdio Transport Mode\n\nWhen running without a `PORT` environment variable, the server uses stdio (standard input/output) transport, which is the default mode for local AI assistant integration.\n\nSource: [src/index.ts:54-56](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n```typescript\n// stdio mode: default for npx / local usage\nconst server = createServer();\nconst transport = new StdioServerTransport();\nawait server.connect(transport);\n```\n\n### HTTP Transport Mode\n\nWhen `PORT` is defined, the server launches an Express.js application with CORS support and Streamable HTTP transport for remote deployments.\n\nSource: [src/index.ts:28-31](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n```typescript\n// HTTP mode: Streamable HTTP transport (stateless, for Cloud Run / remote)\nconst express = (await import(\"express\")).default;\nconst cors = (await import(\"cors\")).default;\n\nconst app = express();\napp.use(cors());\napp.use(express.json());\n```\n\n## Server Creation Flow\n\nThe `createServer()` function initializes the MCP server with version metadata and registers all available tools.\n\n```mermaid\ngraph TD\n    A[Start] --> B[Check PORT Environment Variable]\n    B -->|PORT defined| C[HTTP Mode Setup]\n    B -->|No PORT| D[Stdio Mode Setup]\n    C --> E[Create Express App]\n    E --> F[Configure CORS & JSON middleware]\n    F --> G[Setup Health Endpoint /mcp]\n    G --> H[Start Listening]\n    D --> I[createServer]\n    I --> J[Register Tools via registerTools]\n    J --> K[new McpServer]\n    K --> L[new StdioServerTransport]\n    L --> M[Connect and Await Requests]\n```\n\n### Server Instance Creation\n\nSource: [src/index.ts:10-18](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n```typescript\nfunction createServer(): McpServer {\n  const server = new McpServer({\n    name: SERVER_NAME,\n    version: SERVER_VERSION,\n  });\n  registerTools(server);\n  return server;\n}\n```\n\nThe server configuration constants are defined as:\n\n| Constant | Value | Purpose |\n|----------|-------|---------|\n| `SERVER_NAME` | `\"templatefox\"` | Server identifier for MCP protocol |\n| `SERVER_VERSION` | `\"1.8.2\"` | Semantic version of the server |\n\nSource: [src/index.ts:6-8](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n## HTTP Server Endpoints\n\nThe HTTP transport mode exposes two endpoints:\n\n### Health Check Endpoint\n\nSource: [src/index.ts:33-36](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n```typescript\napp.get(\"/health\", (_req, res) => {\n  res.json({ status: \"ok\", version: SERVER_VERSION });\n});\n```\n\n### MCP Request Endpoint\n\nSource: [src/index.ts:38-68](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n```typescript\napp.post(\"/mcp\", async (req, res) => {\n  // Extract API key from Authorization header or x-api-key\n  const authHeader = req.headers.authorization;\n  const apiKey = authHeader?.startsWith(\"Bearer \")\n    ? authHeader.slice(7)\n    : (req.headers[\"x-api-key\"] as string | undefined);\n\n  if (!apiKey) {\n    res.status(401).json({\n      jsonrpc: \"2.0\",\n      error: {\n        code: -32001,\n        message: \"API key required. Pass it via Authorization: Bearer <key> or x-api-key header.\",\n      },\n      id: null,\n    });\n    return;\n  }\n  // ... server initialization continues\n});\n```\n\n### Error Handling Endpoints\n\nThe server returns 405 Method Not Allowed for incorrect HTTP methods:\n\n```typescript\napp.get(\"/mcp\", (_req, res) => {\n  res.status(405).json({\n    jsonrpc: \"2.0\",\n    error: { code: -32000, message: \"Method not allowed. Use POST for MCP requests.\" },\n    id: null,\n  });\n});\n\napp.delete(\"/mcp\", (_req, res) => {\n  res.status(405).json({\n    jsonrpc: \"2.0\",\n    error: { code: -32000, message: \"Method not allowed. Sessions are not supported.\" },\n    id: null,\n  });\n});\n```\n\nSource: [src/index.ts:70-82](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n## API Key Handling\n\nThe server implements a multi-tier API key resolution strategy:\n\n```mermaid\ngraph LR\n    A[API Key Request] --> B{HTTP Transport?}\n    B -->|Yes| C[Extract from Header]\n    B -->|No| D{Check Environment}\n    C --> E[AsyncLocalStorage Context]\n    D -->|Found| F[Use TEMPLATEFOX_API_KEY]\n    D -->|Not Found| G[Throw Error]\n    E --> H[API Request with Key]\n    F --> H\n```\n\n### Key Resolution Priority\n\nSource: [src/api-client.ts:28-43](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n\n```typescript\nfunction getApiKey(): string {\n  // 1. Per-request key from HTTP transport (AsyncLocalStorage)\n  const contextKey = apiKeyStore.getStore();\n  if (contextKey) return contextKey;\n\n  // 2. Environment variable (stdio mode)\n  const key = process.env.TEMPLATEFOX_API_KEY;\n  if (!key) {\n    throw new Error(\n      \"TEMPLATEFOX_API_KEY is required. \" +\n      \"Set it as an environment variable or pass it via the Authorization header. \" +\n      \"Get your API key at https://app.templatefox.com/dashboard/api-keys\"\n    );\n  }\n  return key;\n}\n```\n\n### HTTP Transport Key Injection\n\nFor HTTP mode, the API key is extracted from request headers and stored in AsyncLocalStorage context:\n\nSource: [src/index.ts:40-43](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n```typescript\nconst authHeader = req.headers.authorization;\nconst apiKey = authHeader?.startsWith(\"Bearer \")\n  ? authHeader.slice(7)\n  : (req.headers[\"x-api-key\"] as string | undefined);\n```\n\nThe key is then passed to the request handler:\n\nSource: [src/index.ts:53-58](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n```typescript\nconst server = createServer();\nconst transport = new StreamableHTTPServerTransport({\n  sessionIdGenerator: undefined,\n});\nawait server.connect(transport);\nawait runWithApiKey(apiKey, () => transport.handleRequest(req, res, req.body));\n```\n\n### AsyncLocalStorage Context\n\nSource: [src/api-client.ts:20-26](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n\n```typescript\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nconst apiKeyStore = new AsyncLocalStorage<string>();\n\n/**\n * Run a function with a specific API key in context.\n * Used by HTTP transport to pass per-request API keys.\n */\nexport function runWithApiKey<T>(apiKey: string, fn: () => T): T {\n  return apiKeyStore.run(apiKey, fn);\n}\n```\n\n## Tool Registration\n\nAll MCP tools are registered during server initialization via the `registerTools()` function.\n\nSource: [src/tools.ts:4-7](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n```typescript\nexport function registerTools(server: McpServer): void {\n  // Tool registrations...\n}\n```\n\n### Available Tools\n\n| Tool | Description | Credits | Read-Only |\n|------|-------------|---------|-----------|\n| `generate_pdf` | Generate PDF from template | 1 | No |\n| `generate_pdf_async` | Queue async PDF generation | 1 | No |\n| `get_pdf_job_status` | Check async job status | - | Yes |\n| `list_pdf_jobs` | List async jobs | - | Yes |\n| `list_templates` | List available templates | - | Yes |\n| `get_template_fields` | Get template field definitions | - | Yes |\n| `get_account_info` | Get account and credit info | - | Yes |\n| `list_transactions` | View credit transaction history | - | Yes |\n\nSource: [src/tools.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n## Configuration Options\n\n### Environment Variables\n\n| Variable | Required | Default | Description |\n|----------|----------|---------|-------------|\n| `TEMPLATEFOX_API_KEY` | Yes (Stdio) / Via Header (HTTP) | - | API key starting with `sk_` |\n| `TEMPLATEFOX_BASE_URL` | No | `https://api.templatefox.com` | Override API base URL |\n| `PORT` | No | - | Enable HTTP mode on specified port |\n\nSource: [src/api-client.ts:15](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n\n### Build and Runtime Scripts\n\nSource: [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n\n| Script | Command | Purpose |\n|--------|---------|---------|\n| `build` | `tsc` | Compile TypeScript to JavaScript |\n| `start` | `node dist/index.js` | Run the compiled server |\n\n### Server Binaries\n\n```json\n{\n  \"bin\": {\n    \"templatefox-mcp-server\": \"./dist/index.js\"\n  }\n}\n```\n\n## Startup Sequence\n\n```mermaid\nsequenceDiagram\n    participant CLI as CLI/npm\n    participant Server as MCP Server\n    participant MCP as MCP SDK\n    participant Express as Express App\n\n    CLI->>Server: node dist/index.js\n    Server->>Server: Check PORT env var\n    alt Stdio Mode\n        Server->>MCP: createServer()\n        MCP->>Server: McpServer instance\n        Server->>MCP: registerTools()\n        Server->>MCP: new StdioServerTransport()\n        Server->>MCP: connect(transport)\n        Note over Server,MCP: Await stdio requests\n    else HTTP Mode\n        Server->>Express: new Express()\n        Express->>Server: app configured\n        Server->>Server: app.listen(port)\n        Note over Server,Express: /health, /mcp endpoints ready\n    end\n```\n\n## Error Handling\n\n### HTTP Mode Error Handler\n\nSource: [src/index.ts:59-67](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n```typescript\n} catch (error) {\n  if (!res.headersSent) {\n    res.status(500).json({\n      jsonrpc: \"2.0\",\n      error: { code: -32603, message: \"Internal server error\" },\n      id: null,\n    });\n  }\n}\n```\n\n### Session Cleanup\n\nSource: [src/index.ts:55-57](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n```typescript\nres.on(\"close\", () => {\n  transport.close();\n  server.close();\n});\n```\n\n## Version Information\n\nThe server reports its version through:\n\n1. **HTTP Health Endpoint**: Returns `{ status: \"ok\", version: SERVER_VERSION }`\n2. **Package Version**: `1.10.1` in package.json\n3. **Runtime Version**: `1.8.2` defined as `SERVER_VERSION` constant\n\nSource: [package.json:4](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\nSource: [src/index.ts:8](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n## Dependencies\n\nThe server initialization relies on these core dependencies:\n\n| Package | Version | Purpose |\n|---------|---------|---------|\n| `@modelcontextprotocol/sdk` | `^1.29.0` | MCP protocol implementation |\n| `express` | `^5.2.1` | HTTP server framework |\n| `cors` | `^2.8.6` | Cross-origin resource sharing |\n| `typescript` | `^5.8.0` | TypeScript compilation |\n| `@types/node` | `^22.0.0` | Node.js type definitions |\n\nSource: [package.json:24-35](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n\n---\n\n<a id='page-pdf-generation-tools'></a>\n\n## PDF Generation Tools\n\n### Related Pages\n\nRelated topics: [Template Management Tools](#page-template-management-tools), [Account Management Tools](#page-account-management-tools), [API Client](#page-api-client)\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following source files were used to generate this page:\n\n- [src/tools.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n- [src/api-client.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n- [src/index.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n- [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n- [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n</details>\n\n# PDF Generation Tools\n\nThe 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.\n\n## Architecture Overview\n\nThe 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:\n\n```mermaid\ngraph TD\n    A[\"AI Assistant<br/>(Claude, Cursor, Windsurf)\"] --> B[\"MCP SDK<br/>StdioServerTransport / StreamableHTTPServerTransport\"]\n    B --> C[\"MCP Server (index.ts)\"]\n    C --> D[\"Tool Registry (tools.ts)\"]\n    D --> E[\"API Client (api-client.ts)\"]\n    E --> F[\"TemplateFox API<br/>https://api.templatefox.com\"]\n    \n    style A fill:#e1f5fe\n    style F fill:#fff3e0\n    style D fill:#f3e5f5\n```\n\nThe server supports two transport modes:\n- **Stdio Transport**: Default mode for local/cli usage via `npx`\n- **Streamable HTTP Transport**: For cloud deployments and remote access\n\nSource: [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)\n\n## Tool Registration\n\nAll 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.\n\n```mermaid\ngraph LR\n    A[\"registerTools(server)\"] --> B[\"generate_pdf\"]\n    A --> C[\"generate_pdf_async\"]\n    A --> D[\"get_pdf_job_status\"]\n    A --> C --> D\n    A --> E[\"list_pdf_jobs\"]\n    A --> F[\"list_templates\"]\n    A --> G[\"get_template_fields\"]\n    A --> H[\"get_account_info\"]\n    A --> I[\"list_transactions\"]\n```\n\nSource: [src/tools.ts:1-10](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n## Core PDF Generation Tools\n\n### generate_pdf\n\nThe `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.\n\n**Tool Name:** `generate_pdf`  \n**API Endpoint:** `POST /v1/pdf/create`  \n**Cost:** 1 credit per generation  \n**Source:** [src/tools.ts:20-60](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n#### Input Parameters\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `template_id` | string | Yes | Template short ID (12 characters) |\n| `data` | Record<string, unknown> | Yes | Key-value data to render in the template. Keys must match template variables. |\n| `export_type` | enum | No | Export format: `url` (upload to CDN, return URL) or `binary` (return raw PDF bytes) |\n| `expiration` | number | No | URL expiration in seconds (60-604800, i.e., 1 min to 7 days). Only applies to `url` export type. |\n| `filename` | string | No | Custom filename for the PDF (without .pdf extension). Defaults to 'document'. |\n| `store_s3` | boolean | No | Upload to configured S3 bucket instead of CDN |\n| `s3_filepath` | string | No | Custom path prefix in S3 bucket |\n| `s3_bucket` | string | No | Override the default S3 bucket configured in S3 integration |\n| `pdf_variant` | enum | No | Standards-compliant PDF variant: `pdf/a-1b`, `pdf/a-2b`, or `pdf/a-3b` |\n| `version` | string | No | Optional version tag (e.g., `prod`) or version number (e.g., `3`). Uses current draft if omitted. |\n\n#### PDF/A Variants\n\nThe tool supports generating PDF/A variants for archival and compliance purposes:\n\n| Variant | Use Case |\n|---------|----------|\n| `pdf/a-1b` | Basic archival compliance |\n| `pdf/a-2b` | Most common for archival compliance |\n| `pdf/a-3b` | Required for documents with file attachments (e.g., Factur-X, ZUGFeRD invoices) |\n\n#### Hints\n\n| Hint | Value | Description |\n|------|-------|-------------|\n| `destructiveHint` | false | Indicates this tool does not delete data |\n\nSource: [src/tools.ts:20-60](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n### generate_pdf_async\n\nThe `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.\n\n**Tool Name:** `generate_pdf_async`  \n**API Endpoint:** `POST /v1/pdf/create-async`  \n**Cost:** 1 credit per generation  \n**Source:** [src/tools.ts:65-120](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n#### Input Parameters\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `template_id` | string | Yes | Template short ID (12 characters) |\n| `data` | Record<string, unknown> | Yes | Key-value data to render in the template |\n| `export_type` | enum | No | Export format. Currently only `url` is supported for async. |\n| `expiration` | number | No | URL expiration in seconds (60-604800). Default: 86400 (24 hours) |\n| `filename` | string | No | Custom filename for the PDF |\n| `store_s3` | boolean | No | Upload to configured S3 bucket |\n| `s3_filepath` | string | No | Custom path prefix in S3 bucket |\n| `s3_bucket` | string | No | Override the default S3 bucket |\n| `webhook_url` | string | No | HTTPS URL to receive POST notification when job completes or fails |\n| `webhook_secret` | string | No | Secret for HMAC-SHA256 signing of webhook payloads (minimum 16 characters) |\n| `pdf_variant` | enum | No | PDF/A variant for compliance |\n| `version` | string | No | Version tag or number |\n\n#### Async Workflow\n\n```mermaid\ngraph TD\n    A[\"Call generate_pdf_async\"] --> B[\"Receive job_id (UUID)\"]\n    B --> C[\"Poll with get_pdf_job_status\"]\n    C --> D{\"Status = completed?\"}\n    D -->|Yes| E[\"Receive PDF URL\"]\n    D -->|No| F[\"Continue polling\"]\n    F --> C\n    D -->|Failed| G[\"Handle error\"]\n    B --> H[\"Optional: Configure webhook\"]\n    H --> I[\"Receive POST to webhook_url\"]\n    I --> E\n```\n\nSource: [src/tools.ts:65-120](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n## Job Management Tools\n\n### get_pdf_job_status\n\nThe `get_pdf_job_status` tool retrieves the current status of an asynchronous PDF generation job.\n\n**Tool Name:** `get_pdf_job_status`  \n**API Endpoint:** `GET /v1/pdf/jobs/{job_id}`  \n**Source:** [src/tools.ts:125-145](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n#### Input Parameters\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `job_id` | string | Yes | Async job ID (UUID returned by the create-async endpoint) |\n\n#### Job Status Values\n\n| Status | Description |\n|--------|-------------|\n| `pending` | Job is queued but not yet processing |\n| `processing` | PDF generation is in progress |\n| `completed` | PDF generation finished successfully; PDF URL available |\n| `failed` | PDF generation failed; check error details |\n\n#### Hints\n\n| Hint | Value | Description |\n|------|-------|-------------|\n| `readOnlyHint` | true | This tool only reads data, no modifications |\n\nSource: [src/tools.ts:125-145](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n### list_pdf_jobs\n\nThe `list_pdf_jobs` tool retrieves a list of asynchronous PDF generation jobs with pagination and status filtering.\n\n**Tool Name:** `list_pdf_jobs`  \n**API Endpoint:** `GET /v1/pdf/jobs`  \n**Source:** [src/tools.ts:150-175](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n#### Input Parameters\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `limit` | number | No | Maximum number of results to return |\n| `offset` | number | No | Number of results to skip (for pagination) |\n| `status` | enum | No | Filter jobs by status: `pending`, `processing`, `completed`, or `failed` |\n\n#### Hints\n\n| Hint | Value | Description |\n|------|-------|-------------|\n| `readOnlyHint` | true | This tool only reads data |\n\nSource: [src/tools.ts:150-175](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n## Template Discovery Tools\n\n### list_templates\n\nThe `list_templates` tool returns all available PDF templates in the user's account.\n\n**Tool Name:** `list_templates`  \n**API Endpoint:** `GET /v1/templates`  \n**Source:** [src/tools.ts:180-200](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n#### Hints\n\n| Hint | Value | Description |\n|------|-------|-------------|\n| `readOnlyHint` | true | This tool only reads data |\n\n#### Usage Pattern\n\n```mermaid\ngraph LR\n    A[\"list_templates\"] --> B[\"Get list of templates<br/>with IDs and names\"]\n    B --> C[\"Select template_id\"]\n    C --> D[\"get_template_fields\"]\n    D --> E[\"Discover required fields\"]\n    E --> F[\"generate_pdf with complete data\"]\n```\n\nSource: [src/tools.ts:180-200](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n### get_template_fields\n\nThe `get_template_fields` tool retrieves the dynamic fields defined for a specific template, including field names, types, and whether they are required.\n\n**Tool Name:** `get_template_fields`  \n**API Endpoint:** `GET /v1/templates/{template_id}/fields`  \n**Source:** [src/tools.ts:205-230](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n#### Input Parameters\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `template_id` | string | Yes | Template short ID (12 characters) |\n\n#### Hints\n\n| Hint | Value | Description |\n|------|-------|-------------|\n| `readOnlyHint` | true | This tool only reads data |\n\n#### Return Value\n\nThe tool returns field metadata including:\n- Field names (must match when providing data to `generate_pdf`)\n- Field types (string, number, boolean, etc.)\n- Required vs optional fields\n\nSource: [src/tools.ts:205-230](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n## Account Management Tools\n\n### get_account_info\n\nThe `get_account_info` tool retrieves account information including remaining credits and email address.\n\n**Tool Name:** `get_account_info`  \n**API Endpoint:** `GET /v1/account`  \n**Source:** [src/tools.ts:235-255](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n#### Hints\n\n| Hint | Value | Description |\n|------|-------|-------------|\n| `readOnlyHint` | true | This tool only reads data |\n\nSource: [src/tools.ts:235-255](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n### list_transactions\n\nThe `list_transactions` tool provides access to credit transaction history, showing PDF generations, purchases, and refunds.\n\n**Tool Name:** `list_transactions`  \n**API Endpoint:** `GET /v1/account/transactions`  \n**Source:** [src/tools.ts:260-285](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n#### Input Parameters\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `limit` | number | No | Number of records to return (1-1000) |\n| `offset` | number | No | Number of records to skip for pagination |\n\n#### Hints\n\n| Hint | Value | Description |\n|------|-------|-------------|\n| `readOnlyHint` | true | This tool only reads data |\n\nSource: [src/tools.ts:260-285](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n## API Client Integration\n\nThe tools utilize the `apiRequest` function from `src/api-client.ts` to communicate with the TemplateFox API. The API client handles:\n\n- **Base URL Configuration**: Defaults to `https://api.templatefox.com`, configurable via `TEMPLATEFOX_BASE_URL` environment variable\n- **API Key Management**: Supports two modes:\n  1. Per-request key from HTTP transport via `AsyncLocalStorage`\n  2. Environment variable `TEMPLATEFOX_API_KEY` for stdio mode\n- **Request Building**: Constructs URLs with query parameters and request bodies\n- **Response Handling**: Parses JSON or text responses based on `Content-Type` header\n\n```mermaid\ngraph TD\n    A[\"Tool Handler\"] --> B[\"apiRequest(method, path, body, query)\"]\n    B --> C[\"Construct URL with BASE_URL + path\"]\n    C --> D[\"Add query parameters if provided\"]\n    D --> E[\"Set headers<br/>x-api-key, Content-Type, Accept\"]\n    E --> F[\"Make fetch request\"]\n    F --> G[\"Parse response by Content-Type\"]\n    G --> H[\"Return ApiResponse<br/>{ok, status, data}\"]\n```\n\n### API Key Resolution\n\nThe `getApiKey()` function implements a fallback chain for API key resolution:\n\n1. **Per-request key from HTTP transport** - Uses `AsyncLocalStorage` context\n2. **Environment variable** - Falls back to `TEMPLATEFOX_API_KEY`\n3. **Error** - Throws if no key is available\n\n```mermaid\ngraph TD\n    A[\"getApiKey called\"] --> B{\"AsyncLocalStorage<br/>has context?\"}\n    B -->|Yes| C[\"Return context key\"]\n    B -->|No| D{\"TEMPLATEFOX_API_KEY<br/>env var set?\"}\n    D -->|Yes| E[\"Return env var value\"]\n    D -->|No| F[\"Throw error:<br/>API key required\"]\n```\n\nSource: [src/api-client.ts:1-75](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n\n## Configuration\n\n### Environment Variables\n\n| Variable | Required | Default | Description |\n|----------|----------|---------|-------------|\n| `TEMPLATEFOX_API_KEY` | Yes (stdio mode) | - | API key starting with `sk_` |\n| `TEMPLATEFOX_BASE_URL` | No | `https://api.templatefox.com` | Override API base URL |\n| `PORT` | No | - | Enable HTTP mode when set |\n\n### HTTP Transport Configuration\n\nWhen running in HTTP mode (by setting `PORT`), the server requires API key authentication via HTTP headers:\n\n| Header | Format | Example |\n|--------|--------|---------|\n| `Authorization` | `Bearer <key>` | `Authorization: Bearer sk_abc123...` |\n| `x-api-key` | `<key>` | `x-api-key: sk_abc123...` |\n\nSource: [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)\n\n## Complete Tool Summary\n\n| Tool | Name | Purpose | Read-Only |\n|------|------|---------|-----------|\n| `generate_pdf` | Synchronous PDF Generation | Create PDF from template with data | No |\n| `generate_pdf_async` | Async PDF Generation | Queue PDF job with webhook support | No |\n| `get_pdf_job_status` | Job Status Check | Poll async job status by ID | Yes |\n| `list_pdf_jobs` | Job List | List jobs with pagination/filtering | Yes |\n| `list_templates` | Template Discovery | List available templates | Yes |\n| `get_template_fields` | Field Discovery | Get template variable definitions | Yes |\n| `get_account_info` | Account Info | View credits and account details | Yes |\n| `list_transactions` | Transaction History | View credit transaction log | Yes |\n\nSource: [src/tools.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n## Version Information\n\n| Component | Version |\n|-----------|---------|\n| Package | `@templatefox/mcp-server` |\n| Server | 1.8.2 |\n| Package.json | 1.10.1 |\n| MCP SDK | ^1.29.0 |\n| Node.js Requirement | >=18.0.0 |\n\nSource: [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)\n\n---\n\n<a id='page-template-management-tools'></a>\n\n## Template Management Tools\n\n### Related Pages\n\nRelated topics: [PDF Generation Tools](#page-pdf-generation-tools), [Introduction](#page-introduction)\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following source files were used to generate this page:\n\n- [src/tools.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n- [src/api-client.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n- [src/index.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n- [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n- [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n</details>\n\n# Template Management Tools\n\n## Overview\n\nTemplate 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.\n\nThe 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.\n\n## Architecture\n\n### System Components\n\nThe template management system integrates several components within the MCP server architecture:\n\n| Component | File | Responsibility |\n|-----------|------|----------------|\n| MCP Server | `src/index.ts` | Initializes the MCP server and registers tools |\n| Tool Registration | `src/tools.ts` | Defines and registers template management tools |\n| API Client | `src/api-client.ts` | Handles HTTP communication with TemplateFox API |\n\n### Data Flow\n\n```mermaid\ngraph TD\n    A[AI Assistant] -->|MCP Protocol| B[MCP Server]\n    B -->|registerTools| C[Template Management Tools]\n    C -->|apiRequest| D[TemplateFox API]\n    D -->|Template List| B\n    B -->|Formatted Response| A\n    \n    E[TemplateFox API] -->|Field Schema| B\n```\n\n### API Communication\n\nThe 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.\n\nSource: [src/api-client.ts:8-9](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts#L8-L9)\nSource: [src/api-client.ts:19-35](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts#L19-L35)\n\n## Available Tools\n\n### list_templates\n\nThe `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.\n\n**Tool Definition:**\n\n```typescript\nserver.tool(\n  \"list_templates\",\n  \"List all available PDF templates. Returns template IDs and names. Use this to discover which templates are available before generating a PDF.\",\n  {},\n  { readOnlyHint: true },\n  async () => {\n    const url = \"/v1/templates\";\n    const result = await apiRequest(\"GET\", url);\n    return {\n      content: [{ type: \"text\", text: JSON.stringify(result.data, null, 2) }],\n      isError: !result.ok,\n    };\n  },\n);\n```\n\nSource: [src/tools.ts:115-128](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts#L115-L128)\n\n**Parameters:** None required\n\n**Return Value:** JSON object containing an array of template objects with their IDs and names\n\n**Characteristics:**\n\n- Read-only operation (marked with `readOnlyHint: true`)\n- Calls the `/v1/templates` endpoint via GET request\n- No pagination parameters supported\n\n### get_template_fields\n\nThe `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.\n\n**Tool Definition:**\n\n```typescript\nserver.tool(\n  \"get_template_fields\",\n  \"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.\",\n  {\n    template_id: z.string().describe(\"Template short ID (12 characters)\"),\n  },\n  { readOnlyHint: true },\n  async ({ template_id }) => {\n    const url = `/v1/templates/${template_id}/fields`;\n    const result = await apiRequest(\"GET\", url);\n    return {\n      content: [{ type: \"text\", text: JSON.stringify(result.data, null, 2) }],\n      isError: !result.ok,\n    };\n  },\n);\n```\n\nSource: [src/tools.ts:130-145](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts#L130-L145)\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `template_id` | string | Yes | Template short ID (12 characters) |\n\n**Return Value:** JSON object containing field names, types, and required status for each dynamic field in the template\n\n**Characteristics:**\n\n- Read-only operation (marked with `readOnlyHint: true`)\n- Calls the `/v1/templates/{template_id}/fields` endpoint via GET request\n- Template ID must be a valid 12-character string\n\n## Integration with PDF Generation\n\nTemplate management tools are integral to the PDF generation workflow. The typical workflow follows a discovery-then-generation pattern:\n\n```mermaid\ngraph LR\n    A[list_templates] -->|Discover template ID| B[get_template_fields]\n    B -->|Understand required fields| C[generate_pdf]\n    B -->|Job ID returned| D[generate_pdf_async]\n    D -->|Poll status| E[get_pdf_job_status]\n```\n\n### Workflow Example\n\n1. **List Available Templates**: Use `list_templates` to retrieve all templates and identify the desired template by name or ID\n2. **Inspect Template Schema**: Use `get_template_fields` with the template ID to understand required data fields, their types, and which are mandatory\n3. **Generate PDF**: Pass the template ID and properly structured data object to `generate_pdf` for synchronous generation or `generate_pdf_async` for background processing\n\nSource: [README.md:58-70](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md#L58-L70)\n\n## Configuration Requirements\n\n### Environment Variables\n\n| Variable | Required | Default | Description |\n|----------|----------|---------|-------------|\n| `TEMPLATEFOX_API_KEY` | Yes | — | API key starting with `sk_` |\n| `TEMPLATEFOX_BASE_URL` | No | `https://api.templatefox.com` | Override API base URL |\n\nSource: [README.md:38-47](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md#L38-L47)\n\n### Transport Modes\n\nThe MCP server supports two transport modes, both of which work with template management tools:\n\n| Mode | Command | Use Case |\n|------|---------|----------|\n| Stdio | `npx -y @templatefox/mcp-server` | Local desktop integration (Claude Desktop, Cursor, Windsurf) |\n| HTTP | `PORT=8080` + server binary | Remote/cloud deployments |\n\nFor HTTP transport, API key authentication is handled via HTTP headers:\n\n```\nAuthorization: Bearer sk_your_api_key_here\n```\n\nor:\n\n```\nx-api-key: sk_your_api_key_here\n```\n\nSource: [README.md:45-56](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md#L45-L56)\nSource: [src/index.ts:32-50](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts#L32-L50)\n\n## Tool Registration Mechanism\n\nThe `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`:\n\n```typescript\nfunction createServer(): McpServer {\n  const server = new McpServer({\n    name: SERVER_NAME,\n    version: SERVER_VERSION,\n  });\n  registerTools(server);\n  return server;\n}\n```\n\nSource: [src/index.ts:16-23](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts#L16-L23)\n\nEach tool is registered using the `@modelcontextprotocol/sdk` library's `server.tool()` method with the following signature:\n\n```typescript\nserver.tool(\n  name: string,           // Tool identifier\n  description: string,    // Human-readable description for AI\n  inputSchema: object,    // Zod schema for validation\n  annotations: object,    // Tool hints (readOnlyHint, destructiveHint)\n  handler: function       // Async function executing the tool\n)\n```\n\nSource: [src/tools.ts:4-11](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts#L4-L11)\n\n## Error Handling\n\nTemplate management tools return errors when API requests fail. The `isError` flag is set based on the `response.ok` property from the API client:\n\n```typescript\nreturn {\n  content: [{ type: \"text\", text: JSON.stringify(result.data, null, 2) }],\n  isError: !result.ok,\n};\n```\n\nSource: [src/tools.ts:123-128](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts#L123-L128)\n\nCommon error scenarios include:\n\n| Error | Cause | Resolution |\n|-------|-------|------------|\n| 401 Unauthorized | Missing or invalid API key | Ensure `TEMPLATEFOX_API_KEY` is set correctly |\n| 404 Not Found | Invalid template ID | Verify the template ID is 12 characters and exists |\n| 500 Internal Server Error | TemplateFox API issue | Check TemplateFox status page |\n\n## Package Information\n\n| Property | Value |\n|----------|-------|\n| Package Name | `@templatefox/mcp-server` |\n| Version | `1.10.1` |\n| License | MIT |\n| Node Engine | `>=18.0.0` |\n| SDK | `@modelcontextprotocol/sdk` ^1.29.0 |\n\nSource: [package.json:2-10](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json#L2-L10)\n\n---\n\n<a id='page-account-management-tools'></a>\n\n## Account Management Tools\n\n### Related Pages\n\nRelated topics: [PDF Generation Tools](#page-pdf-generation-tools)\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following source files were used to generate this page:\n\n- [src/tools.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n- [src/api-client.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n- [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n- [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n</details>\n\n# Account Management Tools\n\nThe 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.\n\n## Overview\n\nAccount Management Tools provide read-only access to account metadata and transaction history. They allow users to:\n\n- Check remaining credits and account details\n- Review credit transaction history with pagination support\n- Monitor PDF generation usage patterns\n\nAll 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.\n\n```mermaid\ngraph TD\n    A[MCP Client] -->|get_account_info| B[Account Info Tool]\n    A -->|list_transactions| C[Transaction History Tool]\n    B -->|GET /v1/account| D[TemplateFox API]\n    C -->|GET /v1/account/transactions| D\n    D -->|JSON Response| A\n```\n\n## Available Tools\n\n| Tool Name | Description | Endpoint |\n|-----------|-------------|----------|\n| `get_account_info` | Retrieve account details and remaining credits | `GET /v1/account` |\n| `list_transactions` | Fetch paginated credit transaction history | `GET /v1/account/transactions` |\n\n## get_account_info\n\nRetrieves comprehensive account information including remaining credits, email address, and account status. This tool is useful for checking resource availability before initiating PDF generation operations.\n\n### Parameters\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| (none) | - | - | This tool accepts no input parameters |\n\n### Implementation\n\n```typescript\n// getAccount -> get_account_info\nserver.tool(\n  \"get_account_info\",\n  \"Get account information including remaining credits and email address.\",\n  {\n  },\n  { readOnlyHint: true },\n  async () => {\n    const url = \"/v1/account\";\n    const result = await apiRequest(\"GET\", url);\n    return {\n      content: [{ type: \"text\", text: JSON.stringify(result.data, null, 2) }],\n      isError: !result.ok,\n    };\n  },\n);\n```\n\n*Source: [src/tools.ts:104-119](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)*\n\n### Response Format\n\nThe tool returns a JSON object containing account metadata. The typical response structure includes:\n\n- **credits**: Remaining credit balance for PDF generation\n- **email**: Account email address\n- **account status**: Active/suspended state\n\n### Use Cases\n\n- Verify sufficient credits before batch PDF generation\n- Display account dashboard information to users\n- Check if account is active before processing requests\n\n## list_transactions\n\nRetrieves 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.\n\n### Parameters\n\n| Parameter | Type | Required | Default | Description |\n|-----------|------|----------|---------|-------------|\n| `limit` | number (integer) | No | - | Number of records to return (1-1000) |\n| `offset` | number (integer) | No | 0 | Number of records to skip for pagination |\n| `status` | enum | No | - | Filter by transaction status |\n\n### Implementation\n\n```typescript\n// listTransactions -> list_transactions\nserver.tool(\n  \"list_transactions\",\n  \"List credit transaction history showing PDF generations, purchases, and refunds. Supports pagination.\",\n  {\n    limit: z.number().int().min(1).max(1000).optional().describe(\"Number of records to return\"),\n    offset: z.number().int().min(0).optional().describe(\"Number of records to skip\"),\n  },\n  { readOnlyHint: true },\n  async ({ limit, offset }) => {\n    const url = \"/v1/account/transactions\";\n    const result = await apiRequest(\"GET\", url, undefined, { limit, offset });\n    return {\n      content: [{ type: \"text\", JSON.stringify(result.data, null, 2) }],\n      isError: !result.ok,\n    };\n  },\n);\n```\n\n*Source: [src/tools.ts:144-162](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)*\n\n### Pagination Behavior\n\nThe pagination implementation in `api-client.ts` processes query parameters and appends them to the request URL:\n\n```typescript\nif (query) {\n  for (const [key, value] of Object.entries(query)) {\n    if (value !== undefined && value !== null) {\n      url.searchParams.set(key, String(value));\n    }\n  }\n}\n```\n\n*Source: [src/api-client.ts:42-47](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)*\n\n### Response Format\n\nThe transactions endpoint returns an array of transaction objects with:\n\n- **type**: Transaction type (generation, purchase, refund)\n- **amount**: Credit amount (positive for additions, negative for usage)\n- **timestamp**: When the transaction occurred\n- **description**: Human-readable transaction description\n\n### Use Cases\n\n- Audit trail for compliance and reporting\n- Track monthly PDF generation costs\n- Identify refund transactions\n- Monitor credit usage patterns\n\n## API Key Handling\n\nAccount Management Tools require a valid API key for authentication. The MCP server supports two authentication modes:\n\n```mermaid\ngraph LR\n    A[Request] --> B{Transport Mode}\n    B -->|stdio| C[Environment Variable<br/>TEMPLATEFOX_API_KEY]\n    B -->|HTTP| D[Authorization Header<br/>or x-api-key]\n```\n\n### Stdio Mode (Environment Variable)\n\n```typescript\nconst key = process.env.TEMPLATEFOX_API_KEY;\nif (!key) {\n  throw new Error(\n    \"TEMPLATEFOX_API_KEY is required. \" +\n    \"Set it as an environment variable or pass it via the Authorization header.\"\n  );\n}\n```\n\n*Source: [src/api-client.ts:20-28](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)*\n\n### HTTP Mode (Request Headers)\n\nFor HTTP transport, the API key is extracted from request headers:\n\n```typescript\nconst authHeader = req.headers.authorization;\nconst apiKey = authHeader?.startsWith(\"Bearer \")\n  ? authHeader.slice(7)\n  : (req.headers[\"x-api-key\"] as string | undefined);\n```\n\n*Source: [src/index.ts:52-56](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)*\n\n## Configuration\n\n| Environment Variable | Required | Default | Description |\n|---------------------|----------|---------|-------------|\n| `TEMPLATEFOX_API_KEY` | Yes | - | API key starting with `sk_` |\n| `TEMPLATEFOX_BASE_URL` | No | `https://api.templatefox.com` | Override API base URL |\n\n*Source: [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)*\n\n## Error Handling\n\nBoth Account Management Tools include standardized error handling:\n\n```typescript\nreturn {\n  content: [{ type: \"text\", text: JSON.stringify(result.data, null, 2) }],\n  isError: !result.ok,\n};\n```\n\nThe `isError` flag is set based on the API response status, allowing MCP clients to handle errors appropriately. Common error scenarios include:\n\n- **401 Unauthorized**: Invalid or missing API key\n- **403 Forbidden**: API key lacks necessary permissions\n- **429 Too Many Requests**: Rate limit exceeded\n- **500 Internal Server Error**: TemplateFox API issues\n\n## Example Usage\n\n### Checking Account Credits\n\n```\nTool: get_account_info\n```\n\nResponse:\n```json\n{\n  \"credits\": 150,\n  \"email\": \"user@example.com\",\n  \"status\": \"active\"\n}\n```\n\n### Retrieving Transaction History\n\n```\nTool: list_transactions\nParameters: {\n  \"limit\": 10,\n  \"offset\": 0\n}\n```\n\nResponse:\n```json\n{\n  \"transactions\": [\n    { \"type\": \"generation\", \"amount\": -1, \"description\": \"Invoice Template\", \"timestamp\": \"2024-01-15T10:30:00Z\" },\n    { \"type\": \"purchase\", \"amount\": 100, \"description\": \"Credit pack purchase\", \"timestamp\": \"2024-01-10T08:00:00Z\" }\n  ],\n  \"total\": 2\n}\n```\n\n## Related Tools\n\n| Tool | Category | Purpose |\n|------|----------|---------|\n| `generate_pdf` | PDF Generation | Create PDFs (consumes credits) |\n| `generate_pdf_async` | PDF Generation | Async PDF creation with webhooks |\n| `list_templates` | Template Discovery | Browse available templates |\n| `get_template_fields` | Template Discovery | Get template field definitions |\n\n---\n\n<a id='page-api-client'></a>\n\n## API Client\n\n### Related Pages\n\nRelated topics: [PDF Generation Tools](#page-pdf-generation-tools)\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following source files were used to generate this page:\n\n- [src/api-client.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n- [src/tools.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n- [src/index.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n- [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n- [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n</details>\n\n# API Client\n\nThe 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.\n\n## Overview\n\nThe 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:\n\n- Establishing authenticated connections to the TemplateFox API\n- Managing API credentials from multiple sources (environment variables, per-request headers)\n- Serializing and sending HTTP requests with proper content types\n- Handling JSON responses and error states\n- Supporting both synchronous (stdio) and asynchronous (HTTP) transport modes\n\n**Base URL Configuration:**\n```typescript\nconst BASE_URL = process.env.TEMPLATEFOX_BASE_URL || \"https://api.templatefox.com\";\n```\nSource: [`src/api-client.ts:11`](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n\n## Architecture\n\n### Request Flow\n\n```mermaid\ngraph TD\n    A[Tool Call] --> B[registerTools in tools.ts]\n    B --> C[apiRequest function]\n    C --> D{Transport Mode?}\n    D -->|Stdio| E[getApiKey from env]\n    D -->|HTTP| F[runWithApiKey with AsyncLocalStorage]\n    E --> G[Fetch API call]\n    F --> G\n    G --> H[Parse Response]\n    H --> I[Return ApiResponse]\n```\n\n### Dual Transport Support\n\nThe API Client supports two distinct transport modes:\n\n| Transport Mode | Trigger | API Key Source | Use Case |\n|----------------|---------|-----------------|----------|\n| **Stdio** | No `PORT` env var | `process.env.TEMPLATEFOX_API_KEY` | Local Claude Desktop, npx usage |\n| **HTTP** | `PORT` env var set | Per-request Authorization header | Cloud Run, self-hosted, remote clients |\n\nSource: [`src/index.ts:22-23`](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n## Core Components\n\n### ApiResponse Interface\n\n```typescript\ninterface ApiResponse {\n  ok: boolean;\n  status: number;\n  data: unknown;\n}\n```\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `ok` | `boolean` | Indicates if the HTTP response status was in the 2xx range |\n| `status` | `number` | HTTP status code from the API |\n| `data` | `unknown` | Parsed response body (JSON object or raw string) |\n\nSource: [`src/api-client.ts:58-62`](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n\n### The `apiRequest` Function\n\nThe central function for making API calls:\n\n```typescript\nexport async function apiRequest(\n  method: string,\n  path: string,\n  body?: Record<string, unknown>,\n  query?: Record<string, string | number | undefined>,\n): Promise<ApiResponse>\n```\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `method` | `string` | Yes | HTTP method (GET, POST, etc.) |\n| `path` | `string` | Yes | API endpoint path (e.g., `/v1/pdf/create`) |\n| `body` | `Record<string, unknown>` | No | JSON request body for POST requests |\n| `query` | `Record<string, string \\| number \\| undefined>` | No | Query string parameters |\n\n**Request Processing:**\n\n1. Constructs full URL by combining `BASE_URL` with the provided `path`\n2. Appends query parameters to URL\n3. Sets required headers including API key and Content-Type\n4. Executes fetch request\n5. Parses response based on Content-Type header\n\nSource: [`src/api-client.ts:64-101`](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n\n### API Key Management\n\n#### AsyncLocalStorage for Per-Request Keys\n\n```typescript\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nconst apiKeyStore = new AsyncLocalStorage<string>();\n```\n\nThe module uses Node.js `AsyncLocalStorage` to maintain per-request API key context in HTTP transport mode. This enables:\n\n- Stateless request handling (no session management required)\n- Isolation of API keys between concurrent requests\n- Clean middleware-style API key injection\n\nSource: [`src/api-client.ts:4,7`](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n\n#### The `runWithApiKey` Function\n\n```typescript\nexport function runWithApiKey<T>(apiKey: string, fn: () => T): T {\n  return apiKeyStore.run(apiKey, fn);\n}\n```\n\nWraps a function execution within a specific API key context. Used by the HTTP transport layer to inject the per-request API key.\n\nSource: [`src/api-client.ts:17-20`](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n\n#### The `getApiKey` Function\n\n```typescript\nfunction getApiKey(): string {\n  // 1. Per-request key from HTTP transport (AsyncLocalStorage)\n  const contextKey = apiKeyStore.getStore();\n  if (contextKey) return contextKey;\n\n  // 2. Environment variable (stdio mode)\n  const key = process.env.TEMPLATEFOX_API_KEY;\n  if (!key) {\n    throw new Error(\n      \"TEMPLATEFOX_API_KEY is required. \" +\n      \"Set it as an environment variable or pass it via the Authorization header. \" +\n      \"Get your API key at https://app.templatefox.com/dashboard/api-keys\"\n    );\n  }\n  return key;\n}\n```\n\n**Priority Order:**\n\n1. **Per-request key** from `AsyncLocalStorage` (HTTP transport mode)\n2. **Environment variable** `TEMPLATEFOX_API_KEY` (stdio transport mode)\n\nIf neither is available, throws a descriptive error with setup instructions.\n\nSource: [`src/api-client.ts:22-40`](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n\n## Usage in Tools\n\nAll MCP tools in `src/tools.ts` consume the API Client through `apiRequest`:\n\n```typescript\nimport { apiRequest } from \"./api-client.js\";\n\n// Example: List templates\nasync () => {\n  const url = \"/v1/templates\";\n  const result = await apiRequest(\"GET\", url);\n  return {\n    content: [{ type: \"text\", text: JSON.stringify(result.data, null, 2) }],\n    isError: !result.ok,\n  };\n}\n```\n\n**Tools Using the API Client:**\n\n| Tool | Method | Endpoint | Purpose |\n|------|--------|----------|---------|\n| `generate_pdf` | POST | `/v1/pdf/create` | Synchronous PDF generation |\n| `generate_pdf_async` | POST | `/v1/pdf/create-async` | Async PDF generation with webhooks |\n| `get_pdf_job_status` | GET | `/v1/pdf/jobs/{job_id}` | Check async job status |\n| `list_pdf_jobs` | GET | `/v1/pdf/jobs` | List all async jobs |\n| `list_templates` | GET | `/v1/templates` | List available templates |\n| `get_template_fields` | GET | `/v1/templates/{template_id}/fields` | Get template schema |\n| `get_account_info` | GET | `/v1/account` | Account and credit info |\n| `list_transactions` | GET | `/v1/account/transactions` | Credit transaction history |\n\nSource: [`src/tools.ts`](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n## HTTP Transport Integration\n\n### Request Handling in Express\n\n```typescript\napp.post(\"/mcp\", async (req, res) => {\n  const authHeader = req.headers.authorization;\n  const apiKey = authHeader?.startsWith(\"Bearer \")\n    ? authHeader.slice(7)\n    : (req.headers[\"x-api-key\"] as string | undefined);\n\n  if (!apiKey) {\n    res.status(401).json({\n      jsonrpc: \"2.0\",\n      error: {\n        code: -32001,\n        message: \"API key required. Pass it via Authorization: Bearer <key> or x-api-key header.\",\n      },\n      id: null,\n    });\n    return;\n  }\n\n  try {\n    const server = createServer();\n    const transport = new StreamableHTTPServerTransport({\n      sessionIdGenerator: undefined,\n    });\n    await server.connect(transport);\n    await runWithApiKey(apiKey, () => transport.handleRequest(req, res, req.body));\n  } catch (error) {\n    // Error handling\n  }\n});\n```\n\nSource: [`src/index.ts:47-82`](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n### Supported Authentication Headers\n\n| Header | Format | Example |\n|--------|--------|---------|\n| `Authorization` | `Bearer <api_key>` | `Authorization: Bearer sk_live_abc123...` |\n| `x-api-key` | `<api_key>` | `x-api-key: sk_live_abc123...` |\n\n## Configuration\n\n### Environment Variables\n\n| Variable | Required | Default | Description |\n|----------|----------|---------|-------------|\n| `TEMPLATEFOX_API_KEY` | Yes (Stdio) / No (HTTP) | - | API key starting with `sk_` |\n| `TEMPLATEFOX_BASE_URL` | No | `https://api.templatefox.com` | Override API base URL |\n| `PORT` | No | - | If set, enables HTTP transport mode |\n\nSource: [`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)\n\n## Dependencies\n\nThe API Client relies on these npm packages:\n\n| Package | Version | Purpose |\n|---------|---------|---------|\n| `@modelcontextprotocol/sdk` | `^1.29.0` | MCP server framework |\n| `express` | `^5.2.1` | HTTP server for remote transport |\n| `cors` | `^5.2.6` | CORS middleware for HTTP mode |\n\nSource: [`package.json`](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n\n## Error Handling\n\nThe 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:\n\n```typescript\nconst result = await apiRequest(\"GET\", url);\nreturn {\n  content: [{ type: \"text\", text: JSON.stringify(result.data, null, 2) }],\n  isError: !result.ok,\n};\n```\n\nThe response data typically contains error details from the TemplateFox API, including:\n\n- HTTP status codes\n- JSON-RPC error objects\n- Descriptive error messages\n\n## Health Check Endpoint\n\nWhen running in HTTP mode, a health check endpoint is available:\n\n```typescript\napp.get(\"/health\", (_req, res) => {\n  res.json({ status: \"ok\", version: SERVER_VERSION });\n});\n```\n\nThis endpoint does not require authentication and is suitable for load balancer health checks.\n\nSource: [`src/index.ts:35-38`](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n---\n\n<a id='page-installation'></a>\n\n## Installation and Setup\n\n### Related Pages\n\nRelated topics: [Docker Deployment](#page-docker-deployment), [Transport Modes](#page-transport-modes)\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following source files were used to generate this page:\n\n- [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n- [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n- [src/index.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n- [src/api-client.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n</details>\n\n# Installation and Setup\n\n## Overview\n\nThe 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.\n\nThe 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.\n\n**Source:** [README.md:1-5](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n## Prerequisites\n\n### System Requirements\n\n| Requirement | Specification |\n|-------------|---------------|\n| Node.js Version | `>= 18.0.0` |\n| Package Manager | npm, yarn, or pnpm |\n| Network Access | Outbound HTTPS to `api.templatefox.com` |\n\n**Source:** [package.json:17-19](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n\n### Required Credentials\n\nYou must obtain an API key from the TemplateFox dashboard before using the server:\n\n1. Visit [app.templatefox.com/dashboard/api-keys](https://app.templatefox.com/dashboard/api-keys)\n2. Generate a new API key (keys start with `sk_`)\n3. Store the key securely for configuration\n\n**Source:** [README.md:33-35](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n## Installation Methods\n\n### Method 1: Direct npx (Recommended for Claude Desktop)\n\nNo upfront installation required. Claude Desktop automatically downloads and runs the package.\n\n**Source:** [README.md:21-28](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n### Method 2: Global npm Installation\n\nFor command-line usage or custom MCP configurations:\n\n```bash\nnpm install -g @templatefox/mcp-server\n```\n\nAfter global installation, use the CLI directly:\n\n```bash\ntemplatefox-mcp-server\n```\n\n**Source:** [README.md:29-31](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n### Method 3: Docker Deployment\n\nBuild and run the server in a container:\n\n```bash\ndocker build -t templatefox-mcp .\ndocker run -p 8080:8080 templatefox-mcp\n```\n\n**Source:** [README.md:66-67](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n## Claude Desktop Configuration\n\n### Configuration File Location\n\n| Operating System | Config File Path |\n|-----------------|------------------|\n| macOS | `~/Library/Application Support/Claude/claude_desktop_config.json` |\n| Windows | `%APPDATA%\\Claude\\claude_desktop_config.json` |\n| Linux | `~/.config/Claude/claude_desktop_config.json` |\n\n**Source:** [README.md:14-16](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n### Configuration Format\n\nAdd the following to your Claude Desktop config:\n\n```json\n{\n  \"mcpServers\": {\n    \"templatefox\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@templatefox/mcp-server\"],\n      \"env\": {\n        \"TEMPLATEFOX_API_KEY\": \"sk_your_api_key_here\"\n      }\n    }\n  }\n}\n```\n\n**Source:** [README.md:17-27](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n## Claude Code Configuration\n\n### CLI Installation\n\nUse the Claude Code MCP management command:\n\n```bash\nclaude mcp add templatefox -- npx -y @templatefox/mcp-server\n```\n\nSet the `TEMPLATEFOX_API_KEY` environment variable in your shell configuration:\n\n```bash\nexport TEMPLATEFOX_API_KEY=sk_your_api_key_here\n```\n\n**Source:** [README.md:37-45](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n## Cursor and Windsurf Configuration\n\nBoth Cursor and Windsurf support the same MCP server configuration. Use the npx command with environment variable injection:\n\n```json\n{\n  \"mcpServers\": {\n    \"templatefox\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@templatefox/mcp-server\"],\n      \"env\": {\n        \"TEMPLATEFOX_API_KEY\": \"sk_your_api_key_here\"\n      }\n    }\n  }\n}\n```\n\n**Source:** [README.md:47-52](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n## Environment Variables\n\n### Configuration Reference\n\n| Variable | Required | Default | Description |\n|----------|----------|---------|-------------|\n| `TEMPLATEFOX_API_KEY` | Yes | - | Your API key (starts with `sk_`) |\n| `TEMPLATEFOX_BASE_URL` | No | `https://api.templatefox.com` | Override API base URL |\n| `PORT` | No | - | Enable HTTP mode on specified port |\n\n**Source:** [README.md:57-63](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n### API Key Resolution Order\n\nThe server resolves the API key in the following priority order:\n\n```mermaid\ngraph TD\n    A[API Key Request] --> B{Per-Request Header?}\n    B -->|Yes| C[Use Authorization or x-api-key header]\n    B -->|No| D{Environment Variable?}\n    D -->|Yes| E[Use TEMPLATEFOX_API_KEY]\n    D -->|No| F[Throw Error]\n    C --> G[Process Request]\n    E --> G\n    F --> H[Error: API key required]\n```\n\n**Source:** [src/api-client.ts:25-38](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n\n## HTTP Transport Mode\n\nThe MCP server supports HTTP transport via Streamable HTTP, enabling remote and cloud deployments.\n\n### Server Architecture\n\n```mermaid\ngraph LR\n    A[MCP Client] -->|HTTPS POST /mcp| B[Express Server]\n    A -->|Authorization Header| B\n    B --> C[StreamableHTTPServerTransport]\n    C --> D[McpServer Instance]\n    D --> E[API Request to TemplateFox]\n    E --> F[api.templatefox.com]\n```\n\n### Running in HTTP Mode\n\nSet the `PORT` environment variable to enable HTTP transport:\n\n```bash\nPORT=8080 TEMPLATEFOX_API_KEY=sk_your_key node dist/index.js\n```\n\n**Source:** [README.md:69-70](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n### Remote Server Endpoint\n\nTemplateFox hosts a public MCP server for remote access:\n\n```\nhttps://mcp-server-599407781746.us-central1.run.app/mcp\n```\n\n**Source:** [README.md:73-77](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n### HTTP Authentication\n\nMCP clients must pass the API key via HTTP header:\n\n```http\nAuthorization: Bearer sk_your_api_key_here\n```\n\nOr alternatively:\n\n```http\nx-api-key: sk_your_api_key_here\n```\n\n**Source:** [README.md:79-86](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n### HTTP Server Endpoints\n\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `/health` | GET | Health check endpoint |\n| `/mcp` | POST | MCP request endpoint |\n| `/mcp` | GET | Returns 405 Method Not Allowed |\n| `/mcp` | DELETE | Returns 405 (sessions not supported) |\n\n**Source:** [src/index.ts:42-56](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n### Per-Request API Key Handling\n\nIn HTTP mode, the server extracts the API key from incoming requests using `AsyncLocalStorage` to maintain request isolation:\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant Express\n    participant Transport\n    participant Server\n    participant API\n\n    Client->>Express: POST /mcp with Authorization header\n    Express->>Transport: Extract apiKey\n    Transport->>Server: Handle request with apiKey context\n    Server->>API: Make TemplateFox API call\n    API-->>Server: Response\n    Server-->>Transport: Tool result\n    Transport-->>Express: JSON-RPC response\n    Express-->>Client: HTTP Response\n```\n\n**Source:** [src/api-client.ts:8-14](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n\n## Stdio Transport Mode (Default)\n\nWhen `PORT` is not set, the server runs in stdio mode, which is the default for npx and local CLI usage:\n\n```mermaid\ngraph TD\n    A[AI Assistant] -->|stdio| B[StdioServerTransport]\n    B --> C[McpServer]\n    C --> D[Tool Handler]\n    D --> E[TemplateFox API]\n```\n\n**Source:** [src/index.ts:67-71](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n## Build from Source\n\nFor development or custom deployments:\n\n```bash\n# Clone the repository\ngit clone https://github.com/TemplateFoxPDF/mcp-server.git\ncd mcp-server\n\n# Install dependencies\nnpm install\n\n# Build TypeScript\nnpm run build\n\n# Run the server\nnpm start\n```\n\n### Build Scripts\n\n| Script | Command | Description |\n|--------|---------|-------------|\n| `build` | `tsc` | Compiles TypeScript to JavaScript |\n| `start` | `node dist/index.js` | Runs the compiled server |\n\n**Source:** [package.json:8-11](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n\n## Transport Selection Flow\n\n```mermaid\ngraph TD\n    A[Start] --> B{PORT environment variable set?}\n    B -->|Yes| C[HTTP Mode]\n    B -->|No| D[Stdio Mode]\n    C --> E[Initialize Express + StreamableHTTP]\n    D --> F[Initialize StdioServerTransport]\n    E --> G[Listen on configured port]\n    F --> H[Connect to stdio]\n```\n\n**Source:** [src/index.ts:32-71](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n## Package Metadata\n\n| Property | Value |\n|----------|-------|\n| Package Name | `@templatefox/mcp-server` |\n| Version | `1.10.1` |\n| License | MIT |\n| MCP Server Name | `io.github.TemplateFoxPDF/mcp-server` |\n| Homepage | `https://templatefox.com` |\n\n**Source:** [package.json:2-9](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n\n## Dependencies\n\n| Dependency | Version | Purpose |\n|------------|---------|---------|\n| `@modelcontextprotocol/sdk` | `^1.29.0` | MCP protocol implementation |\n| `express` | `^5.2.1` | HTTP server framework |\n| `cors` | `^2.8.6` | Cross-origin resource sharing |\n\n**Source:** [package.json:12-15](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n\n## Next Steps\n\nAfter successful installation and setup:\n\n1. **List Templates** - Discover available PDF templates using the `list_templates` tool\n2. **Get Template Fields** - Understand required data fields using `get_template_fields`\n3. **Generate PDFs** - Use `generate_pdf` to create PDFs with dynamic data\n4. **Check Credits** - Monitor remaining credits with `get_account_info`\n\n**Source:** [README.md:91-101](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n---\n\n<a id='page-docker-deployment'></a>\n\n## Docker Deployment\n\n### Related Pages\n\nRelated topics: [Installation and Setup](#page-installation), [Transport Modes](#page-transport-modes)\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following source files were used to generate this page:\n\n- [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n- [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n- [src/index.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n- [src/api-client.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n- [src/tools.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n</details>\n\n# Docker Deployment\n\nThe 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.\n\n## Overview\n\nDocker 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.\n\n**Key characteristics:**\n- HTTP-based transport mode (Streamable HTTP)\n- Stateless request handling\n- Health check endpoint for monitoring\n- Environment-based configuration\n- API key authentication via HTTP headers\n\nSource: [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[Docker Container] --> B[Express HTTP Server]\n    B --> C[/health Endpoint]\n    B --> D[/mcp Endpoint]\n    D --> E[MCP SDK Server]\n    E --> F[API Client]\n    F --> G[TemplateFox API]\n    \n    H[External Client] -->|POST /mcp| D\n    H -->|GET /health| C\n    \n    style A fill:#e1f5fe\n    style G fill:#fff3e0\n```\n\nThe 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.\n\nSource: [src/index.ts:1-95](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n## Building the Docker Image\n\n### Prerequisites\n\n- Docker Engine 20.10+\n- TemplateFox API key (obtained from [app.templatefox.com/dashboard/api-keys](https://app.templatefox.com/dashboard/api-keys))\n\n### Build Command\n\n```bash\ndocker build -t templatefox-mcp .\n```\n\nThe build process executes the following steps:\n1. Base image setup (Node.js runtime)\n2. Dependency installation via npm\n3. TypeScript compilation\n4. Production artifact preparation\n\nSource: [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json) (build script)\n\n### Build Script Configuration\n\n```json\n{\n  \"scripts\": {\n    \"build\": \"tsc\",\n    \"start\": \"node dist/index.js\"\n  }\n}\n```\n\nSource: [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n\n## Running the Container\n\n### Basic Usage\n\n```bash\ndocker run -p 8080:8080 -e TEMPLATEFOX_API_KEY=sk_your_api_key templatefox-mcp\n```\n\nThis command:\n- Maps container port 8080 to host port 8080\n- Passes the API key via environment variable\n- Starts the MCP server in HTTP mode\n\nSource: [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n### Environment Variables\n\n| Variable | Required | Default | Description |\n|----------|----------|---------|-------------|\n| `TEMPLATEFOX_API_KEY` | Yes | - | API key for TemplateFox API (starts with `sk_`) |\n| `PORT` | No | undefined (stdio mode) | Set to enable HTTP transport mode |\n| `TEMPLATEFOX_BASE_URL` | No | `https://api.templatefox.com` | Override API base URL |\n\nSource: [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)\n\n### Port Configuration\n\nWhen the `PORT` environment variable is set, the server automatically switches from stdio mode to HTTP mode:\n\n```typescript\nconst port = process.env.PORT ? parseInt(process.env.PORT, 10) : undefined;\n\nif (port) {\n  // HTTP mode: Streamable HTTP transport\n  const express = (await import(\"express\")).default;\n  // ... Express setup\n  app.listen(port, \"0.0.0.0\", () => {\n    console.error(`TemplateFox MCP server (HTTP) listening on http://0.0.0.0:${port}/mcp`);\n  });\n}\n```\n\nSource: [src/index.ts:27-35](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n## HTTP Endpoints\n\n### Health Check\n\n```\nGET /health\n```\n\nReturns server status and version information:\n\n```json\n{\n  \"status\": \"ok\",\n  \"version\": \"1.8.2\"\n}\n```\n\nSource: [src/index.ts:42-45](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n### MCP Endpoint\n\n```\nPOST /mcp\n```\n\nHandles all MCP JSON-RPC requests. Supports the complete MCP protocol including:\n- `initialize`\n- `tools/list`\n- `tools/call`\n- `ping`\n\n**Request Headers:**\n\n| Header | Required | Description |\n|--------|----------|-------------|\n| `Authorization` | Yes* | `Bearer sk_your_api_key_here` |\n| `x-api-key` | Yes* | `sk_your_api_key_here` (alternative) |\n| `Content-Type` | Yes | `application/json` for POST requests |\n\n*Either `Authorization` or `x-api-key` header is required.\n\nSource: [src/index.ts:47-62](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n### Method Not Allowed Responses\n\n```json\n{\n  \"jsonrpc\": \"2.0\",\n  \"error\": { \"code\": -32000, \"message\": \"Method not allowed. Use POST for MCP requests.\" },\n  \"id\": null\n}\n```\n\nBoth `GET /mcp` and `DELETE /mcp` return 405 Method Not Allowed responses since MCP requires POST.\n\nSource: [src/index.ts:81-92](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n## API Key Authentication\n\nThe server implements per-request API key authentication for HTTP transport:\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant Docker as Docker Container\n    participant MCP as MCP Server\n    participant API as TemplateFox API\n    \n    Client->>Docker: POST /mcp with API key header\n    Docker->>MCP: Extract API key from header\n    MCP->>API: Forward request with API key\n    API-->>MCP: Response data\n    MCP-->>Client: JSON-RPC response\n```\n\n### Key Extraction Logic\n\n```typescript\nconst authHeader = req.headers.authorization;\nconst apiKey = authHeader?.startsWith(\"Bearer \")\n  ? authHeader.slice(7)\n  : (req.headers[\"x-api-key\"] as string | undefined);\n```\n\nSource: [src/index.ts:47-53](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n### Key Resolution Priority\n\n1. **Per-request key** from HTTP transport via AsyncLocalStorage\n2. **Environment variable** `TEMPLATEFOX_API_KEY` (stdio mode fallback)\n\n```typescript\nfunction getApiKey(): string {\n  const contextKey = apiKeyStore.getStore();\n  if (contextKey) return contextKey;\n  \n  const key = process.env.TEMPLATEFOX_API_KEY;\n  if (!key) {\n    throw new Error(\"TEMPLATEFOX_API_KEY is required...\");\n  }\n  return key;\n}\n```\n\nSource: [src/api-client.ts:18-30](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n\n## Request Handling Flow\n\n```mermaid\ngraph TD\n    A[POST /mcp] --> B{API Key Present?}\n    B -->|No| C[401 Unauthorized]\n    B -->|Yes| D[Create MCP Server]\n    D --> E[Create HTTP Transport]\n    E --> F[Connect Server to Transport]\n    F --> G[Handle Request with API Key Context]\n    G --> H[Process JSON-RPC]\n    H --> I[Return Response]\n    I --> J[Close Transport & Server]\n    \n    style C fill:#ffcdd2\n    style I fill:#c8e6c9\n```\n\nThe server creates a fresh MCP server instance for each request to ensure stateless operation in cloud environments.\n\nSource: [src/index.ts:64-79](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n## MCP Tools Available\n\nOnce deployed, the following tools are accessible via the MCP protocol:\n\n| Tool | Purpose | Credits |\n|------|---------|---------|\n| `generate_pdf` | Synchronous PDF generation | 1 |\n| `generate_pdf_async` | Asynchronous PDF generation with webhooks | 1 |\n| `get_pdf_job_status` | Check async job status | - |\n| `list_pdf_jobs` | List async PDF jobs | - |\n| `list_templates` | List available templates | - |\n| `get_template_fields` | Get template field definitions | - |\n| `get_account_info` | Check account credits | - |\n| `list_transactions` | View transaction history | - |\n\nSource: [src/tools.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n## Remote Server Deployment\n\n### Cloud Run Example\n\nThe server can be deployed to Google Cloud Run using the provided Dockerfile:\n\n```bash\n# Build and deploy\ngcloud builds submit --tag gcr.io/PROJECT_ID/templatefox-mcp\ngcloud run deploy templatefox-mcp --image gcr.io/PROJECT_ID/templatefox-mcp --port 8080\n```\n\n### Connecting via URL\n\nExternal MCP clients can connect to the deployed server:\n\n```\nhttps://mcp-server-599407781746.us-central1.run.app/mcp\n```\n\nSource: [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n## Container Networking\n\n```mermaid\ngraph LR\n    subgraph Host\n        A[localhost:8080] --> B[Container:8080]\n    end\n    \n    subgraph Container\n        B --> C[Express Server]\n        C --> D[MCP Handler]\n        D --> E[TemplateFox API]\n    end\n    \n    E -->|HTTPS| F[api.templatefox.com]\n```\n\nThe container listens on all network interfaces (`0.0.0.0`) to accept external connections when deployed to cloud environments.\n\nSource: [src/index.ts:34](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n## Dependencies\n\n### Production Dependencies\n\n| Package | Version | Purpose |\n|---------|---------|---------|\n| `@modelcontextprotocol/sdk` | ^1.29.0 | MCP protocol implementation |\n| `express` | ^5.2.1 | HTTP server framework |\n| `cors` | ^2.8.6 | Cross-origin resource sharing |\n\nSource: [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n\n### Runtime Requirements\n\n- Node.js >= 18.0.0\n- Network access to `api.templatefox.com`\n- Valid TemplateFox API key\n\nSource: [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n\n## Troubleshooting\n\n### Container Exits Immediately\n\n**Cause:** Missing `PORT` environment variable.\n\n**Solution:** Set `PORT` environment variable to enable HTTP mode:\n```bash\ndocker run -p 8080:8080 -e PORT=8080 -e TEMPLATEFOX_API_KEY=sk_xxx templatefox-mcp\n```\n\n### 401 Unauthorized Errors\n\n**Cause:** Missing or invalid API key in request headers.\n\n**Solution:** Include API key via `Authorization: Bearer` header or `x-api-key` header.\n\n### Connection Refused\n\n**Cause:** Port not mapped correctly or container not running.\n\n**Solution:** Verify container is running and port mapping is correct:\n```bash\ndocker ps | grep templatefox-mcp\ndocker port templatefox-mcp\n```\n\n## Security Considerations\n\n- **API keys** are passed via HTTP headers; always use HTTPS in production\n- **Container runs as non-root** (recommended for production deployments)\n- **Network isolation** is handled by Docker's container networking\n- **Environment variables** should be managed via secrets in production orchestration systems\n\nSource: [src/index.ts:47-62](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n---\n\n---\n\n## Doramagic Pitfall Log\n\nProject: templatefoxpdf/mcp-server\n\nSummary: 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.\n\n## 1. installation · 社区讨论暴露的待验证问题：darkzodchi en X: \"Top MCP Servers That Turn Claude Into a Productivity Machine\" / X\n\n- Severity: medium\n- Evidence strength: source_linked\n- 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…\n- User impact: 这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。\n- Suggested check: Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。\n- 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\n\n## 2. capability · 能力判断依赖假设\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: README/documentation is current enough for a first validation pass.\n- User impact: 假设不成立时，用户拿不到承诺的能力。\n- Suggested check: 将假设转成下游验证清单。\n- Guardrail action: 假设必须转成验证项；没有验证结果前不能写成事实。\n- 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.\n\n## 3. runtime · 社区讨论暴露的待验证问题：Adding Github MCP to Claude Code Error : r/ClaudeAI - Reddit\n\n- Severity: medium\n- Evidence strength: source_linked\n- 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 ...\n- User impact: 这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。\n- Suggested check: Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。\n- 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\n\n## 4. runtime · 社区讨论暴露的待验证问题：you need somewhere between 1-10 Claude skills depending on what ...\n\n- Severity: medium\n- Evidence strength: source_linked\n- 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 ...\n- User impact: 这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。\n- Suggested check: Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。\n- Evidence: social_signal:x | ssig_504e57203f64433a83bf7ec96631f94c | https://x.com/Hesamation/status/2035136966719582695 | you need somewhere between 1-10 Claude skills depending on what ...\n\n## 5. maintenance · 维护活跃度未知\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: 未记录 last_activity_observed。\n- User impact: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- Suggested check: 补 GitHub 最近 commit、release、issue/PR 响应信号。\n- Guardrail action: 维护活跃度未知时，推荐强度不能标为高信任。\n- 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\n\n## 6. security_permissions · 下游验证发现风险项\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: no_demo\n- User impact: 下游已经要求复核，不能在页面中弱化。\n- Suggested check: 进入安全/权限治理复核队列。\n- Guardrail action: 下游风险存在时必须保持 review/recommendation 降级。\n- 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\n\n## 7. security_permissions · 存在评分风险\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: no_demo\n- User impact: 风险会影响是否适合普通用户安装。\n- Suggested check: 把风险写入边界卡，并确认是否需要人工复核。\n- Guardrail action: 评分风险必须进入边界卡，不能只作为内部分数。\n- 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\n\n## 8. maintenance · issue/PR 响应质量未知\n\n- Severity: low\n- Evidence strength: source_linked\n- Finding: issue_or_pr_quality=unknown。\n- User impact: 用户无法判断遇到问题后是否有人维护。\n- Suggested check: 抽样最近 issue/PR，判断是否长期无人处理。\n- Guardrail action: issue/PR 响应未知时，必须提示维护风险。\n- 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\n\n## 9. maintenance · 发布节奏不明确\n\n- Severity: low\n- Evidence strength: source_linked\n- Finding: release_recency=unknown。\n- User impact: 安装命令和文档可能落后于代码，用户踩坑概率升高。\n- Suggested check: 确认最近 release/tag 和 README 安装命令是否一致。\n- Guardrail action: 发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 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\n\n<!-- canonical_name: templatefoxpdf/mcp-server; human_manual_source: deepwiki_human_wiki -->\n",
      "markdown_key": "mcp-server",
      "pages": "draft",
      "source_refs": [
        {
          "evidence_id": "mcp_registry:io.github.TemplateFoxPDF/mcp-server:1.9.7",
          "kind": "mcp_registry",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://registry.modelcontextprotocol.io/v0.1/servers/io.github.TemplateFoxPDF%2Fmcp-server/versions/1.9.7"
        }
      ],
      "summary": "DeepWiki/Human Wiki output with a Doramagic pitfall appendix.",
      "title": "mcp-server 说明书",
      "toc": [
        "https://github.com/TemplateFoxPDF/mcp-server Project Manual",
        "Table of Contents",
        "Introduction",
        "Overview",
        "Architecture",
        "Transport Modes",
        "API Key Management",
        "Tool Registration",
        "Doramagic 踩坑日志"
      ]
    }
  },
  "quality_gate": {
    "blocking_gaps": [],
    "category_confidence": "medium",
    "compile_status": "ready_for_review",
    "five_assets_present": true,
    "install_sandbox_verified": true,
    "missing_evidence": [],
    "next_action": "publish to Doramagic.ai project surfaces",
    "prompt_preview_boundary_ok": true,
    "publish_status": "publishable",
    "quick_start_verified": true,
    "repo_clone_verified": true,
    "repo_commit": "12d686c56af50830db95be8ed81c90efa9f48c1e",
    "repo_inspection_error": null,
    "repo_inspection_files": [
      "Dockerfile",
      "package.json",
      "README.md",
      "src/tools.ts",
      "src/index.ts",
      "src/api-client.ts"
    ],
    "repo_inspection_verified": true,
    "review_reasons": [],
    "tag_count_ok": true,
    "unsupported_claims": []
  },
  "schema_version": "0.1",
  "user_assets": {
    "ai_context_pack": {
      "asset_id": "ai_context_pack",
      "filename": "AI_CONTEXT_PACK.md",
      "markdown": "# @templatefox/mcp-server - Doramagic AI Context Pack\n\n> 定位：安装前体验与判断资产。它帮助宿主 AI 有一个好的开始，但不代表已经安装、执行或验证目标项目。\n\n## 充分原则\n\n- **充分原则，不是压缩原则**：AI Context Pack 应该充分到让宿主 AI 在开工前理解项目价值、能力边界、使用入口、风险和证据来源；它可以分层组织，但不以最短摘要为目标。\n- **压缩策略**：只压缩噪声和重复内容，不压缩会影响判断和开工质量的上下文。\n\n## 给宿主 AI 的使用方式\n\n你正在读取 Doramagic 为 @templatefox/mcp-server 编译的 AI Context Pack。请把它当作开工前上下文：帮助用户理解适合谁、能做什么、如何开始、哪些必须安装后验证、风险在哪里。不要声称你已经安装、运行或执行了目标项目。\n\n## Claim 消费规则\n\n- **事实来源**：Repo Evidence + Claim/Evidence Graph；Human Wiki 只提供显著性、术语和叙事结构。\n- **事实最低状态**：`supported`\n- `supported`：可以作为项目事实使用，但回答中必须引用 claim_id 和证据路径。\n- `weak`：只能作为低置信度线索，必须要求用户继续核实。\n- `inferred`：只能用于风险提示或待确认问题，不能包装成项目事实。\n- `unverified`：不得作为事实使用，应明确说证据不足。\n- `contradicted`：必须展示冲突来源，不得替用户强行选择一个版本。\n\n## 它最适合谁\n\n- **正在使用 Claude/Codex/Cursor/Gemini 等宿主 AI 的开发者**：README 或插件配置提到多个宿主 AI。 证据：`README.md` Claim：`clm_0002` supported 0.86\n\n## 它能做什么\n\n- **命令行启动或安装流程**（需要安装后验证）：项目文档中存在可执行命令，真实使用需要在本地或宿主环境中运行这些命令。 证据：`README.md` Claim：`clm_0001` supported 0.86\n\n## 怎么开始\n\n- `claude mcp add templatefox -- npx -y @templatefox/mcp-server` 证据：`README.md` Claim：`clm_0003` supported 0.86\n- `npm install -g @templatefox/mcp-server` 证据：`README.md` Claim：`clm_0004` supported 0.86\n\n## 继续前判断卡\n\n- **当前建议**：需要管理员/安全审批\n- **为什么**：继续前可能涉及密钥、账号、外部服务或敏感上下文，建议先经过管理员或安全审批。\n\n### 30 秒判断\n\n- **现在怎么做**：需要管理员/安全审批\n- **最小安全下一步**：先跑 Prompt Preview；若涉及凭证或企业环境，先审批再试装\n- **先别相信**：工具权限边界不能在安装前相信。\n- **继续会触碰**：命令执行、本地环境或项目文件、环境变量 / API Key\n\n### 现在可以相信\n\n- **适合人群线索：正在使用 Claude/Codex/Cursor/Gemini 等宿主 AI 的开发者**（supported）：有 supported claim 或项目证据支撑，但仍不等于真实安装效果。 证据：`README.md` Claim：`clm_0002` supported 0.86\n- **能力存在：命令行启动或安装流程**（supported）：可以相信项目包含这类能力线索；是否适合你的具体任务仍要试用或安装后验证。 证据：`README.md` Claim：`clm_0001` supported 0.86\n- **存在 Quick Start / 安装命令线索**（supported）：可以相信项目文档出现过启动或安装入口；不要因此直接在主力环境运行。 证据：`README.md` Claim：`clm_0003` supported 0.86\n\n### 现在还不能相信\n\n- **工具权限边界不能在安装前相信。**（unverified）：MCP/tool 类项目通常会触碰文件、网络、浏览器或外部 API，必须真实检查权限和日志。\n- **真实输出质量不能在安装前相信。**（unverified）：Prompt Preview 只能展示引导方式，不能证明真实项目中的结果质量。\n- **宿主 AI 版本兼容性不能在安装前相信。**（unverified）：Claude、Cursor、Codex、Gemini 等宿主加载规则和版本差异必须在真实环境验证。\n- **不会污染现有宿主 AI 行为，不能直接相信。**（inferred）：Skill、plugin、AGENTS/CLAUDE/GEMINI 指令可能改变宿主 AI 的默认行为。\n- **可安全回滚不能默认相信。**（unverified）：除非项目明确提供卸载和恢复说明，否则必须先在隔离环境验证。\n- **真实安装后是否与用户当前宿主 AI 版本兼容？**（unverified）：兼容性只能通过实际宿主环境验证。\n- **项目输出质量是否满足用户具体任务？**（unverified）：安装前预览只能展示流程和边界，不能替代真实评测。\n- **安装命令是否需要网络、权限或全局写入？**（unverified）：这影响企业环境和个人环境的安装风险。 证据：`README.md`\n\n### 继续会触碰什么\n\n- **命令执行**：包管理器、网络下载、本地插件目录、项目配置或用户主目录。 原因：运行第一条命令就可能产生环境改动；必须先判断是否值得跑。 证据：`README.md`\n- **本地环境或项目文件**：安装结果、插件缓存、项目配置或本地依赖目录。 原因：安装前无法证明写入范围和回滚方式，需要隔离验证。 证据：`README.md`\n- **环境变量 / API Key**：项目入口文档明确出现 API key、token、secret 或账号凭证配置。 原因：如果真实安装需要凭证，应先使用测试凭证并经过权限/合规判断。 证据：`README.md`, `src/api-client.ts`\n- **宿主 AI 上下文**：AI Context Pack、Prompt Preview、Skill 路由、风险规则和项目事实。 原因：导入上下文会影响宿主 AI 后续判断，必须避免把未验证项包装成事实。\n\n### 最小安全下一步\n\n- **先跑 Prompt Preview**：用安装前交互式试用判断工作方式是否匹配，不需要授权或改环境。（适用：任何项目都适用，尤其是输出质量未知时。）\n- **只在隔离目录或测试账号试装**：避免安装命令污染主力宿主 AI、真实项目或用户主目录。（适用：存在命令执行、插件配置或本地写入线索时。）\n- **不要使用真实生产凭证**：环境变量/API key 一旦进入宿主或工具链，可能产生账号和合规风险。（适用：出现 API、TOKEN、KEY、SECRET 等环境线索时。）\n- **安装后只验证一个最小任务**：先验证加载、兼容、输出质量和回滚，再决定是否深用。（适用：准备从试用进入真实工作流时。）\n\n### 退出方式\n\n- **保留安装前状态**：记录原始宿主配置和项目状态，后续才能判断是否可恢复。\n- **记录安装命令和写入路径**：没有明确卸载说明时，至少要知道哪些目录或配置需要手动清理。\n- **准备撤销测试 API key 或 token**：测试凭证泄露或误用时，可以快速止损。\n- **如果没有回滚路径，不进入主力环境**：不可回滚是继续前阻断项，不应靠信任或运气继续。\n\n## 哪些只能预览\n\n- 解释项目适合谁和能做什么\n- 基于项目文档演示典型对话流程\n- 帮助用户判断是否值得安装或继续研究\n\n## 哪些必须安装后验证\n\n- 真实安装 Skill、插件或 CLI\n- 执行脚本、修改本地文件或访问外部服务\n- 验证真实输出质量、性能和兼容性\n\n## 边界与风险判断卡\n\n- **把安装前预览误认为真实运行**：用户可能高估项目已经完成的配置、权限和兼容性验证。 处理方式：明确区分 prompt_preview_can_do 与 runtime_required。 Claim：`clm_0005` inferred 0.45\n- **命令执行会修改本地环境**：安装命令可能写入用户主目录、宿主插件目录或项目配置。 处理方式：先在隔离环境或测试账号中运行。 证据：`README.md` Claim：`clm_0006` supported 0.86\n- **待确认**：真实安装后是否与用户当前宿主 AI 版本兼容？。原因：兼容性只能通过实际宿主环境验证。\n- **待确认**：项目输出质量是否满足用户具体任务？。原因：安装前预览只能展示流程和边界，不能替代真实评测。\n- **待确认**：安装命令是否需要网络、权限或全局写入？。原因：这影响企业环境和个人环境的安装风险。\n\n## 开工前工作上下文\n\n### 加载顺序\n\n- 先读取 how_to_use.host_ai_instruction，建立安装前判断资产的边界。\n- 读取 claim_graph_summary，确认事实来自 Claim/Evidence Graph，而不是 Human Wiki 叙事。\n- 再读取 intended_users、capabilities 和 quick_start_candidates，判断用户是否匹配。\n- 需要执行具体任务时，优先查 role_skill_index，再查 evidence_index。\n- 遇到真实安装、文件修改、网络访问、性能或兼容性问题时，转入 risk_card 和 boundaries.runtime_required。\n\n### 任务路由\n\n- **命令行启动或安装流程**：先说明这是安装后验证能力，再给出安装前检查清单。 边界：必须真实安装或运行后验证。 证据：`README.md` Claim：`clm_0001` supported 0.86\n\n### 上下文规模\n\n- 文件总数：10\n- 重要文件覆盖：9/10\n- 证据索引条目：9\n- 角色 / Skill 条目：1\n\n### 证据不足时的处理\n\n- **missing_evidence**：说明证据不足，要求用户提供目标文件、README 段落或安装后验证记录；不要补全事实。\n- **out_of_scope_request**：说明该任务超出当前 AI Context Pack 证据范围，并建议用户先查看 Human Manual 或真实安装后验证。\n- **runtime_request**：给出安装前检查清单和命令来源，但不要替用户执行命令或声称已执行。\n- **source_conflict**：同时展示冲突来源，标记为待核实，不要强行选择一个版本。\n\n## Prompt Recipes\n\n### 适配判断\n\n- 目标：判断这个项目是否适合用户当前任务。\n- 预期输出：适配结论、关键理由、证据引用、安装前可预览内容、必须安装后验证内容、下一步建议。\n\n```text\n请基于 @templatefox/mcp-server 的 AI Context Pack，先问我 3 个必要问题，然后判断它是否适合我的任务。回答必须包含：适合谁、能做什么、不能做什么、是否值得安装、证据来自哪里。所有项目事实必须引用 evidence_refs、source_paths 或 claim_id。\n```\n\n### 安装前体验\n\n- 目标：让用户在安装前感受核心工作流，同时避免把预览包装成真实能力或营销承诺。\n- 预期输出：一段带边界标签的体验剧本、安装后验证清单和谨慎建议；不含真实运行承诺或强营销表述。\n\n```text\n请把 @templatefox/mcp-server 当作安装前体验资产，而不是已安装工具或真实运行环境。\n\n请严格输出四段：\n1. 先问我 3 个必要问题。\n2. 给出一段“体验剧本”：用 [安装前可预览]、[必须安装后验证]、[证据不足] 三种标签展示它可能如何引导工作流。\n3. 给出安装后验证清单：列出哪些能力只有真实安装、真实宿主加载、真实项目运行后才能确认。\n4. 给出谨慎建议：只能说“值得继续研究/试装”“先补充信息后再判断”或“不建议继续”，不得替项目背书。\n\n硬性边界：\n- 不要声称已经安装、运行、执行测试、修改文件或产生真实结果。\n- 不要写“自动适配”“确保通过”“完美适配”“强烈建议安装”等承诺性表达。\n- 如果描述安装后的工作方式，必须使用“如果安装成功且宿主正确加载 Skill，它可能会……”这种条件句。\n- 体验剧本只能写成“示例台词/假设流程”：使用“可能会询问/可能会建议/可能会展示”，不要写“已写入、已生成、已通过、正在运行、正在生成”。\n- Prompt Preview 不负责给安装命令；如用户准备试装，只能提示先阅读 Quick Start 和 Risk Card，并在隔离环境验证。\n- 所有项目事实必须来自 supported claim、evidence_refs 或 source_paths；inferred/unverified 只能作风险或待确认项。\n\n```\n\n### 角色 / Skill 选择\n\n- 目标：从项目里的角色或 Skill 中挑选最匹配的资产。\n- 预期输出：候选角色或 Skill 列表，每项包含适用场景、证据路径、风险边界和是否需要安装后验证。\n\n```text\n请读取 role_skill_index，根据我的目标任务推荐 3-5 个最相关的角色或 Skill。每个推荐都要说明适用场景、可能输出、风险边界和 evidence_refs。\n```\n\n### 风险预检\n\n- 目标：安装或引入前识别环境、权限、规则冲突和质量风险。\n- 预期输出：环境、权限、依赖、许可、宿主冲突、质量风险和未知项的检查清单。\n\n```text\n请基于 risk_card、boundaries 和 quick_start_candidates，给我一份安装前风险预检清单。不要替我执行命令，只说明我应该检查什么、为什么检查、失败会有什么影响。\n```\n\n### 宿主 AI 开工指令\n\n- 目标：把项目上下文转成一次对话开始前的宿主 AI 指令。\n- 预期输出：一段边界明确、证据引用明确、适合复制给宿主 AI 的开工前指令。\n\n```text\n请基于 @templatefox/mcp-server 的 AI Context Pack，生成一段我可以粘贴给宿主 AI 的开工前指令。这段指令必须遵守 not_runtime=true，不能声称项目已经安装、运行或产生真实结果。\n```\n\n\n## 角色 / Skill 索引\n\n- 共索引 1 个角色 / Skill / 项目文档条目。\n\n- **TemplateFox MCP Server**（project_doc）：MCP Model Context Protocol server for the TemplateFox https://templatefox.com PDF generation API. Generate PDFs from templates directly through AI assistants like Claude, Cursor, and Windsurf. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`README.md`\n\n## 证据索引\n\n- 共索引 9 条证据。\n\n- **TemplateFox MCP Server**（documentation）：MCP Model Context Protocol server for the TemplateFox https://templatefox.com PDF generation API. Generate PDFs from templates directly through AI assistants like Claude, Cursor, and Windsurf. 证据：`README.md`\n- **Package**（package_manifest）：{ \"name\": \"@templatefox/mcp-server\", \"version\": \"1.10.1\", \"description\": \"MCP server for TemplateFox PDF generation API - Generate PDFs from templates via AI assistants\", \"author\": \"TemplateFox\", \"license\": \"MIT\", \"type\": \"module\", \"bin\": { \"templatefox-mcp-server\": \"./dist/index.js\" }, \"main\": \"./dist/index.js\", \"files\": \"dist\" , \"scripts\": { \"build\": \"tsc\", \"start\": \"node dist/index.js\" }, \"dependencies\": { \"@modelcontextprotocol/sdk\": \"^1.29.0\", \"express\": \"^5.2.1\", \"cors\": \"^2.8.6\" }, \"devDependencies\": { \"typescript\": \"^5.8.0\", \"@types/node\": \"^22.0.0\", \"@types/express\": \"^5.0.0\", \"@types/cors\": \"^2.8.0\" }, \"keywords\": \"mcp\", \"mcp-server\", \"model-context-protocol\", \"pdf\", \"templatefox\"… 证据：`package.json`\n- **License**（source_file）：Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files the \"Software\" , to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 证据：`LICENSE`\n- **Tsconfig**（structured_config）：{ \"compilerOptions\": { \"target\": \"ES2022\", \"module\": \"Node16\", \"moduleResolution\": \"Node16\", \"outDir\": \"./dist\", \"rootDir\": \"./src\", \"strict\": true, \"esModuleInterop\": true, \"skipLibCheck\": true, \"forceConsistentCasingInFileNames\": true, \"declaration\": true, \"declarationMap\": true, \"sourceMap\": true }, \"include\": \"src/ / \" , \"exclude\": \"node modules\", \"dist\" } 证据：`tsconfig.json`\n- **.dockerignore**（source_file）：node modules dist .git .md LICENSE 证据：`.dockerignore`\n- **Dockerfile**（source_file）：FROM node:22-slim AS builder WORKDIR /app COPY package.json package-lock.json ./ RUN npm install COPY . . RUN npm run build 证据：`Dockerfile`\n- **Api Client**（source_file）：import { AsyncLocalStorage } from \"node:async hooks\"; 证据：`src/api-client.ts`\n- **!/usr/bin/env node**（source_file）：!/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\"; 证据：`src/index.ts`\n- **Tools**（source_file）：import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\"; import { z } from \"zod\"; import { apiRequest } from \"./api-client.js\"; 证据：`src/tools.ts`\n\n## 宿主 AI 必须遵守的规则\n\n- **把本资产当作开工前上下文，而不是运行环境。**：AI Context Pack 只包含证据化项目理解，不包含目标项目的可执行状态。 证据：`README.md`, `package.json`, `LICENSE`\n- **回答用户时区分可预览内容与必须安装后才能验证的内容。**：安装前体验的消费者价值来自降低误装和误判，而不是伪装成真实运行。 证据：`README.md`, `package.json`, `LICENSE`\n\n## 用户开工前应该回答的问题\n\n- 你准备在哪个宿主 AI 或本地环境中使用它？\n- 你只是想先体验工作流，还是准备真实安装？\n- 你最在意的是安装成本、输出质量、还是和现有规则的冲突？\n\n## 验收标准\n\n- 所有能力声明都能回指到 evidence_refs 中的文件路径。\n- AI_CONTEXT_PACK.md 没有把预览包装成真实运行。\n- 用户能在 3 分钟内看懂适合谁、能做什么、如何开始和风险边界。\n\n---\n\n## Doramagic Context Augmentation\n\nThe following material strengthens the Repomix/AI Context Pack body. Human Manual is only a reading skeleton; pitfall logs become hard operating constraints for the host AI.\n\n## Human Manual Skeleton\n\nUsage rule: this is only a reading path and salience signal, not factual authority. Concrete facts must still come from repo evidence / Claim Graph.\n\nHard rules for the host AI:\n- Do not treat page titles, order, summaries, or importance as project facts.\n- When explaining the Human Manual skeleton, state that it is only a reading path / salience signal.\n- Capability, installation, compatibility, runtime status, and risk judgments must cite repo evidence, source paths, or Claim Graph.\n\n- **Introduction**：importance `high`\n  - source_paths: README.md, package.json\n- **Project Structure**：importance `high`\n  - source_paths: package.json, tsconfig.json, Dockerfile\n- **Transport Modes**：importance `high`\n  - source_paths: src/index.ts\n- **Server Initialization**：importance `medium`\n  - source_paths: src/index.ts, src/tools.ts\n- **PDF Generation Tools**：importance `high`\n  - source_paths: src/tools.ts\n- **Template Management Tools**：importance `high`\n  - source_paths: src/tools.ts\n- **Account Management Tools**：importance `medium`\n  - source_paths: src/tools.ts\n- **API Client**：importance `high`\n  - source_paths: src/api-client.ts\n\n## Repo Inspection Evidence\n\n- repo_clone_verified: true\n- repo_inspection_verified: true\n- repo_commit: `12d686c56af50830db95be8ed81c90efa9f48c1e`\n- inspected_files: `Dockerfile`, `package.json`, `README.md`, `src/tools.ts`, `src/index.ts`, `src/api-client.ts`\n\nHard rules for the host AI:\n- Without repo_clone_verified=true, do not claim the source code has been read.\n- Without repo_inspection_verified=true, do not turn README/docs/package observations into facts.\n- Without quick_start_verified=true, do not claim the Quick Start has been successfully run.\n\n## Doramagic Pitfall Constraints\n\nThese rules come from Doramagic discovery, validation, or compilation pitfalls. The host AI must treat them as operating constraints, not general background notes.\n\n### Constraint 1: 社区讨论暴露的待验证问题：darkzodchi en X: \"Top MCP Servers That Turn Claude Into a Productivity Machine\" / X\n\n- Trigger: 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…\n- Host AI rule: Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。\n- Why it matters: 这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。\n- 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\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 2: 能力判断依赖假设\n\n- Trigger: README/documentation is current enough for a first validation pass.\n- Host AI rule: 将假设转成下游验证清单。\n- Why it matters: 假设不成立时，用户拿不到承诺的能力。\n- 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.\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 3: 社区讨论暴露的待验证问题：Adding Github MCP to Claude Code Error : r/ClaudeAI - Reddit\n\n- Trigger: 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 ...\n- Host AI rule: Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。\n- Why it matters: 这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。\n- 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\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 4: 社区讨论暴露的待验证问题：you need somewhere between 1-10 Claude skills depending on what ...\n\n- Trigger: 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 ...\n- Host AI rule: Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。\n- Why it matters: 这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。\n- Evidence: social_signal:x | ssig_504e57203f64433a83bf7ec96631f94c | https://x.com/Hesamation/status/2035136966719582695 | you need somewhere between 1-10 Claude skills depending on what ...\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 5: 维护活跃度未知\n\n- Trigger: 未记录 last_activity_observed。\n- Host AI rule: 补 GitHub 最近 commit、release、issue/PR 响应信号。\n- Why it matters: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 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\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 6: 下游验证发现风险项\n\n- Trigger: no_demo\n- Host AI rule: 进入安全/权限治理复核队列。\n- Why it matters: 下游已经要求复核，不能在页面中弱化。\n- 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\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 7: 存在评分风险\n\n- Trigger: no_demo\n- Host AI rule: 把风险写入边界卡，并确认是否需要人工复核。\n- Why it matters: 风险会影响是否适合普通用户安装。\n- 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\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 8: issue/PR 响应质量未知\n\n- Trigger: issue_or_pr_quality=unknown。\n- Host AI rule: 抽样最近 issue/PR，判断是否长期无人处理。\n- Why it matters: 用户无法判断遇到问题后是否有人维护。\n- 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\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n\n### Constraint 9: 发布节奏不明确\n\n- Trigger: release_recency=unknown。\n- Host AI rule: 确认最近 release/tag 和 README 安装命令是否一致。\n- Why it matters: 安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 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\n- Hard boundary: do not present this pitfall as solved, verified, or safe to ignore unless later validation evidence explicitly closes it.\n",
      "summary": "Context and operating boundaries for host AI agents.",
      "title": "AI Context Pack"
    },
    "boundary_risk_card": {
      "asset_id": "boundary_risk_card",
      "filename": "BOUNDARY_RISK_CARD.md",
      "markdown": "# Boundary & Risk Card\n\nProject: templatefoxpdf/mcp-server\n\n## Doramagic Trial Decision\n\nCurrent decision: it can enter pre-publication recommendation checks. First use should still start with least privilege, a temporary directory, and reversible configuration.\n\n## What The User Can Do Now\n\n- Read the Human Manual first to understand the project purpose and main workflows.\n- Use Prompt Preview for pre-install exploration; it validates interaction shape, not real execution.\n- Run official Quick Start commands only inside an isolated environment, not a primary setup.\n\n## Do Not Do Yet\n\n- Do not treat Prompt Preview as a real project execution result.\n- Do not treat metadata-only validation as sandbox installation validation.\n- Do not describe unverified capabilities as supported, working, or safe to install.\n- Do not provide production data, private files, real secrets, or primary host configuration on first trial.\n\n## Pre-Install Checklist\n\n- Host AI match: mcp_host\n- Official installation entry status: official entry point found\n- Isolated temporary directory, temporary host, or container validation: required\n- Configuration rollback path: required\n- API keys, network access, file access, or host configuration changes: treat as high risk until confirmed\n- Installation command, actual output, and failure logs: must be recorded\n\n## Current Blockers\n\n- No blockers.\n\n## Project-Specific Pitfalls\n\n- 社区讨论暴露的待验证问题：darkzodchi en X: \"Top MCP Servers That Turn Claude Into a Productivity Machine\" / X (medium): 这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。 Suggested check: Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。\n- 能力判断依赖假设 (medium): 假设不成立时，用户拿不到承诺的能力。 Suggested check: 将假设转成下游验证清单。\n- 社区讨论暴露的待验证问题：Adding Github MCP to Claude Code Error : r/ClaudeAI - Reddit (medium): 这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。 Suggested check: Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。\n- 社区讨论暴露的待验证问题：you need somewhere between 1-10 Claude skills depending on what ... (medium): 这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。 Suggested check: Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。\n- 维护活跃度未知 (medium): 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。 Suggested check: 补 GitHub 最近 commit、release、issue/PR 响应信号。\n\n## Risk And Permission Notes\n\n- no_demo: medium\n\n## Evidence Gaps\n\n- No structured evidence gaps are currently visible.\n",
      "summary": "Installation, permission, validation, and pre-recommendation risks.",
      "title": "Boundary & Risk Card"
    },
    "human_manual": {
      "asset_id": "human_manual",
      "filename": "HUMAN_MANUAL.md",
      "markdown": "# https://github.com/TemplateFoxPDF/mcp-server Project Manual\n\nGenerated on: 2026-05-22 15:16:53 UTC\n\n## Table of Contents\n\n- [Introduction](#page-introduction)\n- [Project Structure](#page-project-structure)\n- [Transport Modes](#page-transport-modes)\n- [Server Initialization](#page-server-initialization)\n- [PDF Generation Tools](#page-pdf-generation-tools)\n- [Template Management Tools](#page-template-management-tools)\n- [Account Management Tools](#page-account-management-tools)\n- [API Client](#page-api-client)\n- [Installation and Setup](#page-installation)\n- [Docker Deployment](#page-docker-deployment)\n\n<a id='page-introduction'></a>\n\n## Introduction\n\n### Related Pages\n\nRelated topics: [Project Structure](#page-project-structure), [PDF Generation Tools](#page-pdf-generation-tools), [Installation and Setup](#page-installation)\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following source files were used to generate this page:\n\n- [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n- [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n- [src/tools.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n- [src/api-client.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n- [src/index.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n</details>\n\n# Introduction\n\nTemplateFox 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]()\n\n## Overview\n\nThe 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]()\n\n### Core Functionality\n\nThe server exposes eight primary tools that cover the complete PDF generation workflow:\n\n| Tool | Purpose |\n|------|---------|\n| `generate_pdf` | Synchronous PDF generation from templates |\n| `generate_pdf_async` | Asynchronous PDF generation with job queuing |\n| `get_pdf_job_status` | Poll status of async generation jobs |\n| `list_pdf_jobs` | List and filter async job history |\n| `list_templates` | Discover available PDF templates |\n| `get_template_fields` | Retrieve template variable definitions |\n| `get_account_info` | Check account credits and status |\n| `list_transactions` | View credit transaction history |\n\nSource: [README.md]()\n\n## Architecture\n\nThe server follows a modular architecture with clear separation of concerns across three main source files.\n\n### Component Overview\n\n```mermaid\ngraph TD\n    A[\"AI Assistant<br/>(Claude, Cursor, Windsurf)\"] --> B[\"MCP Client\"]\n    B --> C[\"TemplateFox MCP Server\"]\n    C --> D[\"API Client<br/>(api-client.ts)\"]\n    C --> E[\"Tools Registry<br/>(tools.ts)\"]\n    D --> F[\"TemplateFox API<br/>api.templatefox.com\"]\n    E --> D\n    \n    subgraph \"Transport Modes\"\n        G[\"StdioServerTransport<br/>(Local/CLI)\"]\n        H[\"StreamableHTTPServerTransport<br/>(HTTP/Cloud)\"]\n    end\n    \n    C --> G\n    C --> H\n```\n\n### File Structure\n\n| File | Responsibility |\n|------|----------------|\n| `src/index.ts` | Server initialization, transport configuration, HTTP middleware |\n| `src/tools.ts` | MCP tool definitions using Zod schemas for validation |\n| `src/api-client.ts` | HTTP request handling, API key management, AsyncLocalStorage context |\n\nSource: [src/index.ts:1-60](), [src/tools.ts:1-50](), [src/api-client.ts:1-35]()\n\n## Transport Modes\n\nThe server supports two distinct transport mechanisms, automatically selected based on environment configuration.\n\n### Standard I/O Mode (Default)\n\nThe 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]()\n\n```mermaid\ngraph LR\n    A[\"AI Assistant\"] -->|\"stdio\"| B[\"StdioServerTransport\"]\n    B --> C[\"McpServer Instance\"]\n    C --> D[\"Tool Handler\"]\n    D --> E[\"TemplateFox API\"]\n```\n\n**Activation:**\n```bash\nnpx -y @templatefox/mcp-server\n```\n\n### HTTP Mode (Cloud/Remote)\n\nThe StreamableHTTPServerTransport enables remote deployments and cloud hosting. This mode activates when the `PORT` environment variable is set. Source: [src/index.ts:21-33]()\n\n**Activation:**\n```bash\nPORT=8080 TEMPLATEFOX_API_KEY=sk_your_key node dist/index.js\n```\n\n**Remote Endpoint:**\n```\nhttps://mcp-server-599407781746.us-central1.run.app/mcp\n```\n\nSource: [README.md]()\n\n## API Key Management\n\nThe server implements a dual-layer API key resolution strategy to support both local and HTTP transport modes.\n\n```mermaid\ngraph TD\n    A[\"API Request\"] --> B{Transport Type}\n    B -->|HTTP| C[\"Extract from Headers\"]\n    B -->|Stdio| D[\"Read from Environment\"]\n    C --> E{\"Key Present?\"}\n    D --> E\n    E -->|Yes| F[\"AsyncLocalStorage Context\"]\n    E -->|No| G[\"Throw Error\"]\n    F --> H[\"API Client\"]\n    G --> I[\"401 Unauthorized\"]\n```\n\n### Key Resolution Priority\n\n1. **HTTP Mode**: Per-request API key from `Authorization: Bearer` or `x-api-key` header via AsyncLocalStorage\n2. **Stdio Mode**: Environment variable `TEMPLATEFOX_API_KEY`\n\nSource: [src/api-client.ts:14-28]()\n\n### AsyncLocalStorage Context\n\nThe 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]()\n\n```typescript\nconst apiKeyStore = new AsyncLocalStorage<string>();\n\nexport function runWithApiKey<T>(apiKey: string, fn: () => T): T {\n  return apiKeyStore.run(apiKey, fn);\n}\n```\n\n## Tool Registration\n\nTools are registered using the `@modelcontextprotocol/sdk` package with Zod schema validation for all input parameters. Source: [src/tools.ts:1-10]()\n\n### Tool Configuration Pattern\n\nEach tool follows a consistent registration pattern:\n\n```typescript\nserver.tool(\n  \"tool_name\",                    // Tool identifier\n  \"Description text\",            // Human-readable description\n  { /* Zod schema */ },          // Input validation\n  { /* Hints */ },               // Read/destructive hints\n  async (params) => { ... }      // Handler function\n);\n```\n\n### Tool Hints\n\n| Hint | Description |\n|------|-------------|\n| `readOnlyHint: true` | Read-only operation (GET requests) |\n| `destructiveHint: false` | Non-destructive operation |\n\nSource: [src/tools.ts:50-60]()\n\n## Server Configuration\n\n### Environment Variables\n\n| Variable | Required | Default | Description |\n|----------|----------|---------|-------------|\n| `TEMPLATEFOX_API_KEY` | Yes (Stdio) | - | API key starting with `sk_` |\n| `TEMPLATEFOX_BASE_URL` | No | `https://api.templatefox.com` | Override API base URL |\n| `PORT` | No | - | Enable HTTP mode when set |\n\nSource: [README.md](), [src/api-client.ts:6]()\n\n### HTTP Server Middleware\n\nWhen running in HTTP mode, the server configures Express with CORS and JSON parsing middleware:\n\n```typescript\nconst app = express();\napp.use(cors());\napp.use(express.json());\n```\n\n**Endpoints:**\n\n| Endpoint | Method | Purpose |\n|----------|--------|---------|\n| `/health` | GET | Health check with version info |\n| `/mcp` | POST | MCP request handling |\n| `/mcp` | GET/DELETE | Method not allowed (405) |\n\nSource: [src/index.ts:27-45]()\n\n## Package Metadata\n\n| Property | Value |\n|----------|-------|\n| **Package Name** | `@templatefox/mcp-server` |\n| **Version** | `1.10.1` |\n| **Node.js Requirement** | `>=18.0.0` |\n| **License** | MIT |\n| **MCP Name** | `io.github.TemplateFoxPDF/mcp-server` |\n\nSource: [package.json:1-25]()\n\n### Core Dependencies\n\n| Package | Version | Purpose |\n|---------|---------|---------|\n| `@modelcontextprotocol/sdk` | `^1.29.0` | MCP protocol implementation |\n| `express` | `^5.2.1` | HTTP server framework |\n| `cors` | `^2.8.6` | Cross-origin resource sharing |\n\nSource: [package.json:26-32]()\n\n## Quick Start Workflow\n\n```mermaid\ngraph TD\n    A[\"Configure MCP Client\"] --> B[\"Add to Claude Desktop config\"]\n    A --> C[\"Or use claude mcp add command\"]\n    B --> D[\"Set TEMPLATEFOX_API_KEY\"]\n    C --> D\n    D --> E[\"Ask AI to generate PDF\"]\n    E --> F[\"list_templates\"]\n    F --> G[\"get_template_fields\"]\n    G --> H[\"generate_pdf\"]\n    H --> I[\"Return download URL\"]\n```\n\nExample AI prompt:\n> \"List my PDF templates and generate an invoice using the Invoice Template with customer name 'John Doe' and amount 150.00\"\n\nSource: [README.md]()\n\n## Next Steps\n\nFor detailed information about specific features, refer to:\n\n- **Tool Reference**: Detailed documentation for each MCP tool\n- **API Client**: HTTP request handling and authentication\n- **Deployment**: Cloud Run and Docker deployment configurations\n\n---\n\n<a id='page-project-structure'></a>\n\n## Project Structure\n\n### Related Pages\n\nRelated topics: [Introduction](#page-introduction), [Server Initialization](#page-server-initialization), [API Client](#page-api-client)\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following source files were used to generate this page:\n\n- [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n- [src/index.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n- [src/tools.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n- [src/api-client.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n- [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n</details>\n\n# Project Structure\n\nThe 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.\n\n## Repository Overview\n\nThe 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.\n\n| Property | Value |\n|----------|-------|\n| **Package Name** | `@templatefox/mcp-server` |\n| **Version** | 1.10.1 |\n| **License** | MIT |\n| **Node.js Requirement** | >=18.0.0 |\n| **Module Type** | ESM (ECMAScript Modules) |\n| **MCP SDK Version** | ^1.29.0 |\n| Source: [package.json:1-18](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json) |\n\n## Directory Structure\n\n```\nmcp-server/\n├── src/\n│   ├── index.ts        # Main entry point with transport handling\n│   ├── tools.ts        # MCP tool definitions\n│   └── api-client.ts   # API communication layer\n├── dist/               # Compiled JavaScript output\n├── package.json        # Package configuration\n├── tsconfig.json        # TypeScript configuration\n├── Dockerfile           # Container deployment\n└── README.md            # Documentation\n```\n\n## Source Code Architecture\n\n### Core Components Overview\n\n```mermaid\ngraph TD\n    A[MCP Client<br/>Claude/Cursor] -->|JSON-RPC| B[Transport Layer]\n    B --> C{Mode Detection}\n    C -->|No PORT env| D[StdioServerTransport]\n    C -->|PORT defined| E[StreamableHTTPServerTransport]\n    D --> F[McpServer Instance]\n    E --> G[Express HTTP Server]\n    G --> F\n    F --> H[registerTools]\n    H --> I[API Client]\n    I --> J[TemplateFox API]\n    J -->|PDF/Response| I\n    I --> F\n    F --> B\n```\n\n### Entry Point (`src/index.ts`)\n\nThe main entry point handles dual-mode operation based on environment configuration:\n\n**Key Responsibilities:**\n- Initialize the McpServer instance with name and version\n- Detect transport mode via the `PORT` environment variable\n- Set up Express server with CORS for HTTP mode\n- Extract API keys from request headers for per-request authentication\n\n| Transport Mode | Trigger | Use Case |\n|----------------|---------|----------|\n| **Stdio** | No `PORT` variable | Local AI assistant integration |\n| **HTTP** | `PORT` defined | Cloud Run, remote deployments |\n\nSource: [src/index.ts:1-28](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n#### HTTP Transport Configuration\n\n```typescript\nconst port = process.env.PORT ? parseInt(process.env.PORT, 10) : undefined;\n\nif (port) {\n  // HTTP mode: Streamable HTTP transport\n  const app = express();\n  app.use(cors());\n  app.use(express.json());\n  // ... route handlers\n}\n```\n\nSource: [src/index.ts:24-32](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n#### API Key Extraction\n\nThe HTTP transport extracts API keys from incoming requests using two methods:\n\n| Header | Format | Priority |\n|--------|--------|----------|\n| `Authorization` | `Bearer sk_xxx` | Primary |\n| `x-api-key` | `sk_xxx` | Fallback |\n\nSource: [src/index.ts:47-53](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n### API Client (`src/api-client.ts`)\n\nThe API client module handles all communication with the TemplateFox API endpoint at `https://api.templatefox.com`.\n\n#### API Key Management Strategy\n\n```mermaid\ngraph TD\n    A[apiRequest called] --> B{AsyncLocalStorage<br/>has key?}\n    B -->|Yes| C[Return context key]\n    B -->|No| D{Environment<br/>TEMPLATEFOX_API_KEY?}\n    D -->|Yes| E[Return env key]\n    D -->|No| F[Throw Error]\n    C --> G[Make API Request]\n    E --> G\n    F --> H[Error: API key required]\n```\n\nThe client implements a two-tier API key resolution strategy:\n\n1. **Per-request context** via `AsyncLocalStorage` (HTTP transport mode)\n2. **Environment variable fallback** (`TEMPLATEFOX_API_KEY`) for stdio mode\n\nSource: [src/api-client.ts:1-31](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n\n#### Request Building\n\nThe `apiRequest` function constructs HTTP requests with the following components:\n\n| Component | Value |\n|-----------|-------|\n| **Base URL** | `TEMPLATEFOX_BASE_URL` or `https://api.templatefox.com` |\n| **Method** | GET or POST |\n| **Authentication** | `x-api-key` header |\n| **Content-Type** | `application/json` (for POST) |\n| **Accept** | `application/json` |\n\nSource: [src/api-client.ts:49-78](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n\n### MCP Tools (`src/tools.ts`)\n\nThe tools module defines all MCP tools exposed to AI assistants. Each tool corresponds to a TemplateFox API endpoint.\n\n#### Tool Categories\n\n| Category | Tools | Operations |\n|----------|-------|------------|\n| **PDF Generation** | `generate_pdf`, `generate_pdf_async` | Create PDFs synchronously or asynchronously |\n| **Job Management** | `get_pdf_job_status`, `list_pdf_jobs` | Monitor and list async jobs |\n| **Templates** | `list_templates`, `get_template_fields` | Discover available templates |\n| **Account** | `get_account_info`, `list_transactions` | View credits and history |\n\nSource: [src/tools.ts:1-200](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n#### Tool Definition Pattern\n\nEach MCP tool follows this schema:\n\n```typescript\nserver.tool(\n  \"tool_name\",                    // Tool identifier\n  \"Description for AI assistant\", // Human-readable description\n  { /* Zod schema parameters */}, // Input validation schema\n  { /* Hints */ },                // Read/destructive hints\n  async ({ params }) => {          // Handler function\n    const url = \"/v1/endpoint\";\n    const result = await apiRequest(\"METHOD\", url, body);\n    return {\n      content: [{ type: \"text\", text: JSON.stringify(result.data) }],\n      isError: !result.ok,\n    };\n  }\n);\n```\n\nSource: [src/tools.ts:7-22](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n#### Available Tools Reference\n\n| Tool | HTTP Method | Endpoint | Credits | Async Support |\n|------|-------------|----------|---------|---------------|\n| `generate_pdf` | POST | `/v1/pdf/create` | 1 | No |\n| `generate_pdf_async` | POST | `/v1/pdf/create-async` | 1 | Yes |\n| `get_pdf_job_status` | GET | `/v1/pdf/jobs/{job_id}` | 0 | - |\n| `list_pdf_jobs` | GET | `/v1/pdf/jobs` | 0 | - |\n| `list_templates` | GET | `/v1/templates` | 0 | - |\n| `get_template_fields` | GET | `/v1/templates/{id}/fields` | 0 | - |\n| `get_account_info` | GET | `/v1/account` | 0 | - |\n| `list_transactions` | GET | `/v1/account/transactions` | 0 | - |\n\nSource: [src/tools.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n## Build Configuration\n\n### Package Scripts\n\n| Script | Command | Purpose |\n|--------|---------|---------|\n| `build` | `tsc` | Compile TypeScript to JavaScript |\n| `start` | `node dist/index.js` | Run the compiled server |\n\nSource: [package.json:12-15](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n\n### Dependencies\n\n#### Production Dependencies\n\n| Package | Version | Purpose |\n|---------|---------|---------|\n| `@modelcontextprotocol/sdk` | ^1.29.0 | MCP protocol implementation |\n| `express` | ^5.2.1 | HTTP server framework |\n| `cors` | ^2.8.6 | Cross-origin resource sharing |\n\nSource: [package.json:16-20](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n\n#### Development Dependencies\n\n| Package | Version | Purpose |\n|---------|---------|---------|\n| `typescript` | ^5.8.0 | TypeScript compiler |\n| `@types/node` | ^22.0.0 | Node.js type definitions |\n| `@types/express` | ^5.0.0 | Express type definitions |\n| `@types/cors` | ^2.8.0 | CORS type definitions |\n\nSource: [package.json:21-25](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n\n### Binary Configuration\n\nThe package exposes a CLI binary for global installation:\n\n```json\n{\n  \"bin\": {\n    \"templatefox-mcp-server\": \"./dist/index.js\"\n  }\n}\n```\n\nSource: [package.json:9-11](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n\n## Deployment Modes\n\n### Stdio Mode (Local)\n\nDefault mode for AI assistant integration via npx:\n\n```bash\nnpx -y @templatefox/mcp-server\n```\n\nRequires `TEMPLATEFOX_API_KEY` environment variable.\n\nSource: [README.md:15-24](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n### HTTP Mode (Cloud)\n\nEnabled by setting the `PORT` environment variable:\n\n```bash\nPORT=8080 TEMPLATEFOX_API_KEY=sk_your_key node dist/index.js\n```\n\n| Endpoint | Method | Purpose |\n|----------|--------|---------|\n| `/health` | GET | Health check |\n| `/mcp` | POST | MCP request handler |\n\nSource: [src/index.ts:35-39](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n### Docker Deployment\n\nThe project includes Dockerfile support for containerized deployments:\n\n```bash\ndocker build -t templatefox-mcp .\ndocker run -p 8080:8080 templatefox-mcp\n```\n\nSource: [README.md:66-70](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n## Data Flow Architecture\n\n### Synchronous PDF Generation\n\n```mermaid\nsequenceDiagram\n    participant AI as AI Assistant\n    participant MCP as MCP Server\n    participant API as TemplateFox API\n    AI->>MCP: generate_pdf(template_id, data)\n    MCP->>MCP: apiRequest(POST, /v1/pdf/create)\n    MCP->>API: HTTP POST with JSON body\n    API->>API: Generate PDF\n    API-->>MCP: PDF URL or binary\n    MCP-->>AI: JSON-RPC response\n```\n\n### Asynchronous PDF Generation\n\n```mermaid\nsequenceDiagram\n    participant AI as AI Assistant\n    participant MCP as MCP Server\n    participant API as TemplateFox API\n    participant Webhook as Webhook URL\n    AI->>MCP: generate_pdf_async(template_id, data, webhook_url)\n    MCP->>MCP: apiRequest(POST, /v1/pdf/create-async)\n    MCP->>API: HTTP POST\n    API-->>MCP: { job_id, status: \"pending\" }\n    MCP-->>AI: job_id\n    loop Poll or Webhook\n        API->>Webhook: POST when completed\n        alt Polling Mode\n            AI->>MCP: get_pdf_job_status(job_id)\n            MCP-->>AI: { status, pdf_url }\n        end\n    end\n```\n\n## Configuration Reference\n\n### Environment Variables\n\n| Variable | Required | Default | Description |\n|----------|----------|---------|-------------|\n| `TEMPLATEFOX_API_KEY` | Yes (stdio) / No (HTTP) | - | API key starting with `sk_` |\n| `TEMPLATEFOX_BASE_URL` | No | `https://api.templatefox.com` | Override API base URL |\n| `PORT` | No | undefined | Enable HTTP mode on specified port |\n\nSource: [README.md:42-47](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n## Workflow Example\n\nA typical AI-assisted PDF generation workflow:\n\n```mermaid\ngraph TD\n    A[User Request] --> B[list_templates]\n    B --> C[Choose Template]\n    C --> D[get_template_fields]\n    D --> E[Prepare Data]\n    E --> F{Size/Complexity}\n    F -->|Small Doc| G[generate_pdf]\n    F -->|Large Doc| H[generate_pdf_async]\n    H --> I[Poll get_pdf_job_status]\n    I -->|Not Ready| I\n    I -->|Ready| J[Return PDF URL]\n    G --> J\n```\n\nSource: [README.md:71-79](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n## Keywords and Metadata\n\nThe package includes comprehensive metadata for discoverability:\n\n```json\n{\n  \"keywords\": [\n    \"mcp\",\n    \"mcp-server\", \n    \"model-context-protocol\",\n    \"pdf\",\n    \"templatefox\",\n    \"pdf-generation\",\n    \"ai\",\n    \"claude\"\n  ],\n  \"mcpName\": \"io.github.TemplateFoxPDF/mcp-server\"\n}\n```\n\nSource: [package.json:26-34](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n\n---\n\n<a id='page-transport-modes'></a>\n\n## Transport Modes\n\n### Related Pages\n\nRelated topics: [Server Initialization](#page-server-initialization), [Installation and Setup](#page-installation), [Docker Deployment](#page-docker-deployment)\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following source files were used to generate this page:\n\n- [src/index.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n- [src/api-client.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n- [src/tools.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n- [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n- [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n</details>\n\n# Transport Modes\n\nThe 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.\n\n## Overview\n\nThe server implements the Model Context Protocol (MCP) and can operate in two primary transport configurations:\n\n| Transport Mode | Use Case | Deployment | Default |\n|---------------|----------|------------|---------|\n| **Stdio** | Local development, desktop AI assistants | Same machine as client | Yes |\n| **Streamable HTTP** | Remote/cloud deployments, web services | Separate server | No (when PORT is set) |\n\nSource: [src/index.ts:1-50](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[MCP Client] -->|Transport Choice| B\n    B{Transport Mode?}\n    B -->|stdio| C[StdioServerTransport]\n    B -->|http| D[StreamableHTTPServerTransport]\n    C --> E[Local Process Communication]\n    D --> F[Express.js HTTP Server]\n    F --> G[/health Endpoint]\n    F --> H[/mcp Endpoint]\n    E --> I[McpServer Instance]\n    F --> I\n```\n\n## Stdio Transport Mode\n\nStdio (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.\n\n### Configuration\n\nStdio mode requires no additional configuration beyond the essential environment variable:\n\n```bash\nTEMPLATEFOX_API_KEY=sk_your_api_key_here npx -y @templatefox/mcp-server\n```\n\nOr with a global installation:\n\n```bash\ntemplatefox-mcp-server\n```\n\n### How It Works\n\n1. 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)\n\n2. A `StdioServerTransport` is created to handle stdio communication. Source: [src/index.ts:30](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n3. 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)\n\n### API Key Handling in Stdio Mode\n\nIn 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.\n\nThe `getApiKey()` function in `api-client.ts` implements a two-tier lookup:\n\n```typescript\nfunction getApiKey(): string {\n  // 1. Per-request key from HTTP transport (AsyncLocalStorage)\n  const contextKey = apiKeyStore.getStore();\n  if (contextKey) return contextKey;\n\n  // 2. Environment variable (stdio mode)\n  const key = process.env.TEMPLATEFOX_API_KEY;\n  if (!key) {\n    throw new Error(\n      \"TEMPLATEFOX_API_KEY is required. \" +\n      \"Set it as an environment variable or pass it via the Authorization header. \" +\n      \"Get your API key at https://app.templatefox.com/dashboard/api-keys\"\n    );\n  }\n  return key;\n}\n```\n\nSource: [src/api-client.ts:44-60](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n\n## Streamable HTTP Transport Mode\n\nHTTP 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.\n\n### Enabling HTTP Mode\n\nHTTP mode is activated by setting the `PORT` environment variable:\n\n```bash\nPORT=8080 TEMPLATEFOX_API_KEY=sk_your_key node dist/index.js\n```\n\nSource: [src/index.ts:34](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n### Express.js Server Setup\n\nThe HTTP transport relies on Express.js for request handling:\n\n```typescript\nconst express = (await import(\"express\")).default;\nconst cors = (await import(\"cors\")).default;\n\nconst app = express();\napp.use(cors());\napp.use(express.json());\n```\n\nSource: [src/index.ts:36-40](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n### Endpoints\n\n| Endpoint | Method | Purpose |\n|----------|--------|---------|\n| `/health` | GET | Health check for monitoring |\n| `/mcp` | POST | MCP request handling |\n\nSource: [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)\n\n### Health Check Endpoint\n\n```typescript\napp.get(\"/health\", (_req, res) => {\n  res.json({ status: \"ok\", version: SERVER_VERSION });\n});\n```\n\nSource: [src/index.ts:42-44](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n### MCP Request Handling\n\nThe `/mcp` POST endpoint extracts the API key from request headers, creates a new server instance, and routes the request through the streamable HTTP transport:\n\n```typescript\napp.post(\"/mcp\", async (req, res) => {\n  const authHeader = req.headers.authorization;\n  const apiKey = authHeader?.startsWith(\"Bearer \")\n    ? authHeader.slice(7)\n    : (req.headers[\"x-api-key\"] as string | undefined);\n```\n\nSource: [src/index.ts:70-75](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n### API Key Extraction in HTTP Mode\n\nHTTP transport supports two header formats for API key authentication:\n\n| Header Format | Example |\n|--------------|---------|\n| `Authorization: Bearer <key>` | `Authorization: Bearer sk_your_api_key_here` |\n| `x-api-key: <key>` | `x-api-key: sk_your_api_key_here` |\n\nSource: [src/index.ts:70-75](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n### Per-Request API Key Handling\n\nHTTP mode uses `AsyncLocalStorage` to maintain per-request API key context:\n\n```typescript\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nconst apiKeyStore = new AsyncLocalStorage<string>();\n\nexport function runWithApiKey<T>(apiKey: string, fn: () => T): T {\n  return apiKeyStore.run(apiKey, fn);\n}\n```\n\nSource: [src/api-client.ts:11-17](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n\nThis 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.\n\n### Session Management\n\nThe HTTP transport is configured with stateless request handling:\n\n```typescript\nconst transport = new StreamableHTTPServerTransport({\n  sessionIdGenerator: undefined,\n});\n```\n\nSource: [src/index.ts:80-82](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\nSetting `sessionIdGenerator` to `undefined` disables session tracking, making each request independent.\n\n### Error Handling\n\nHTTP mode includes comprehensive error responses:\n\n```typescript\n// 401 Unauthorized - Missing API key\nres.status(401).json({\n  jsonrpc: \"2.0\",\n  error: {\n    code: -32001,\n    message: \"API key required. Pass it via Authorization: Bearer <key> or x-api-key header.\",\n  },\n  id: null,\n});\n\n// 405 Method Not Allowed\nres.status(405).json({\n  jsonrpc: \"2.0\",\n  error: { code: -32000, message: \"Method not allowed. Use POST for MCP requests.\" },\n  id: null,\n});\n\n// 500 Internal Server Error\nres.status(500).json({\n  jsonrpc: \"2.0\",\n  error: { code: -32603, message: \"Internal server error\" },\n  id: null,\n});\n```\n\nSource: [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)\n\n### Method Restriction\n\nThe server explicitly blocks inappropriate HTTP methods on the MCP endpoint:\n\n```typescript\napp.get(\"/mcp\", (_req, res) => {\n  res.status(405).json({...});\n});\n\napp.delete(\"/mcp\", (_req, res) => {\n  res.status(405).json({...});\n});\n```\n\nSource: [src/index.ts:90-99](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n## Deployment Options\n\n### Docker Deployment\n\nFor containerized HTTP deployments:\n\n```bash\ndocker build -t templatefox-mcp .\ndocker run -p 8080:8080 templatefox-mcp\n```\n\nSource: [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n### Cloud Run Deployment\n\nThe server is pre-deployed and accessible at:\n\n```\nhttps://mcp-server-599407781746.us-central1.run.app/mcp\n```\n\nSource: [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n### Claude Desktop Configuration\n\n```json\n{\n  \"mcpServers\": {\n    \"templatefox\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@templatefox/mcp-server\"],\n      \"env\": {\n        \"TEMPLATEFOX_API_KEY\": \"sk_your_api_key_here\"\n      }\n    }\n  }\n}\n```\n\nSource: [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n### Claude Code Configuration\n\n```bash\nclaude mcp add templatefox -- npx -y @templatefox/mcp-server\n```\n\nSource: [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n## Environment Variables\n\n| Variable | Required | Default | Description |\n|----------|----------|---------|-------------|\n| `TEMPLATEFOX_API_KEY` | Yes | - | API key (starts with `sk_`) |\n| `TEMPLATEFOX_BASE_URL` | No | `https://api.templatefox.com` | Override API base URL |\n| `PORT` | No | - | Enables HTTP mode when set |\n\nSource: [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)\n\n## Dependencies\n\nThe transport implementation relies on these packages:\n\n| Package | Version | Purpose |\n|---------|---------|---------|\n| `@modelcontextprotocol/sdk` | ^1.29.0 | MCP protocol and transport classes |\n| `express` | ^5.2.1 | HTTP server framework |\n| `cors` | ^2.8.6 | Cross-origin resource sharing |\n\nSource: [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n\n## Comparison: Stdio vs HTTP\n\n| Aspect | Stdio | Streamable HTTP |\n|--------|-------|-----------------|\n| **Startup** | Immediate | Requires PORT variable |\n| **Connection** | Process-based | TCP/HTTP |\n| **API Key Source** | Environment variable | Per-request header |\n| **Scalability** | Single client | Multiple clients |\n| **Use Case** | Desktop integrations | Cloud deployments |\n| **Session Support** | Native (process) | Stateless (no sessions) |\n| **AsyncLocalStorage** | Not used | Used for per-request context |\n\n## Request Flow Comparison\n\n```mermaid\ngraph LR\n    subgraph \"Stdio Mode\"\n        A1[Stdin Request] --> B1[StdioServerTransport]\n        B1 --> C1[McpServer]\n        C1 --> D1[Stdout Response]\n    end\n    \n    subgraph \"HTTP Mode\"\n        A2[HTTP POST] --> B2[Express App]\n        B2 --> C2[StreamableHTTPServerTransport]\n        C2 --> D2[McpServer]\n        D2 --> E2[HTTP Response]\n    end\n```\n\n## Tool Registration\n\nRegardless of transport mode, all tools are registered identically:\n\n```typescript\nexport function registerTools(server: McpServer): void {\n  // Tools are registered once at server creation\n  server.tool(\"generate_pdf\", {...});\n  server.tool(\"generate_pdf_async\", {...});\n  server.tool(\"get_pdf_job_status\", {...});\n  server.tool(\"list_pdf_jobs\", {...});\n  server.tool(\"list_templates\", {...});\n  server.tool(\"get_template_fields\", {...});\n  server.tool(\"get_account_info\", {...});\n  server.tool(\"list_transactions\", {...});\n}\n```\n\nSource: [src/tools.ts:3-20](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n---\n\n<a id='page-server-initialization'></a>\n\n## Server Initialization\n\n### Related Pages\n\nRelated topics: [Transport Modes](#page-transport-modes), [PDF Generation Tools](#page-pdf-generation-tools)\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following source files were used to generate this page:\n\n- [src/index.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n- [src/tools.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n- [src/api-client.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n- [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n- [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n</details>\n\n# Server Initialization\n\n## Overview\n\nThe 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.\n\nSource: [src/index.ts:1-5](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n```typescript\n#!/usr/bin/env node\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { StreamableHTTPServerTransport } from \"@modelcontextprotocol/sdk/server/streamableHttp.js\";\nimport { registerTools } from \"./tools.js\";\nimport { runWithApiKey } from \"./api-client.js\";\n```\n\n## Transport Modes\n\nThe server supports two distinct transport mechanisms determined by environment configuration.\n\n| Mode | Trigger | Use Case |\n|------|---------|----------|\n| **Stdio** | No `PORT` env var | Local CLI usage via npx, Claude Desktop |\n| **HTTP** | `PORT` env var set | Remote/cloud deployment, self-hosted |\n\nSource: [src/index.ts:25-26](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n```typescript\nconst port = process.env.PORT ? parseInt(process.env.PORT, 10) : undefined;\n```\n\n### Stdio Transport Mode\n\nWhen running without a `PORT` environment variable, the server uses stdio (standard input/output) transport, which is the default mode for local AI assistant integration.\n\nSource: [src/index.ts:54-56](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n```typescript\n// stdio mode: default for npx / local usage\nconst server = createServer();\nconst transport = new StdioServerTransport();\nawait server.connect(transport);\n```\n\n### HTTP Transport Mode\n\nWhen `PORT` is defined, the server launches an Express.js application with CORS support and Streamable HTTP transport for remote deployments.\n\nSource: [src/index.ts:28-31](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n```typescript\n// HTTP mode: Streamable HTTP transport (stateless, for Cloud Run / remote)\nconst express = (await import(\"express\")).default;\nconst cors = (await import(\"cors\")).default;\n\nconst app = express();\napp.use(cors());\napp.use(express.json());\n```\n\n## Server Creation Flow\n\nThe `createServer()` function initializes the MCP server with version metadata and registers all available tools.\n\n```mermaid\ngraph TD\n    A[Start] --> B[Check PORT Environment Variable]\n    B -->|PORT defined| C[HTTP Mode Setup]\n    B -->|No PORT| D[Stdio Mode Setup]\n    C --> E[Create Express App]\n    E --> F[Configure CORS & JSON middleware]\n    F --> G[Setup Health Endpoint /mcp]\n    G --> H[Start Listening]\n    D --> I[createServer]\n    I --> J[Register Tools via registerTools]\n    J --> K[new McpServer]\n    K --> L[new StdioServerTransport]\n    L --> M[Connect and Await Requests]\n```\n\n### Server Instance Creation\n\nSource: [src/index.ts:10-18](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n```typescript\nfunction createServer(): McpServer {\n  const server = new McpServer({\n    name: SERVER_NAME,\n    version: SERVER_VERSION,\n  });\n  registerTools(server);\n  return server;\n}\n```\n\nThe server configuration constants are defined as:\n\n| Constant | Value | Purpose |\n|----------|-------|---------|\n| `SERVER_NAME` | `\"templatefox\"` | Server identifier for MCP protocol |\n| `SERVER_VERSION` | `\"1.8.2\"` | Semantic version of the server |\n\nSource: [src/index.ts:6-8](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n## HTTP Server Endpoints\n\nThe HTTP transport mode exposes two endpoints:\n\n### Health Check Endpoint\n\nSource: [src/index.ts:33-36](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n```typescript\napp.get(\"/health\", (_req, res) => {\n  res.json({ status: \"ok\", version: SERVER_VERSION });\n});\n```\n\n### MCP Request Endpoint\n\nSource: [src/index.ts:38-68](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n```typescript\napp.post(\"/mcp\", async (req, res) => {\n  // Extract API key from Authorization header or x-api-key\n  const authHeader = req.headers.authorization;\n  const apiKey = authHeader?.startsWith(\"Bearer \")\n    ? authHeader.slice(7)\n    : (req.headers[\"x-api-key\"] as string | undefined);\n\n  if (!apiKey) {\n    res.status(401).json({\n      jsonrpc: \"2.0\",\n      error: {\n        code: -32001,\n        message: \"API key required. Pass it via Authorization: Bearer <key> or x-api-key header.\",\n      },\n      id: null,\n    });\n    return;\n  }\n  // ... server initialization continues\n});\n```\n\n### Error Handling Endpoints\n\nThe server returns 405 Method Not Allowed for incorrect HTTP methods:\n\n```typescript\napp.get(\"/mcp\", (_req, res) => {\n  res.status(405).json({\n    jsonrpc: \"2.0\",\n    error: { code: -32000, message: \"Method not allowed. Use POST for MCP requests.\" },\n    id: null,\n  });\n});\n\napp.delete(\"/mcp\", (_req, res) => {\n  res.status(405).json({\n    jsonrpc: \"2.0\",\n    error: { code: -32000, message: \"Method not allowed. Sessions are not supported.\" },\n    id: null,\n  });\n});\n```\n\nSource: [src/index.ts:70-82](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n## API Key Handling\n\nThe server implements a multi-tier API key resolution strategy:\n\n```mermaid\ngraph LR\n    A[API Key Request] --> B{HTTP Transport?}\n    B -->|Yes| C[Extract from Header]\n    B -->|No| D{Check Environment}\n    C --> E[AsyncLocalStorage Context]\n    D -->|Found| F[Use TEMPLATEFOX_API_KEY]\n    D -->|Not Found| G[Throw Error]\n    E --> H[API Request with Key]\n    F --> H\n```\n\n### Key Resolution Priority\n\nSource: [src/api-client.ts:28-43](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n\n```typescript\nfunction getApiKey(): string {\n  // 1. Per-request key from HTTP transport (AsyncLocalStorage)\n  const contextKey = apiKeyStore.getStore();\n  if (contextKey) return contextKey;\n\n  // 2. Environment variable (stdio mode)\n  const key = process.env.TEMPLATEFOX_API_KEY;\n  if (!key) {\n    throw new Error(\n      \"TEMPLATEFOX_API_KEY is required. \" +\n      \"Set it as an environment variable or pass it via the Authorization header. \" +\n      \"Get your API key at https://app.templatefox.com/dashboard/api-keys\"\n    );\n  }\n  return key;\n}\n```\n\n### HTTP Transport Key Injection\n\nFor HTTP mode, the API key is extracted from request headers and stored in AsyncLocalStorage context:\n\nSource: [src/index.ts:40-43](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n```typescript\nconst authHeader = req.headers.authorization;\nconst apiKey = authHeader?.startsWith(\"Bearer \")\n  ? authHeader.slice(7)\n  : (req.headers[\"x-api-key\"] as string | undefined);\n```\n\nThe key is then passed to the request handler:\n\nSource: [src/index.ts:53-58](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n```typescript\nconst server = createServer();\nconst transport = new StreamableHTTPServerTransport({\n  sessionIdGenerator: undefined,\n});\nawait server.connect(transport);\nawait runWithApiKey(apiKey, () => transport.handleRequest(req, res, req.body));\n```\n\n### AsyncLocalStorage Context\n\nSource: [src/api-client.ts:20-26](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n\n```typescript\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nconst apiKeyStore = new AsyncLocalStorage<string>();\n\n/**\n * Run a function with a specific API key in context.\n * Used by HTTP transport to pass per-request API keys.\n */\nexport function runWithApiKey<T>(apiKey: string, fn: () => T): T {\n  return apiKeyStore.run(apiKey, fn);\n}\n```\n\n## Tool Registration\n\nAll MCP tools are registered during server initialization via the `registerTools()` function.\n\nSource: [src/tools.ts:4-7](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n```typescript\nexport function registerTools(server: McpServer): void {\n  // Tool registrations...\n}\n```\n\n### Available Tools\n\n| Tool | Description | Credits | Read-Only |\n|------|-------------|---------|-----------|\n| `generate_pdf` | Generate PDF from template | 1 | No |\n| `generate_pdf_async` | Queue async PDF generation | 1 | No |\n| `get_pdf_job_status` | Check async job status | - | Yes |\n| `list_pdf_jobs` | List async jobs | - | Yes |\n| `list_templates` | List available templates | - | Yes |\n| `get_template_fields` | Get template field definitions | - | Yes |\n| `get_account_info` | Get account and credit info | - | Yes |\n| `list_transactions` | View credit transaction history | - | Yes |\n\nSource: [src/tools.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n## Configuration Options\n\n### Environment Variables\n\n| Variable | Required | Default | Description |\n|----------|----------|---------|-------------|\n| `TEMPLATEFOX_API_KEY` | Yes (Stdio) / Via Header (HTTP) | - | API key starting with `sk_` |\n| `TEMPLATEFOX_BASE_URL` | No | `https://api.templatefox.com` | Override API base URL |\n| `PORT` | No | - | Enable HTTP mode on specified port |\n\nSource: [src/api-client.ts:15](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n\n### Build and Runtime Scripts\n\nSource: [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n\n| Script | Command | Purpose |\n|--------|---------|---------|\n| `build` | `tsc` | Compile TypeScript to JavaScript |\n| `start` | `node dist/index.js` | Run the compiled server |\n\n### Server Binaries\n\n```json\n{\n  \"bin\": {\n    \"templatefox-mcp-server\": \"./dist/index.js\"\n  }\n}\n```\n\n## Startup Sequence\n\n```mermaid\nsequenceDiagram\n    participant CLI as CLI/npm\n    participant Server as MCP Server\n    participant MCP as MCP SDK\n    participant Express as Express App\n\n    CLI->>Server: node dist/index.js\n    Server->>Server: Check PORT env var\n    alt Stdio Mode\n        Server->>MCP: createServer()\n        MCP->>Server: McpServer instance\n        Server->>MCP: registerTools()\n        Server->>MCP: new StdioServerTransport()\n        Server->>MCP: connect(transport)\n        Note over Server,MCP: Await stdio requests\n    else HTTP Mode\n        Server->>Express: new Express()\n        Express->>Server: app configured\n        Server->>Server: app.listen(port)\n        Note over Server,Express: /health, /mcp endpoints ready\n    end\n```\n\n## Error Handling\n\n### HTTP Mode Error Handler\n\nSource: [src/index.ts:59-67](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n```typescript\n} catch (error) {\n  if (!res.headersSent) {\n    res.status(500).json({\n      jsonrpc: \"2.0\",\n      error: { code: -32603, message: \"Internal server error\" },\n      id: null,\n    });\n  }\n}\n```\n\n### Session Cleanup\n\nSource: [src/index.ts:55-57](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n```typescript\nres.on(\"close\", () => {\n  transport.close();\n  server.close();\n});\n```\n\n## Version Information\n\nThe server reports its version through:\n\n1. **HTTP Health Endpoint**: Returns `{ status: \"ok\", version: SERVER_VERSION }`\n2. **Package Version**: `1.10.1` in package.json\n3. **Runtime Version**: `1.8.2` defined as `SERVER_VERSION` constant\n\nSource: [package.json:4](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\nSource: [src/index.ts:8](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n## Dependencies\n\nThe server initialization relies on these core dependencies:\n\n| Package | Version | Purpose |\n|---------|---------|---------|\n| `@modelcontextprotocol/sdk` | `^1.29.0` | MCP protocol implementation |\n| `express` | `^5.2.1` | HTTP server framework |\n| `cors` | `^2.8.6` | Cross-origin resource sharing |\n| `typescript` | `^5.8.0` | TypeScript compilation |\n| `@types/node` | `^22.0.0` | Node.js type definitions |\n\nSource: [package.json:24-35](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n\n---\n\n<a id='page-pdf-generation-tools'></a>\n\n## PDF Generation Tools\n\n### Related Pages\n\nRelated topics: [Template Management Tools](#page-template-management-tools), [Account Management Tools](#page-account-management-tools), [API Client](#page-api-client)\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following source files were used to generate this page:\n\n- [src/tools.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n- [src/api-client.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n- [src/index.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n- [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n- [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n</details>\n\n# PDF Generation Tools\n\nThe 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.\n\n## Architecture Overview\n\nThe 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:\n\n```mermaid\ngraph TD\n    A[\"AI Assistant<br/>(Claude, Cursor, Windsurf)\"] --> B[\"MCP SDK<br/>StdioServerTransport / StreamableHTTPServerTransport\"]\n    B --> C[\"MCP Server (index.ts)\"]\n    C --> D[\"Tool Registry (tools.ts)\"]\n    D --> E[\"API Client (api-client.ts)\"]\n    E --> F[\"TemplateFox API<br/>https://api.templatefox.com\"]\n    \n    style A fill:#e1f5fe\n    style F fill:#fff3e0\n    style D fill:#f3e5f5\n```\n\nThe server supports two transport modes:\n- **Stdio Transport**: Default mode for local/cli usage via `npx`\n- **Streamable HTTP Transport**: For cloud deployments and remote access\n\nSource: [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)\n\n## Tool Registration\n\nAll 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.\n\n```mermaid\ngraph LR\n    A[\"registerTools(server)\"] --> B[\"generate_pdf\"]\n    A --> C[\"generate_pdf_async\"]\n    A --> D[\"get_pdf_job_status\"]\n    A --> C --> D\n    A --> E[\"list_pdf_jobs\"]\n    A --> F[\"list_templates\"]\n    A --> G[\"get_template_fields\"]\n    A --> H[\"get_account_info\"]\n    A --> I[\"list_transactions\"]\n```\n\nSource: [src/tools.ts:1-10](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n## Core PDF Generation Tools\n\n### generate_pdf\n\nThe `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.\n\n**Tool Name:** `generate_pdf`  \n**API Endpoint:** `POST /v1/pdf/create`  \n**Cost:** 1 credit per generation  \n**Source:** [src/tools.ts:20-60](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n#### Input Parameters\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `template_id` | string | Yes | Template short ID (12 characters) |\n| `data` | Record<string, unknown> | Yes | Key-value data to render in the template. Keys must match template variables. |\n| `export_type` | enum | No | Export format: `url` (upload to CDN, return URL) or `binary` (return raw PDF bytes) |\n| `expiration` | number | No | URL expiration in seconds (60-604800, i.e., 1 min to 7 days). Only applies to `url` export type. |\n| `filename` | string | No | Custom filename for the PDF (without .pdf extension). Defaults to 'document'. |\n| `store_s3` | boolean | No | Upload to configured S3 bucket instead of CDN |\n| `s3_filepath` | string | No | Custom path prefix in S3 bucket |\n| `s3_bucket` | string | No | Override the default S3 bucket configured in S3 integration |\n| `pdf_variant` | enum | No | Standards-compliant PDF variant: `pdf/a-1b`, `pdf/a-2b`, or `pdf/a-3b` |\n| `version` | string | No | Optional version tag (e.g., `prod`) or version number (e.g., `3`). Uses current draft if omitted. |\n\n#### PDF/A Variants\n\nThe tool supports generating PDF/A variants for archival and compliance purposes:\n\n| Variant | Use Case |\n|---------|----------|\n| `pdf/a-1b` | Basic archival compliance |\n| `pdf/a-2b` | Most common for archival compliance |\n| `pdf/a-3b` | Required for documents with file attachments (e.g., Factur-X, ZUGFeRD invoices) |\n\n#### Hints\n\n| Hint | Value | Description |\n|------|-------|-------------|\n| `destructiveHint` | false | Indicates this tool does not delete data |\n\nSource: [src/tools.ts:20-60](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n### generate_pdf_async\n\nThe `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.\n\n**Tool Name:** `generate_pdf_async`  \n**API Endpoint:** `POST /v1/pdf/create-async`  \n**Cost:** 1 credit per generation  \n**Source:** [src/tools.ts:65-120](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n#### Input Parameters\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `template_id` | string | Yes | Template short ID (12 characters) |\n| `data` | Record<string, unknown> | Yes | Key-value data to render in the template |\n| `export_type` | enum | No | Export format. Currently only `url` is supported for async. |\n| `expiration` | number | No | URL expiration in seconds (60-604800). Default: 86400 (24 hours) |\n| `filename` | string | No | Custom filename for the PDF |\n| `store_s3` | boolean | No | Upload to configured S3 bucket |\n| `s3_filepath` | string | No | Custom path prefix in S3 bucket |\n| `s3_bucket` | string | No | Override the default S3 bucket |\n| `webhook_url` | string | No | HTTPS URL to receive POST notification when job completes or fails |\n| `webhook_secret` | string | No | Secret for HMAC-SHA256 signing of webhook payloads (minimum 16 characters) |\n| `pdf_variant` | enum | No | PDF/A variant for compliance |\n| `version` | string | No | Version tag or number |\n\n#### Async Workflow\n\n```mermaid\ngraph TD\n    A[\"Call generate_pdf_async\"] --> B[\"Receive job_id (UUID)\"]\n    B --> C[\"Poll with get_pdf_job_status\"]\n    C --> D{\"Status = completed?\"}\n    D -->|Yes| E[\"Receive PDF URL\"]\n    D -->|No| F[\"Continue polling\"]\n    F --> C\n    D -->|Failed| G[\"Handle error\"]\n    B --> H[\"Optional: Configure webhook\"]\n    H --> I[\"Receive POST to webhook_url\"]\n    I --> E\n```\n\nSource: [src/tools.ts:65-120](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n## Job Management Tools\n\n### get_pdf_job_status\n\nThe `get_pdf_job_status` tool retrieves the current status of an asynchronous PDF generation job.\n\n**Tool Name:** `get_pdf_job_status`  \n**API Endpoint:** `GET /v1/pdf/jobs/{job_id}`  \n**Source:** [src/tools.ts:125-145](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n#### Input Parameters\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `job_id` | string | Yes | Async job ID (UUID returned by the create-async endpoint) |\n\n#### Job Status Values\n\n| Status | Description |\n|--------|-------------|\n| `pending` | Job is queued but not yet processing |\n| `processing` | PDF generation is in progress |\n| `completed` | PDF generation finished successfully; PDF URL available |\n| `failed` | PDF generation failed; check error details |\n\n#### Hints\n\n| Hint | Value | Description |\n|------|-------|-------------|\n| `readOnlyHint` | true | This tool only reads data, no modifications |\n\nSource: [src/tools.ts:125-145](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n### list_pdf_jobs\n\nThe `list_pdf_jobs` tool retrieves a list of asynchronous PDF generation jobs with pagination and status filtering.\n\n**Tool Name:** `list_pdf_jobs`  \n**API Endpoint:** `GET /v1/pdf/jobs`  \n**Source:** [src/tools.ts:150-175](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n#### Input Parameters\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `limit` | number | No | Maximum number of results to return |\n| `offset` | number | No | Number of results to skip (for pagination) |\n| `status` | enum | No | Filter jobs by status: `pending`, `processing`, `completed`, or `failed` |\n\n#### Hints\n\n| Hint | Value | Description |\n|------|-------|-------------|\n| `readOnlyHint` | true | This tool only reads data |\n\nSource: [src/tools.ts:150-175](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n## Template Discovery Tools\n\n### list_templates\n\nThe `list_templates` tool returns all available PDF templates in the user's account.\n\n**Tool Name:** `list_templates`  \n**API Endpoint:** `GET /v1/templates`  \n**Source:** [src/tools.ts:180-200](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n#### Hints\n\n| Hint | Value | Description |\n|------|-------|-------------|\n| `readOnlyHint` | true | This tool only reads data |\n\n#### Usage Pattern\n\n```mermaid\ngraph LR\n    A[\"list_templates\"] --> B[\"Get list of templates<br/>with IDs and names\"]\n    B --> C[\"Select template_id\"]\n    C --> D[\"get_template_fields\"]\n    D --> E[\"Discover required fields\"]\n    E --> F[\"generate_pdf with complete data\"]\n```\n\nSource: [src/tools.ts:180-200](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n### get_template_fields\n\nThe `get_template_fields` tool retrieves the dynamic fields defined for a specific template, including field names, types, and whether they are required.\n\n**Tool Name:** `get_template_fields`  \n**API Endpoint:** `GET /v1/templates/{template_id}/fields`  \n**Source:** [src/tools.ts:205-230](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n#### Input Parameters\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `template_id` | string | Yes | Template short ID (12 characters) |\n\n#### Hints\n\n| Hint | Value | Description |\n|------|-------|-------------|\n| `readOnlyHint` | true | This tool only reads data |\n\n#### Return Value\n\nThe tool returns field metadata including:\n- Field names (must match when providing data to `generate_pdf`)\n- Field types (string, number, boolean, etc.)\n- Required vs optional fields\n\nSource: [src/tools.ts:205-230](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n## Account Management Tools\n\n### get_account_info\n\nThe `get_account_info` tool retrieves account information including remaining credits and email address.\n\n**Tool Name:** `get_account_info`  \n**API Endpoint:** `GET /v1/account`  \n**Source:** [src/tools.ts:235-255](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n#### Hints\n\n| Hint | Value | Description |\n|------|-------|-------------|\n| `readOnlyHint` | true | This tool only reads data |\n\nSource: [src/tools.ts:235-255](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n### list_transactions\n\nThe `list_transactions` tool provides access to credit transaction history, showing PDF generations, purchases, and refunds.\n\n**Tool Name:** `list_transactions`  \n**API Endpoint:** `GET /v1/account/transactions`  \n**Source:** [src/tools.ts:260-285](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n#### Input Parameters\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `limit` | number | No | Number of records to return (1-1000) |\n| `offset` | number | No | Number of records to skip for pagination |\n\n#### Hints\n\n| Hint | Value | Description |\n|------|-------|-------------|\n| `readOnlyHint` | true | This tool only reads data |\n\nSource: [src/tools.ts:260-285](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n## API Client Integration\n\nThe tools utilize the `apiRequest` function from `src/api-client.ts` to communicate with the TemplateFox API. The API client handles:\n\n- **Base URL Configuration**: Defaults to `https://api.templatefox.com`, configurable via `TEMPLATEFOX_BASE_URL` environment variable\n- **API Key Management**: Supports two modes:\n  1. Per-request key from HTTP transport via `AsyncLocalStorage`\n  2. Environment variable `TEMPLATEFOX_API_KEY` for stdio mode\n- **Request Building**: Constructs URLs with query parameters and request bodies\n- **Response Handling**: Parses JSON or text responses based on `Content-Type` header\n\n```mermaid\ngraph TD\n    A[\"Tool Handler\"] --> B[\"apiRequest(method, path, body, query)\"]\n    B --> C[\"Construct URL with BASE_URL + path\"]\n    C --> D[\"Add query parameters if provided\"]\n    D --> E[\"Set headers<br/>x-api-key, Content-Type, Accept\"]\n    E --> F[\"Make fetch request\"]\n    F --> G[\"Parse response by Content-Type\"]\n    G --> H[\"Return ApiResponse<br/>{ok, status, data}\"]\n```\n\n### API Key Resolution\n\nThe `getApiKey()` function implements a fallback chain for API key resolution:\n\n1. **Per-request key from HTTP transport** - Uses `AsyncLocalStorage` context\n2. **Environment variable** - Falls back to `TEMPLATEFOX_API_KEY`\n3. **Error** - Throws if no key is available\n\n```mermaid\ngraph TD\n    A[\"getApiKey called\"] --> B{\"AsyncLocalStorage<br/>has context?\"}\n    B -->|Yes| C[\"Return context key\"]\n    B -->|No| D{\"TEMPLATEFOX_API_KEY<br/>env var set?\"}\n    D -->|Yes| E[\"Return env var value\"]\n    D -->|No| F[\"Throw error:<br/>API key required\"]\n```\n\nSource: [src/api-client.ts:1-75](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n\n## Configuration\n\n### Environment Variables\n\n| Variable | Required | Default | Description |\n|----------|----------|---------|-------------|\n| `TEMPLATEFOX_API_KEY` | Yes (stdio mode) | - | API key starting with `sk_` |\n| `TEMPLATEFOX_BASE_URL` | No | `https://api.templatefox.com` | Override API base URL |\n| `PORT` | No | - | Enable HTTP mode when set |\n\n### HTTP Transport Configuration\n\nWhen running in HTTP mode (by setting `PORT`), the server requires API key authentication via HTTP headers:\n\n| Header | Format | Example |\n|--------|--------|---------|\n| `Authorization` | `Bearer <key>` | `Authorization: Bearer sk_abc123...` |\n| `x-api-key` | `<key>` | `x-api-key: sk_abc123...` |\n\nSource: [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)\n\n## Complete Tool Summary\n\n| Tool | Name | Purpose | Read-Only |\n|------|------|---------|-----------|\n| `generate_pdf` | Synchronous PDF Generation | Create PDF from template with data | No |\n| `generate_pdf_async` | Async PDF Generation | Queue PDF job with webhook support | No |\n| `get_pdf_job_status` | Job Status Check | Poll async job status by ID | Yes |\n| `list_pdf_jobs` | Job List | List jobs with pagination/filtering | Yes |\n| `list_templates` | Template Discovery | List available templates | Yes |\n| `get_template_fields` | Field Discovery | Get template variable definitions | Yes |\n| `get_account_info` | Account Info | View credits and account details | Yes |\n| `list_transactions` | Transaction History | View credit transaction log | Yes |\n\nSource: [src/tools.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n## Version Information\n\n| Component | Version |\n|-----------|---------|\n| Package | `@templatefox/mcp-server` |\n| Server | 1.8.2 |\n| Package.json | 1.10.1 |\n| MCP SDK | ^1.29.0 |\n| Node.js Requirement | >=18.0.0 |\n\nSource: [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)\n\n---\n\n<a id='page-template-management-tools'></a>\n\n## Template Management Tools\n\n### Related Pages\n\nRelated topics: [PDF Generation Tools](#page-pdf-generation-tools), [Introduction](#page-introduction)\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following source files were used to generate this page:\n\n- [src/tools.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n- [src/api-client.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n- [src/index.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n- [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n- [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n</details>\n\n# Template Management Tools\n\n## Overview\n\nTemplate 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.\n\nThe 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.\n\n## Architecture\n\n### System Components\n\nThe template management system integrates several components within the MCP server architecture:\n\n| Component | File | Responsibility |\n|-----------|------|----------------|\n| MCP Server | `src/index.ts` | Initializes the MCP server and registers tools |\n| Tool Registration | `src/tools.ts` | Defines and registers template management tools |\n| API Client | `src/api-client.ts` | Handles HTTP communication with TemplateFox API |\n\n### Data Flow\n\n```mermaid\ngraph TD\n    A[AI Assistant] -->|MCP Protocol| B[MCP Server]\n    B -->|registerTools| C[Template Management Tools]\n    C -->|apiRequest| D[TemplateFox API]\n    D -->|Template List| B\n    B -->|Formatted Response| A\n    \n    E[TemplateFox API] -->|Field Schema| B\n```\n\n### API Communication\n\nThe 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.\n\nSource: [src/api-client.ts:8-9](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts#L8-L9)\nSource: [src/api-client.ts:19-35](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts#L19-L35)\n\n## Available Tools\n\n### list_templates\n\nThe `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.\n\n**Tool Definition:**\n\n```typescript\nserver.tool(\n  \"list_templates\",\n  \"List all available PDF templates. Returns template IDs and names. Use this to discover which templates are available before generating a PDF.\",\n  {},\n  { readOnlyHint: true },\n  async () => {\n    const url = \"/v1/templates\";\n    const result = await apiRequest(\"GET\", url);\n    return {\n      content: [{ type: \"text\", text: JSON.stringify(result.data, null, 2) }],\n      isError: !result.ok,\n    };\n  },\n);\n```\n\nSource: [src/tools.ts:115-128](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts#L115-L128)\n\n**Parameters:** None required\n\n**Return Value:** JSON object containing an array of template objects with their IDs and names\n\n**Characteristics:**\n\n- Read-only operation (marked with `readOnlyHint: true`)\n- Calls the `/v1/templates` endpoint via GET request\n- No pagination parameters supported\n\n### get_template_fields\n\nThe `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.\n\n**Tool Definition:**\n\n```typescript\nserver.tool(\n  \"get_template_fields\",\n  \"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.\",\n  {\n    template_id: z.string().describe(\"Template short ID (12 characters)\"),\n  },\n  { readOnlyHint: true },\n  async ({ template_id }) => {\n    const url = `/v1/templates/${template_id}/fields`;\n    const result = await apiRequest(\"GET\", url);\n    return {\n      content: [{ type: \"text\", text: JSON.stringify(result.data, null, 2) }],\n      isError: !result.ok,\n    };\n  },\n);\n```\n\nSource: [src/tools.ts:130-145](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts#L130-L145)\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `template_id` | string | Yes | Template short ID (12 characters) |\n\n**Return Value:** JSON object containing field names, types, and required status for each dynamic field in the template\n\n**Characteristics:**\n\n- Read-only operation (marked with `readOnlyHint: true`)\n- Calls the `/v1/templates/{template_id}/fields` endpoint via GET request\n- Template ID must be a valid 12-character string\n\n## Integration with PDF Generation\n\nTemplate management tools are integral to the PDF generation workflow. The typical workflow follows a discovery-then-generation pattern:\n\n```mermaid\ngraph LR\n    A[list_templates] -->|Discover template ID| B[get_template_fields]\n    B -->|Understand required fields| C[generate_pdf]\n    B -->|Job ID returned| D[generate_pdf_async]\n    D -->|Poll status| E[get_pdf_job_status]\n```\n\n### Workflow Example\n\n1. **List Available Templates**: Use `list_templates` to retrieve all templates and identify the desired template by name or ID\n2. **Inspect Template Schema**: Use `get_template_fields` with the template ID to understand required data fields, their types, and which are mandatory\n3. **Generate PDF**: Pass the template ID and properly structured data object to `generate_pdf` for synchronous generation or `generate_pdf_async` for background processing\n\nSource: [README.md:58-70](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md#L58-L70)\n\n## Configuration Requirements\n\n### Environment Variables\n\n| Variable | Required | Default | Description |\n|----------|----------|---------|-------------|\n| `TEMPLATEFOX_API_KEY` | Yes | — | API key starting with `sk_` |\n| `TEMPLATEFOX_BASE_URL` | No | `https://api.templatefox.com` | Override API base URL |\n\nSource: [README.md:38-47](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md#L38-L47)\n\n### Transport Modes\n\nThe MCP server supports two transport modes, both of which work with template management tools:\n\n| Mode | Command | Use Case |\n|------|---------|----------|\n| Stdio | `npx -y @templatefox/mcp-server` | Local desktop integration (Claude Desktop, Cursor, Windsurf) |\n| HTTP | `PORT=8080` + server binary | Remote/cloud deployments |\n\nFor HTTP transport, API key authentication is handled via HTTP headers:\n\n```\nAuthorization: Bearer sk_your_api_key_here\n```\n\nor:\n\n```\nx-api-key: sk_your_api_key_here\n```\n\nSource: [README.md:45-56](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md#L45-L56)\nSource: [src/index.ts:32-50](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts#L32-L50)\n\n## Tool Registration Mechanism\n\nThe `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`:\n\n```typescript\nfunction createServer(): McpServer {\n  const server = new McpServer({\n    name: SERVER_NAME,\n    version: SERVER_VERSION,\n  });\n  registerTools(server);\n  return server;\n}\n```\n\nSource: [src/index.ts:16-23](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts#L16-L23)\n\nEach tool is registered using the `@modelcontextprotocol/sdk` library's `server.tool()` method with the following signature:\n\n```typescript\nserver.tool(\n  name: string,           // Tool identifier\n  description: string,    // Human-readable description for AI\n  inputSchema: object,    // Zod schema for validation\n  annotations: object,    // Tool hints (readOnlyHint, destructiveHint)\n  handler: function       // Async function executing the tool\n)\n```\n\nSource: [src/tools.ts:4-11](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts#L4-L11)\n\n## Error Handling\n\nTemplate management tools return errors when API requests fail. The `isError` flag is set based on the `response.ok` property from the API client:\n\n```typescript\nreturn {\n  content: [{ type: \"text\", text: JSON.stringify(result.data, null, 2) }],\n  isError: !result.ok,\n};\n```\n\nSource: [src/tools.ts:123-128](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts#L123-L128)\n\nCommon error scenarios include:\n\n| Error | Cause | Resolution |\n|-------|-------|------------|\n| 401 Unauthorized | Missing or invalid API key | Ensure `TEMPLATEFOX_API_KEY` is set correctly |\n| 404 Not Found | Invalid template ID | Verify the template ID is 12 characters and exists |\n| 500 Internal Server Error | TemplateFox API issue | Check TemplateFox status page |\n\n## Package Information\n\n| Property | Value |\n|----------|-------|\n| Package Name | `@templatefox/mcp-server` |\n| Version | `1.10.1` |\n| License | MIT |\n| Node Engine | `>=18.0.0` |\n| SDK | `@modelcontextprotocol/sdk` ^1.29.0 |\n\nSource: [package.json:2-10](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json#L2-L10)\n\n---\n\n<a id='page-account-management-tools'></a>\n\n## Account Management Tools\n\n### Related Pages\n\nRelated topics: [PDF Generation Tools](#page-pdf-generation-tools)\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following source files were used to generate this page:\n\n- [src/tools.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n- [src/api-client.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n- [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n- [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n</details>\n\n# Account Management Tools\n\nThe 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.\n\n## Overview\n\nAccount Management Tools provide read-only access to account metadata and transaction history. They allow users to:\n\n- Check remaining credits and account details\n- Review credit transaction history with pagination support\n- Monitor PDF generation usage patterns\n\nAll 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.\n\n```mermaid\ngraph TD\n    A[MCP Client] -->|get_account_info| B[Account Info Tool]\n    A -->|list_transactions| C[Transaction History Tool]\n    B -->|GET /v1/account| D[TemplateFox API]\n    C -->|GET /v1/account/transactions| D\n    D -->|JSON Response| A\n```\n\n## Available Tools\n\n| Tool Name | Description | Endpoint |\n|-----------|-------------|----------|\n| `get_account_info` | Retrieve account details and remaining credits | `GET /v1/account` |\n| `list_transactions` | Fetch paginated credit transaction history | `GET /v1/account/transactions` |\n\n## get_account_info\n\nRetrieves comprehensive account information including remaining credits, email address, and account status. This tool is useful for checking resource availability before initiating PDF generation operations.\n\n### Parameters\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| (none) | - | - | This tool accepts no input parameters |\n\n### Implementation\n\n```typescript\n// getAccount -> get_account_info\nserver.tool(\n  \"get_account_info\",\n  \"Get account information including remaining credits and email address.\",\n  {\n  },\n  { readOnlyHint: true },\n  async () => {\n    const url = \"/v1/account\";\n    const result = await apiRequest(\"GET\", url);\n    return {\n      content: [{ type: \"text\", text: JSON.stringify(result.data, null, 2) }],\n      isError: !result.ok,\n    };\n  },\n);\n```\n\n*Source: [src/tools.ts:104-119](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)*\n\n### Response Format\n\nThe tool returns a JSON object containing account metadata. The typical response structure includes:\n\n- **credits**: Remaining credit balance for PDF generation\n- **email**: Account email address\n- **account status**: Active/suspended state\n\n### Use Cases\n\n- Verify sufficient credits before batch PDF generation\n- Display account dashboard information to users\n- Check if account is active before processing requests\n\n## list_transactions\n\nRetrieves 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.\n\n### Parameters\n\n| Parameter | Type | Required | Default | Description |\n|-----------|------|----------|---------|-------------|\n| `limit` | number (integer) | No | - | Number of records to return (1-1000) |\n| `offset` | number (integer) | No | 0 | Number of records to skip for pagination |\n| `status` | enum | No | - | Filter by transaction status |\n\n### Implementation\n\n```typescript\n// listTransactions -> list_transactions\nserver.tool(\n  \"list_transactions\",\n  \"List credit transaction history showing PDF generations, purchases, and refunds. Supports pagination.\",\n  {\n    limit: z.number().int().min(1).max(1000).optional().describe(\"Number of records to return\"),\n    offset: z.number().int().min(0).optional().describe(\"Number of records to skip\"),\n  },\n  { readOnlyHint: true },\n  async ({ limit, offset }) => {\n    const url = \"/v1/account/transactions\";\n    const result = await apiRequest(\"GET\", url, undefined, { limit, offset });\n    return {\n      content: [{ type: \"text\", JSON.stringify(result.data, null, 2) }],\n      isError: !result.ok,\n    };\n  },\n);\n```\n\n*Source: [src/tools.ts:144-162](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)*\n\n### Pagination Behavior\n\nThe pagination implementation in `api-client.ts` processes query parameters and appends them to the request URL:\n\n```typescript\nif (query) {\n  for (const [key, value] of Object.entries(query)) {\n    if (value !== undefined && value !== null) {\n      url.searchParams.set(key, String(value));\n    }\n  }\n}\n```\n\n*Source: [src/api-client.ts:42-47](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)*\n\n### Response Format\n\nThe transactions endpoint returns an array of transaction objects with:\n\n- **type**: Transaction type (generation, purchase, refund)\n- **amount**: Credit amount (positive for additions, negative for usage)\n- **timestamp**: When the transaction occurred\n- **description**: Human-readable transaction description\n\n### Use Cases\n\n- Audit trail for compliance and reporting\n- Track monthly PDF generation costs\n- Identify refund transactions\n- Monitor credit usage patterns\n\n## API Key Handling\n\nAccount Management Tools require a valid API key for authentication. The MCP server supports two authentication modes:\n\n```mermaid\ngraph LR\n    A[Request] --> B{Transport Mode}\n    B -->|stdio| C[Environment Variable<br/>TEMPLATEFOX_API_KEY]\n    B -->|HTTP| D[Authorization Header<br/>or x-api-key]\n```\n\n### Stdio Mode (Environment Variable)\n\n```typescript\nconst key = process.env.TEMPLATEFOX_API_KEY;\nif (!key) {\n  throw new Error(\n    \"TEMPLATEFOX_API_KEY is required. \" +\n    \"Set it as an environment variable or pass it via the Authorization header.\"\n  );\n}\n```\n\n*Source: [src/api-client.ts:20-28](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)*\n\n### HTTP Mode (Request Headers)\n\nFor HTTP transport, the API key is extracted from request headers:\n\n```typescript\nconst authHeader = req.headers.authorization;\nconst apiKey = authHeader?.startsWith(\"Bearer \")\n  ? authHeader.slice(7)\n  : (req.headers[\"x-api-key\"] as string | undefined);\n```\n\n*Source: [src/index.ts:52-56](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)*\n\n## Configuration\n\n| Environment Variable | Required | Default | Description |\n|---------------------|----------|---------|-------------|\n| `TEMPLATEFOX_API_KEY` | Yes | - | API key starting with `sk_` |\n| `TEMPLATEFOX_BASE_URL` | No | `https://api.templatefox.com` | Override API base URL |\n\n*Source: [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)*\n\n## Error Handling\n\nBoth Account Management Tools include standardized error handling:\n\n```typescript\nreturn {\n  content: [{ type: \"text\", text: JSON.stringify(result.data, null, 2) }],\n  isError: !result.ok,\n};\n```\n\nThe `isError` flag is set based on the API response status, allowing MCP clients to handle errors appropriately. Common error scenarios include:\n\n- **401 Unauthorized**: Invalid or missing API key\n- **403 Forbidden**: API key lacks necessary permissions\n- **429 Too Many Requests**: Rate limit exceeded\n- **500 Internal Server Error**: TemplateFox API issues\n\n## Example Usage\n\n### Checking Account Credits\n\n```\nTool: get_account_info\n```\n\nResponse:\n```json\n{\n  \"credits\": 150,\n  \"email\": \"user@example.com\",\n  \"status\": \"active\"\n}\n```\n\n### Retrieving Transaction History\n\n```\nTool: list_transactions\nParameters: {\n  \"limit\": 10,\n  \"offset\": 0\n}\n```\n\nResponse:\n```json\n{\n  \"transactions\": [\n    { \"type\": \"generation\", \"amount\": -1, \"description\": \"Invoice Template\", \"timestamp\": \"2024-01-15T10:30:00Z\" },\n    { \"type\": \"purchase\", \"amount\": 100, \"description\": \"Credit pack purchase\", \"timestamp\": \"2024-01-10T08:00:00Z\" }\n  ],\n  \"total\": 2\n}\n```\n\n## Related Tools\n\n| Tool | Category | Purpose |\n|------|----------|---------|\n| `generate_pdf` | PDF Generation | Create PDFs (consumes credits) |\n| `generate_pdf_async` | PDF Generation | Async PDF creation with webhooks |\n| `list_templates` | Template Discovery | Browse available templates |\n| `get_template_fields` | Template Discovery | Get template field definitions |\n\n---\n\n<a id='page-api-client'></a>\n\n## API Client\n\n### Related Pages\n\nRelated topics: [PDF Generation Tools](#page-pdf-generation-tools)\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following source files were used to generate this page:\n\n- [src/api-client.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n- [src/tools.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n- [src/index.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n- [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n- [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n</details>\n\n# API Client\n\nThe 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.\n\n## Overview\n\nThe 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:\n\n- Establishing authenticated connections to the TemplateFox API\n- Managing API credentials from multiple sources (environment variables, per-request headers)\n- Serializing and sending HTTP requests with proper content types\n- Handling JSON responses and error states\n- Supporting both synchronous (stdio) and asynchronous (HTTP) transport modes\n\n**Base URL Configuration:**\n```typescript\nconst BASE_URL = process.env.TEMPLATEFOX_BASE_URL || \"https://api.templatefox.com\";\n```\nSource: [`src/api-client.ts:11`](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n\n## Architecture\n\n### Request Flow\n\n```mermaid\ngraph TD\n    A[Tool Call] --> B[registerTools in tools.ts]\n    B --> C[apiRequest function]\n    C --> D{Transport Mode?}\n    D -->|Stdio| E[getApiKey from env]\n    D -->|HTTP| F[runWithApiKey with AsyncLocalStorage]\n    E --> G[Fetch API call]\n    F --> G\n    G --> H[Parse Response]\n    H --> I[Return ApiResponse]\n```\n\n### Dual Transport Support\n\nThe API Client supports two distinct transport modes:\n\n| Transport Mode | Trigger | API Key Source | Use Case |\n|----------------|---------|-----------------|----------|\n| **Stdio** | No `PORT` env var | `process.env.TEMPLATEFOX_API_KEY` | Local Claude Desktop, npx usage |\n| **HTTP** | `PORT` env var set | Per-request Authorization header | Cloud Run, self-hosted, remote clients |\n\nSource: [`src/index.ts:22-23`](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n## Core Components\n\n### ApiResponse Interface\n\n```typescript\ninterface ApiResponse {\n  ok: boolean;\n  status: number;\n  data: unknown;\n}\n```\n\n| Property | Type | Description |\n|----------|------|-------------|\n| `ok` | `boolean` | Indicates if the HTTP response status was in the 2xx range |\n| `status` | `number` | HTTP status code from the API |\n| `data` | `unknown` | Parsed response body (JSON object or raw string) |\n\nSource: [`src/api-client.ts:58-62`](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n\n### The `apiRequest` Function\n\nThe central function for making API calls:\n\n```typescript\nexport async function apiRequest(\n  method: string,\n  path: string,\n  body?: Record<string, unknown>,\n  query?: Record<string, string | number | undefined>,\n): Promise<ApiResponse>\n```\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `method` | `string` | Yes | HTTP method (GET, POST, etc.) |\n| `path` | `string` | Yes | API endpoint path (e.g., `/v1/pdf/create`) |\n| `body` | `Record<string, unknown>` | No | JSON request body for POST requests |\n| `query` | `Record<string, string \\| number \\| undefined>` | No | Query string parameters |\n\n**Request Processing:**\n\n1. Constructs full URL by combining `BASE_URL` with the provided `path`\n2. Appends query parameters to URL\n3. Sets required headers including API key and Content-Type\n4. Executes fetch request\n5. Parses response based on Content-Type header\n\nSource: [`src/api-client.ts:64-101`](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n\n### API Key Management\n\n#### AsyncLocalStorage for Per-Request Keys\n\n```typescript\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nconst apiKeyStore = new AsyncLocalStorage<string>();\n```\n\nThe module uses Node.js `AsyncLocalStorage` to maintain per-request API key context in HTTP transport mode. This enables:\n\n- Stateless request handling (no session management required)\n- Isolation of API keys between concurrent requests\n- Clean middleware-style API key injection\n\nSource: [`src/api-client.ts:4,7`](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n\n#### The `runWithApiKey` Function\n\n```typescript\nexport function runWithApiKey<T>(apiKey: string, fn: () => T): T {\n  return apiKeyStore.run(apiKey, fn);\n}\n```\n\nWraps a function execution within a specific API key context. Used by the HTTP transport layer to inject the per-request API key.\n\nSource: [`src/api-client.ts:17-20`](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n\n#### The `getApiKey` Function\n\n```typescript\nfunction getApiKey(): string {\n  // 1. Per-request key from HTTP transport (AsyncLocalStorage)\n  const contextKey = apiKeyStore.getStore();\n  if (contextKey) return contextKey;\n\n  // 2. Environment variable (stdio mode)\n  const key = process.env.TEMPLATEFOX_API_KEY;\n  if (!key) {\n    throw new Error(\n      \"TEMPLATEFOX_API_KEY is required. \" +\n      \"Set it as an environment variable or pass it via the Authorization header. \" +\n      \"Get your API key at https://app.templatefox.com/dashboard/api-keys\"\n    );\n  }\n  return key;\n}\n```\n\n**Priority Order:**\n\n1. **Per-request key** from `AsyncLocalStorage` (HTTP transport mode)\n2. **Environment variable** `TEMPLATEFOX_API_KEY` (stdio transport mode)\n\nIf neither is available, throws a descriptive error with setup instructions.\n\nSource: [`src/api-client.ts:22-40`](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n\n## Usage in Tools\n\nAll MCP tools in `src/tools.ts` consume the API Client through `apiRequest`:\n\n```typescript\nimport { apiRequest } from \"./api-client.js\";\n\n// Example: List templates\nasync () => {\n  const url = \"/v1/templates\";\n  const result = await apiRequest(\"GET\", url);\n  return {\n    content: [{ type: \"text\", text: JSON.stringify(result.data, null, 2) }],\n    isError: !result.ok,\n  };\n}\n```\n\n**Tools Using the API Client:**\n\n| Tool | Method | Endpoint | Purpose |\n|------|--------|----------|---------|\n| `generate_pdf` | POST | `/v1/pdf/create` | Synchronous PDF generation |\n| `generate_pdf_async` | POST | `/v1/pdf/create-async` | Async PDF generation with webhooks |\n| `get_pdf_job_status` | GET | `/v1/pdf/jobs/{job_id}` | Check async job status |\n| `list_pdf_jobs` | GET | `/v1/pdf/jobs` | List all async jobs |\n| `list_templates` | GET | `/v1/templates` | List available templates |\n| `get_template_fields` | GET | `/v1/templates/{template_id}/fields` | Get template schema |\n| `get_account_info` | GET | `/v1/account` | Account and credit info |\n| `list_transactions` | GET | `/v1/account/transactions` | Credit transaction history |\n\nSource: [`src/tools.ts`](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n## HTTP Transport Integration\n\n### Request Handling in Express\n\n```typescript\napp.post(\"/mcp\", async (req, res) => {\n  const authHeader = req.headers.authorization;\n  const apiKey = authHeader?.startsWith(\"Bearer \")\n    ? authHeader.slice(7)\n    : (req.headers[\"x-api-key\"] as string | undefined);\n\n  if (!apiKey) {\n    res.status(401).json({\n      jsonrpc: \"2.0\",\n      error: {\n        code: -32001,\n        message: \"API key required. Pass it via Authorization: Bearer <key> or x-api-key header.\",\n      },\n      id: null,\n    });\n    return;\n  }\n\n  try {\n    const server = createServer();\n    const transport = new StreamableHTTPServerTransport({\n      sessionIdGenerator: undefined,\n    });\n    await server.connect(transport);\n    await runWithApiKey(apiKey, () => transport.handleRequest(req, res, req.body));\n  } catch (error) {\n    // Error handling\n  }\n});\n```\n\nSource: [`src/index.ts:47-82`](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n### Supported Authentication Headers\n\n| Header | Format | Example |\n|--------|--------|---------|\n| `Authorization` | `Bearer <api_key>` | `Authorization: Bearer sk_live_abc123...` |\n| `x-api-key` | `<api_key>` | `x-api-key: sk_live_abc123...` |\n\n## Configuration\n\n### Environment Variables\n\n| Variable | Required | Default | Description |\n|----------|----------|---------|-------------|\n| `TEMPLATEFOX_API_KEY` | Yes (Stdio) / No (HTTP) | - | API key starting with `sk_` |\n| `TEMPLATEFOX_BASE_URL` | No | `https://api.templatefox.com` | Override API base URL |\n| `PORT` | No | - | If set, enables HTTP transport mode |\n\nSource: [`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)\n\n## Dependencies\n\nThe API Client relies on these npm packages:\n\n| Package | Version | Purpose |\n|---------|---------|---------|\n| `@modelcontextprotocol/sdk` | `^1.29.0` | MCP server framework |\n| `express` | `^5.2.1` | HTTP server for remote transport |\n| `cors` | `^5.2.6` | CORS middleware for HTTP mode |\n\nSource: [`package.json`](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n\n## Error Handling\n\nThe 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:\n\n```typescript\nconst result = await apiRequest(\"GET\", url);\nreturn {\n  content: [{ type: \"text\", text: JSON.stringify(result.data, null, 2) }],\n  isError: !result.ok,\n};\n```\n\nThe response data typically contains error details from the TemplateFox API, including:\n\n- HTTP status codes\n- JSON-RPC error objects\n- Descriptive error messages\n\n## Health Check Endpoint\n\nWhen running in HTTP mode, a health check endpoint is available:\n\n```typescript\napp.get(\"/health\", (_req, res) => {\n  res.json({ status: \"ok\", version: SERVER_VERSION });\n});\n```\n\nThis endpoint does not require authentication and is suitable for load balancer health checks.\n\nSource: [`src/index.ts:35-38`](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n---\n\n<a id='page-installation'></a>\n\n## Installation and Setup\n\n### Related Pages\n\nRelated topics: [Docker Deployment](#page-docker-deployment), [Transport Modes](#page-transport-modes)\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following source files were used to generate this page:\n\n- [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n- [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n- [src/index.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n- [src/api-client.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n</details>\n\n# Installation and Setup\n\n## Overview\n\nThe 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.\n\nThe 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.\n\n**Source:** [README.md:1-5](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n## Prerequisites\n\n### System Requirements\n\n| Requirement | Specification |\n|-------------|---------------|\n| Node.js Version | `>= 18.0.0` |\n| Package Manager | npm, yarn, or pnpm |\n| Network Access | Outbound HTTPS to `api.templatefox.com` |\n\n**Source:** [package.json:17-19](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n\n### Required Credentials\n\nYou must obtain an API key from the TemplateFox dashboard before using the server:\n\n1. Visit [app.templatefox.com/dashboard/api-keys](https://app.templatefox.com/dashboard/api-keys)\n2. Generate a new API key (keys start with `sk_`)\n3. Store the key securely for configuration\n\n**Source:** [README.md:33-35](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n## Installation Methods\n\n### Method 1: Direct npx (Recommended for Claude Desktop)\n\nNo upfront installation required. Claude Desktop automatically downloads and runs the package.\n\n**Source:** [README.md:21-28](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n### Method 2: Global npm Installation\n\nFor command-line usage or custom MCP configurations:\n\n```bash\nnpm install -g @templatefox/mcp-server\n```\n\nAfter global installation, use the CLI directly:\n\n```bash\ntemplatefox-mcp-server\n```\n\n**Source:** [README.md:29-31](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n### Method 3: Docker Deployment\n\nBuild and run the server in a container:\n\n```bash\ndocker build -t templatefox-mcp .\ndocker run -p 8080:8080 templatefox-mcp\n```\n\n**Source:** [README.md:66-67](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n## Claude Desktop Configuration\n\n### Configuration File Location\n\n| Operating System | Config File Path |\n|-----------------|------------------|\n| macOS | `~/Library/Application Support/Claude/claude_desktop_config.json` |\n| Windows | `%APPDATA%\\Claude\\claude_desktop_config.json` |\n| Linux | `~/.config/Claude/claude_desktop_config.json` |\n\n**Source:** [README.md:14-16](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n### Configuration Format\n\nAdd the following to your Claude Desktop config:\n\n```json\n{\n  \"mcpServers\": {\n    \"templatefox\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@templatefox/mcp-server\"],\n      \"env\": {\n        \"TEMPLATEFOX_API_KEY\": \"sk_your_api_key_here\"\n      }\n    }\n  }\n}\n```\n\n**Source:** [README.md:17-27](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n## Claude Code Configuration\n\n### CLI Installation\n\nUse the Claude Code MCP management command:\n\n```bash\nclaude mcp add templatefox -- npx -y @templatefox/mcp-server\n```\n\nSet the `TEMPLATEFOX_API_KEY` environment variable in your shell configuration:\n\n```bash\nexport TEMPLATEFOX_API_KEY=sk_your_api_key_here\n```\n\n**Source:** [README.md:37-45](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n## Cursor and Windsurf Configuration\n\nBoth Cursor and Windsurf support the same MCP server configuration. Use the npx command with environment variable injection:\n\n```json\n{\n  \"mcpServers\": {\n    \"templatefox\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@templatefox/mcp-server\"],\n      \"env\": {\n        \"TEMPLATEFOX_API_KEY\": \"sk_your_api_key_here\"\n      }\n    }\n  }\n}\n```\n\n**Source:** [README.md:47-52](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n## Environment Variables\n\n### Configuration Reference\n\n| Variable | Required | Default | Description |\n|----------|----------|---------|-------------|\n| `TEMPLATEFOX_API_KEY` | Yes | - | Your API key (starts with `sk_`) |\n| `TEMPLATEFOX_BASE_URL` | No | `https://api.templatefox.com` | Override API base URL |\n| `PORT` | No | - | Enable HTTP mode on specified port |\n\n**Source:** [README.md:57-63](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n### API Key Resolution Order\n\nThe server resolves the API key in the following priority order:\n\n```mermaid\ngraph TD\n    A[API Key Request] --> B{Per-Request Header?}\n    B -->|Yes| C[Use Authorization or x-api-key header]\n    B -->|No| D{Environment Variable?}\n    D -->|Yes| E[Use TEMPLATEFOX_API_KEY]\n    D -->|No| F[Throw Error]\n    C --> G[Process Request]\n    E --> G\n    F --> H[Error: API key required]\n```\n\n**Source:** [src/api-client.ts:25-38](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n\n## HTTP Transport Mode\n\nThe MCP server supports HTTP transport via Streamable HTTP, enabling remote and cloud deployments.\n\n### Server Architecture\n\n```mermaid\ngraph LR\n    A[MCP Client] -->|HTTPS POST /mcp| B[Express Server]\n    A -->|Authorization Header| B\n    B --> C[StreamableHTTPServerTransport]\n    C --> D[McpServer Instance]\n    D --> E[API Request to TemplateFox]\n    E --> F[api.templatefox.com]\n```\n\n### Running in HTTP Mode\n\nSet the `PORT` environment variable to enable HTTP transport:\n\n```bash\nPORT=8080 TEMPLATEFOX_API_KEY=sk_your_key node dist/index.js\n```\n\n**Source:** [README.md:69-70](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n### Remote Server Endpoint\n\nTemplateFox hosts a public MCP server for remote access:\n\n```\nhttps://mcp-server-599407781746.us-central1.run.app/mcp\n```\n\n**Source:** [README.md:73-77](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n### HTTP Authentication\n\nMCP clients must pass the API key via HTTP header:\n\n```http\nAuthorization: Bearer sk_your_api_key_here\n```\n\nOr alternatively:\n\n```http\nx-api-key: sk_your_api_key_here\n```\n\n**Source:** [README.md:79-86](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n### HTTP Server Endpoints\n\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `/health` | GET | Health check endpoint |\n| `/mcp` | POST | MCP request endpoint |\n| `/mcp` | GET | Returns 405 Method Not Allowed |\n| `/mcp` | DELETE | Returns 405 (sessions not supported) |\n\n**Source:** [src/index.ts:42-56](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n### Per-Request API Key Handling\n\nIn HTTP mode, the server extracts the API key from incoming requests using `AsyncLocalStorage` to maintain request isolation:\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant Express\n    participant Transport\n    participant Server\n    participant API\n\n    Client->>Express: POST /mcp with Authorization header\n    Express->>Transport: Extract apiKey\n    Transport->>Server: Handle request with apiKey context\n    Server->>API: Make TemplateFox API call\n    API-->>Server: Response\n    Server-->>Transport: Tool result\n    Transport-->>Express: JSON-RPC response\n    Express-->>Client: HTTP Response\n```\n\n**Source:** [src/api-client.ts:8-14](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n\n## Stdio Transport Mode (Default)\n\nWhen `PORT` is not set, the server runs in stdio mode, which is the default for npx and local CLI usage:\n\n```mermaid\ngraph TD\n    A[AI Assistant] -->|stdio| B[StdioServerTransport]\n    B --> C[McpServer]\n    C --> D[Tool Handler]\n    D --> E[TemplateFox API]\n```\n\n**Source:** [src/index.ts:67-71](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n## Build from Source\n\nFor development or custom deployments:\n\n```bash\n# Clone the repository\ngit clone https://github.com/TemplateFoxPDF/mcp-server.git\ncd mcp-server\n\n# Install dependencies\nnpm install\n\n# Build TypeScript\nnpm run build\n\n# Run the server\nnpm start\n```\n\n### Build Scripts\n\n| Script | Command | Description |\n|--------|---------|-------------|\n| `build` | `tsc` | Compiles TypeScript to JavaScript |\n| `start` | `node dist/index.js` | Runs the compiled server |\n\n**Source:** [package.json:8-11](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n\n## Transport Selection Flow\n\n```mermaid\ngraph TD\n    A[Start] --> B{PORT environment variable set?}\n    B -->|Yes| C[HTTP Mode]\n    B -->|No| D[Stdio Mode]\n    C --> E[Initialize Express + StreamableHTTP]\n    D --> F[Initialize StdioServerTransport]\n    E --> G[Listen on configured port]\n    F --> H[Connect to stdio]\n```\n\n**Source:** [src/index.ts:32-71](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n## Package Metadata\n\n| Property | Value |\n|----------|-------|\n| Package Name | `@templatefox/mcp-server` |\n| Version | `1.10.1` |\n| License | MIT |\n| MCP Server Name | `io.github.TemplateFoxPDF/mcp-server` |\n| Homepage | `https://templatefox.com` |\n\n**Source:** [package.json:2-9](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n\n## Dependencies\n\n| Dependency | Version | Purpose |\n|------------|---------|---------|\n| `@modelcontextprotocol/sdk` | `^1.29.0` | MCP protocol implementation |\n| `express` | `^5.2.1` | HTTP server framework |\n| `cors` | `^2.8.6` | Cross-origin resource sharing |\n\n**Source:** [package.json:12-15](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n\n## Next Steps\n\nAfter successful installation and setup:\n\n1. **List Templates** - Discover available PDF templates using the `list_templates` tool\n2. **Get Template Fields** - Understand required data fields using `get_template_fields`\n3. **Generate PDFs** - Use `generate_pdf` to create PDFs with dynamic data\n4. **Check Credits** - Monitor remaining credits with `get_account_info`\n\n**Source:** [README.md:91-101](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n---\n\n<a id='page-docker-deployment'></a>\n\n## Docker Deployment\n\n### Related Pages\n\nRelated topics: [Installation and Setup](#page-installation), [Transport Modes](#page-transport-modes)\n\n<details>\n<summary>Relevant source files</summary>\n\nThe following source files were used to generate this page:\n\n- [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n- [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n- [src/index.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n- [src/api-client.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n- [src/tools.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n</details>\n\n# Docker Deployment\n\nThe 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.\n\n## Overview\n\nDocker 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.\n\n**Key characteristics:**\n- HTTP-based transport mode (Streamable HTTP)\n- Stateless request handling\n- Health check endpoint for monitoring\n- Environment-based configuration\n- API key authentication via HTTP headers\n\nSource: [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[Docker Container] --> B[Express HTTP Server]\n    B --> C[/health Endpoint]\n    B --> D[/mcp Endpoint]\n    D --> E[MCP SDK Server]\n    E --> F[API Client]\n    F --> G[TemplateFox API]\n    \n    H[External Client] -->|POST /mcp| D\n    H -->|GET /health| C\n    \n    style A fill:#e1f5fe\n    style G fill:#fff3e0\n```\n\nThe 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.\n\nSource: [src/index.ts:1-95](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n## Building the Docker Image\n\n### Prerequisites\n\n- Docker Engine 20.10+\n- TemplateFox API key (obtained from [app.templatefox.com/dashboard/api-keys](https://app.templatefox.com/dashboard/api-keys))\n\n### Build Command\n\n```bash\ndocker build -t templatefox-mcp .\n```\n\nThe build process executes the following steps:\n1. Base image setup (Node.js runtime)\n2. Dependency installation via npm\n3. TypeScript compilation\n4. Production artifact preparation\n\nSource: [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json) (build script)\n\n### Build Script Configuration\n\n```json\n{\n  \"scripts\": {\n    \"build\": \"tsc\",\n    \"start\": \"node dist/index.js\"\n  }\n}\n```\n\nSource: [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n\n## Running the Container\n\n### Basic Usage\n\n```bash\ndocker run -p 8080:8080 -e TEMPLATEFOX_API_KEY=sk_your_api_key templatefox-mcp\n```\n\nThis command:\n- Maps container port 8080 to host port 8080\n- Passes the API key via environment variable\n- Starts the MCP server in HTTP mode\n\nSource: [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n### Environment Variables\n\n| Variable | Required | Default | Description |\n|----------|----------|---------|-------------|\n| `TEMPLATEFOX_API_KEY` | Yes | - | API key for TemplateFox API (starts with `sk_`) |\n| `PORT` | No | undefined (stdio mode) | Set to enable HTTP transport mode |\n| `TEMPLATEFOX_BASE_URL` | No | `https://api.templatefox.com` | Override API base URL |\n\nSource: [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)\n\n### Port Configuration\n\nWhen the `PORT` environment variable is set, the server automatically switches from stdio mode to HTTP mode:\n\n```typescript\nconst port = process.env.PORT ? parseInt(process.env.PORT, 10) : undefined;\n\nif (port) {\n  // HTTP mode: Streamable HTTP transport\n  const express = (await import(\"express\")).default;\n  // ... Express setup\n  app.listen(port, \"0.0.0.0\", () => {\n    console.error(`TemplateFox MCP server (HTTP) listening on http://0.0.0.0:${port}/mcp`);\n  });\n}\n```\n\nSource: [src/index.ts:27-35](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n## HTTP Endpoints\n\n### Health Check\n\n```\nGET /health\n```\n\nReturns server status and version information:\n\n```json\n{\n  \"status\": \"ok\",\n  \"version\": \"1.8.2\"\n}\n```\n\nSource: [src/index.ts:42-45](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n### MCP Endpoint\n\n```\nPOST /mcp\n```\n\nHandles all MCP JSON-RPC requests. Supports the complete MCP protocol including:\n- `initialize`\n- `tools/list`\n- `tools/call`\n- `ping`\n\n**Request Headers:**\n\n| Header | Required | Description |\n|--------|----------|-------------|\n| `Authorization` | Yes* | `Bearer sk_your_api_key_here` |\n| `x-api-key` | Yes* | `sk_your_api_key_here` (alternative) |\n| `Content-Type` | Yes | `application/json` for POST requests |\n\n*Either `Authorization` or `x-api-key` header is required.\n\nSource: [src/index.ts:47-62](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n### Method Not Allowed Responses\n\n```json\n{\n  \"jsonrpc\": \"2.0\",\n  \"error\": { \"code\": -32000, \"message\": \"Method not allowed. Use POST for MCP requests.\" },\n  \"id\": null\n}\n```\n\nBoth `GET /mcp` and `DELETE /mcp` return 405 Method Not Allowed responses since MCP requires POST.\n\nSource: [src/index.ts:81-92](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n## API Key Authentication\n\nThe server implements per-request API key authentication for HTTP transport:\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant Docker as Docker Container\n    participant MCP as MCP Server\n    participant API as TemplateFox API\n    \n    Client->>Docker: POST /mcp with API key header\n    Docker->>MCP: Extract API key from header\n    MCP->>API: Forward request with API key\n    API-->>MCP: Response data\n    MCP-->>Client: JSON-RPC response\n```\n\n### Key Extraction Logic\n\n```typescript\nconst authHeader = req.headers.authorization;\nconst apiKey = authHeader?.startsWith(\"Bearer \")\n  ? authHeader.slice(7)\n  : (req.headers[\"x-api-key\"] as string | undefined);\n```\n\nSource: [src/index.ts:47-53](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n### Key Resolution Priority\n\n1. **Per-request key** from HTTP transport via AsyncLocalStorage\n2. **Environment variable** `TEMPLATEFOX_API_KEY` (stdio mode fallback)\n\n```typescript\nfunction getApiKey(): string {\n  const contextKey = apiKeyStore.getStore();\n  if (contextKey) return contextKey;\n  \n  const key = process.env.TEMPLATEFOX_API_KEY;\n  if (!key) {\n    throw new Error(\"TEMPLATEFOX_API_KEY is required...\");\n  }\n  return key;\n}\n```\n\nSource: [src/api-client.ts:18-30](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/api-client.ts)\n\n## Request Handling Flow\n\n```mermaid\ngraph TD\n    A[POST /mcp] --> B{API Key Present?}\n    B -->|No| C[401 Unauthorized]\n    B -->|Yes| D[Create MCP Server]\n    D --> E[Create HTTP Transport]\n    E --> F[Connect Server to Transport]\n    F --> G[Handle Request with API Key Context]\n    G --> H[Process JSON-RPC]\n    H --> I[Return Response]\n    I --> J[Close Transport & Server]\n    \n    style C fill:#ffcdd2\n    style I fill:#c8e6c9\n```\n\nThe server creates a fresh MCP server instance for each request to ensure stateless operation in cloud environments.\n\nSource: [src/index.ts:64-79](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n## MCP Tools Available\n\nOnce deployed, the following tools are accessible via the MCP protocol:\n\n| Tool | Purpose | Credits |\n|------|---------|---------|\n| `generate_pdf` | Synchronous PDF generation | 1 |\n| `generate_pdf_async` | Asynchronous PDF generation with webhooks | 1 |\n| `get_pdf_job_status` | Check async job status | - |\n| `list_pdf_jobs` | List async PDF jobs | - |\n| `list_templates` | List available templates | - |\n| `get_template_fields` | Get template field definitions | - |\n| `get_account_info` | Check account credits | - |\n| `list_transactions` | View transaction history | - |\n\nSource: [src/tools.ts](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/tools.ts)\n\n## Remote Server Deployment\n\n### Cloud Run Example\n\nThe server can be deployed to Google Cloud Run using the provided Dockerfile:\n\n```bash\n# Build and deploy\ngcloud builds submit --tag gcr.io/PROJECT_ID/templatefox-mcp\ngcloud run deploy templatefox-mcp --image gcr.io/PROJECT_ID/templatefox-mcp --port 8080\n```\n\n### Connecting via URL\n\nExternal MCP clients can connect to the deployed server:\n\n```\nhttps://mcp-server-599407781746.us-central1.run.app/mcp\n```\n\nSource: [README.md](https://github.com/TemplateFoxPDF/mcp-server/blob/main/README.md)\n\n## Container Networking\n\n```mermaid\ngraph LR\n    subgraph Host\n        A[localhost:8080] --> B[Container:8080]\n    end\n    \n    subgraph Container\n        B --> C[Express Server]\n        C --> D[MCP Handler]\n        D --> E[TemplateFox API]\n    end\n    \n    E -->|HTTPS| F[api.templatefox.com]\n```\n\nThe container listens on all network interfaces (`0.0.0.0`) to accept external connections when deployed to cloud environments.\n\nSource: [src/index.ts:34](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n## Dependencies\n\n### Production Dependencies\n\n| Package | Version | Purpose |\n|---------|---------|---------|\n| `@modelcontextprotocol/sdk` | ^1.29.0 | MCP protocol implementation |\n| `express` | ^5.2.1 | HTTP server framework |\n| `cors` | ^2.8.6 | Cross-origin resource sharing |\n\nSource: [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n\n### Runtime Requirements\n\n- Node.js >= 18.0.0\n- Network access to `api.templatefox.com`\n- Valid TemplateFox API key\n\nSource: [package.json](https://github.com/TemplateFoxPDF/mcp-server/blob/main/package.json)\n\n## Troubleshooting\n\n### Container Exits Immediately\n\n**Cause:** Missing `PORT` environment variable.\n\n**Solution:** Set `PORT` environment variable to enable HTTP mode:\n```bash\ndocker run -p 8080:8080 -e PORT=8080 -e TEMPLATEFOX_API_KEY=sk_xxx templatefox-mcp\n```\n\n### 401 Unauthorized Errors\n\n**Cause:** Missing or invalid API key in request headers.\n\n**Solution:** Include API key via `Authorization: Bearer` header or `x-api-key` header.\n\n### Connection Refused\n\n**Cause:** Port not mapped correctly or container not running.\n\n**Solution:** Verify container is running and port mapping is correct:\n```bash\ndocker ps | grep templatefox-mcp\ndocker port templatefox-mcp\n```\n\n## Security Considerations\n\n- **API keys** are passed via HTTP headers; always use HTTPS in production\n- **Container runs as non-root** (recommended for production deployments)\n- **Network isolation** is handled by Docker's container networking\n- **Environment variables** should be managed via secrets in production orchestration systems\n\nSource: [src/index.ts:47-62](https://github.com/TemplateFoxPDF/mcp-server/blob/main/src/index.ts)\n\n---\n\n---\n\n## Doramagic Pitfall Log\n\nProject: templatefoxpdf/mcp-server\n\nSummary: 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.\n\n## 1. installation · 社区讨论暴露的待验证问题：darkzodchi en X: \"Top MCP Servers That Turn Claude Into a Productivity Machine\" / X\n\n- Severity: medium\n- Evidence strength: source_linked\n- 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…\n- User impact: 这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。\n- Suggested check: Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。\n- 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\n\n## 2. capability · 能力判断依赖假设\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: README/documentation is current enough for a first validation pass.\n- User impact: 假设不成立时，用户拿不到承诺的能力。\n- Suggested check: 将假设转成下游验证清单。\n- Guardrail action: 假设必须转成验证项；没有验证结果前不能写成事实。\n- 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.\n\n## 3. runtime · 社区讨论暴露的待验证问题：Adding Github MCP to Claude Code Error : r/ClaudeAI - Reddit\n\n- Severity: medium\n- Evidence strength: source_linked\n- 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 ...\n- User impact: 这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。\n- Suggested check: Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。\n- 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\n\n## 4. runtime · 社区讨论暴露的待验证问题：you need somewhere between 1-10 Claude skills depending on what ...\n\n- Severity: medium\n- Evidence strength: source_linked\n- 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 ...\n- User impact: 这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。\n- Suggested check: Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。\n- Evidence: social_signal:x | ssig_504e57203f64433a83bf7ec96631f94c | https://x.com/Hesamation/status/2035136966719582695 | you need somewhere between 1-10 Claude skills depending on what ...\n\n## 5. maintenance · 维护活跃度未知\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: 未记录 last_activity_observed。\n- User impact: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- Suggested check: 补 GitHub 最近 commit、release、issue/PR 响应信号。\n- Guardrail action: 维护活跃度未知时，推荐强度不能标为高信任。\n- 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\n\n## 6. security_permissions · 下游验证发现风险项\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: no_demo\n- User impact: 下游已经要求复核，不能在页面中弱化。\n- Suggested check: 进入安全/权限治理复核队列。\n- Guardrail action: 下游风险存在时必须保持 review/recommendation 降级。\n- 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\n\n## 7. security_permissions · 存在评分风险\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: no_demo\n- User impact: 风险会影响是否适合普通用户安装。\n- Suggested check: 把风险写入边界卡，并确认是否需要人工复核。\n- Guardrail action: 评分风险必须进入边界卡，不能只作为内部分数。\n- 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\n\n## 8. maintenance · issue/PR 响应质量未知\n\n- Severity: low\n- Evidence strength: source_linked\n- Finding: issue_or_pr_quality=unknown。\n- User impact: 用户无法判断遇到问题后是否有人维护。\n- Suggested check: 抽样最近 issue/PR，判断是否长期无人处理。\n- Guardrail action: issue/PR 响应未知时，必须提示维护风险。\n- 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\n\n## 9. maintenance · 发布节奏不明确\n\n- Severity: low\n- Evidence strength: source_linked\n- Finding: release_recency=unknown。\n- User impact: 安装命令和文档可能落后于代码，用户踩坑概率升高。\n- Suggested check: 确认最近 release/tag 和 README 安装命令是否一致。\n- Guardrail action: 发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 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\n\n<!-- canonical_name: templatefoxpdf/mcp-server; human_manual_source: deepwiki_human_wiki -->\n",
      "summary": "DeepWiki/Human Wiki output with a Doramagic pitfall appendix.",
      "title": "Human Manual"
    },
    "pitfall_log": {
      "asset_id": "pitfall_log",
      "filename": "PITFALL_LOG.md",
      "markdown": "# Pitfall Log\n\nProject: templatefoxpdf/mcp-server\n\nSummary: 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.\n\n## 1. installation · 社区讨论暴露的待验证问题：darkzodchi en X: \"Top MCP Servers That Turn Claude Into a Productivity Machine\" / X\n\n- Severity: medium\n- Evidence strength: source_linked\n- 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…\n- User impact: 这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。\n- Suggested check: Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。\n- 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\n\n## 2. capability · 能力判断依赖假设\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: README/documentation is current enough for a first validation pass.\n- User impact: 假设不成立时，用户拿不到承诺的能力。\n- Suggested check: 将假设转成下游验证清单。\n- Guardrail action: 假设必须转成验证项；没有验证结果前不能写成事实。\n- 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.\n\n## 3. runtime · 社区讨论暴露的待验证问题：Adding Github MCP to Claude Code Error : r/ClaudeAI - Reddit\n\n- Severity: medium\n- Evidence strength: source_linked\n- 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 ...\n- User impact: 这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。\n- Suggested check: Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。\n- 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\n\n## 4. runtime · 社区讨论暴露的待验证问题：you need somewhere between 1-10 Claude skills depending on what ...\n\n- Severity: medium\n- Evidence strength: source_linked\n- 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 ...\n- User impact: 这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。\n- Suggested check: Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。\n- Evidence: social_signal:x | ssig_504e57203f64433a83bf7ec96631f94c | https://x.com/Hesamation/status/2035136966719582695 | you need somewhere between 1-10 Claude skills depending on what ...\n\n## 5. maintenance · 维护活跃度未知\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: 未记录 last_activity_observed。\n- User impact: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- Suggested check: 补 GitHub 最近 commit、release、issue/PR 响应信号。\n- Guardrail action: 维护活跃度未知时，推荐强度不能标为高信任。\n- 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\n\n## 6. security_permissions · 下游验证发现风险项\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: no_demo\n- User impact: 下游已经要求复核，不能在页面中弱化。\n- Suggested check: 进入安全/权限治理复核队列。\n- Guardrail action: 下游风险存在时必须保持 review/recommendation 降级。\n- 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\n\n## 7. security_permissions · 存在评分风险\n\n- Severity: medium\n- Evidence strength: source_linked\n- Finding: no_demo\n- User impact: 风险会影响是否适合普通用户安装。\n- Suggested check: 把风险写入边界卡，并确认是否需要人工复核。\n- Guardrail action: 评分风险必须进入边界卡，不能只作为内部分数。\n- 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\n\n## 8. maintenance · issue/PR 响应质量未知\n\n- Severity: low\n- Evidence strength: source_linked\n- Finding: issue_or_pr_quality=unknown。\n- User impact: 用户无法判断遇到问题后是否有人维护。\n- Suggested check: 抽样最近 issue/PR，判断是否长期无人处理。\n- Guardrail action: issue/PR 响应未知时，必须提示维护风险。\n- 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\n\n## 9. maintenance · 发布节奏不明确\n\n- Severity: low\n- Evidence strength: source_linked\n- Finding: release_recency=unknown。\n- User impact: 安装命令和文档可能落后于代码，用户踩坑概率升高。\n- Suggested check: 确认最近 release/tag 和 README 安装命令是否一致。\n- Guardrail action: 发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 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\n",
      "summary": "Identity, installation, configuration, runtime, and safety pitfalls before user trial.",
      "title": "Pitfall Log"
    },
    "prompt_preview": {
      "asset_id": "prompt_preview",
      "filename": "PROMPT_PREVIEW.md",
      "markdown": "# mcp-server - Prompt Preview\n\n> Copy the prompt below into your AI host before installing anything.\n> Its purpose is to let you safely feel the project's workflow, not to claim the project has already run.\n\n## Copy this prompt\n\n```text\nYou are using an independent Doramagic capability pack for templatefoxpdf/mcp-server.\n\nProject:\n- Name: mcp-server\n- Repository: https://github.com/TemplateFoxPDF/mcp-server\n- Summary: MCP server for TemplateFox PDF generation API - Generate PDFs from templates via AI assistants\n- Host target: mcp_host\n\nGoal:\nHelp me evaluate this project for the following task without installing it yet: MCP server for TemplateFox PDF generation API - Generate PDFs from templates via AI assistants\n\nBefore taking action:\n1. Restate my task, success standard, and boundary.\n2. Identify whether the next step requires tools, browser access, network access, filesystem access, credentials, package installation, or host configuration.\n3. Use only the Doramagic Project Pack, the upstream repository, and the source-linked evidence listed below.\n4. If a real command, install step, API call, file write, or host integration is required, mark it as \"requires post-install verification\" and ask for approval first.\n5. If evidence is missing, say \"evidence is missing\" instead of filling the gap.\n\nPreviewable capabilities:\n- Capability 1: MCP server for TemplateFox PDF generation API - Generate PDFs from templates via AI assistants\n\nCapabilities that require post-install verification:\n- Capability 1: Use the source-backed project context to guide one small, checkable workflow step.\n\nCore service flow:\n1. page-introduction: Introduction. Produce one small intermediate artifact and wait for confirmation.\n2. page-project-structure: Project Structure. Produce one small intermediate artifact and wait for confirmation.\n3. page-transport-modes: Transport Modes. Produce one small intermediate artifact and wait for confirmation.\n4. page-pdf-generation-tools: PDF Generation Tools. Produce one small intermediate artifact and wait for confirmation.\n5. page-template-management-tools: Template Management Tools. Produce one small intermediate artifact and wait for confirmation.\n\nSource-backed evidence to keep in mind:\n- https://registry.modelcontextprotocol.io/v0.1/servers/io.github.TemplateFoxPDF%2Fmcp-server/versions/1.9.7\n- README.md\n- package.json\n- tsconfig.json\n- Dockerfile\n- src/index.ts\n- src/tools.ts\n\nFirst response rules:\n1. Start Step 1 only.\n2. Explain the one service action you will perform first.\n3. Ask exactly three questions about my target workflow, success standard, and sandbox boundary.\n4. Stop and wait for my answers.\n\nStep 1 follow-up protocol:\n- After I answer the first three questions, stay in Step 1.\n- Produce six parts only: clarified task, success standard, boundary conditions, two or three options, tradeoffs for each option, and one recommendation.\n- End by asking whether I confirm the recommendation.\n- Do not move to Step 2 until I explicitly confirm.\n\nConversation rules:\n- Advance one step at a time and wait for confirmation after each small artifact.\n- Write outputs as recommendations or planned checks, not as completed execution.\n- Do not claim tests passed, files changed, commands ran, APIs were called, or the project was installed.\n- If the user asks for execution, first provide the sandbox setup, expected output, rollback, and approval checkpoint.\n```\n",
      "summary": "不安装项目也能感受能力节奏的安全试用 Prompt。",
      "title": "Prompt Preview / 安装前试用 Prompt"
    },
    "quick_start": {
      "asset_id": "quick_start",
      "filename": "QUICK_START.md",
      "markdown": "# Quick Start\n\nProject: templatefoxpdf/mcp-server\n\n## Official Entry Points\n\n### Node.js / npx · 官方安装入口\n\n```bash\nnpx @templatefox/mcp-server\n```\n\nSource：https://registry.modelcontextprotocol.io/v0.1/servers/io.github.TemplateFoxPDF%2Fmcp-server/versions/1.9.7\n\n## Sources\n\n- mcp_registry: https://registry.modelcontextprotocol.io/v0.1/servers/io.github.TemplateFoxPDF%2Fmcp-server/versions/1.9.7\n",
      "summary": "Entry points extracted from official README or installation documentation.",
      "title": "Quick Start"
    }
  },
  "validation_id": "dval_1b1d97a0b5c040a48b42d3dd5dcaac8c"
}
