# Office OOXML Template Merge & Markdown Extractor API (v1.0.0)

> Brand-safe .docx/.pptx template merging (fixing Word split XML runs & table loops) and 85%+ token-saving .docx/.pptx/.xlsx Markdown extraction.

Zero-dependency Cloudflare Edge OOXML engine that merges .docx and .pptx templates (healing split XML runs, preserving run/cell styles, and expanding repeating table rows) and extracts .docx, .pptx, and .xlsx files into token-minimal Markdown.

## Why Agents Use This API Instead of DIY
Typing {{customer_name}} in Word or PowerPoint shatters placeholders across multiple <w:r>/<a:r> runs with <w:proofErr/> tags, breaking naive regex scripts and corrupting PKZIP CRC32 headers. This API heals split runs, clones styled table rows, and extracts clean Markdown in milliseconds.

## Connection & Payment (x402 Default + Optional Bearer API Key)
- **MCP Server (Streamable HTTP):** `https://office-template.apikeg.com/mcp` (Registry ID: `com.apikeg/office-template` — `initialize`, `tools/list`, `resources/*`, and `prompts/*` are free)
- **OpenAPI 3.1 Spec:** [openapi.json](https://office-template.apikeg.com/openapi.json)
- **Full Schema & Examples:** [llms-full.txt](https://office-template.apikeg.com/llms-full.txt)
- **RFC 9727 API Catalog:** [.well-known/api-catalog](https://office-template.apikeg.com/.well-known/api-catalog)
- **x402 Bazaar Manifest:** [.well-known/x402.json](https://office-template.apikeg.com/.well-known/x402.json)
- **MCP Discovery Manifest:** [.well-known/mcp.json](https://office-template.apikeg.com/.well-known/mcp.json)
- **A2A Agent Card:** [.well-known/agent-card.json](https://office-template.apikeg.com/.well-known/agent-card.json)
- **Primary Payment (Zero Signup):** Cloudflare Monetization Gateway (`HTTP 402` / `x402` v2 with USDC on Base).
- **Optional Monthly API Key:** Pass `Authorization: Bearer ak_live_...` ($5 / $20 / $50 monthly per-product Stripe plans at [apikeg.com/account](https://apikeg.com/account)).
- **Free Preflight:** Append `?dry_run=true` (or header `X-Dry-Run: true`) to validate any request payload at `$0.00` cost.

## Tools & REST Endpoints
- [`merge_office_template`](https://office-template.apikeg.com/tools/merge-office-template.md) (`POST https://office-template.apikeg.com/v1/merge-office-template`) — $0.004 USD per Office template merge (.docx or .pptx) (x402 instant micropayment): Coalesces split {{variable}} runs across Word (<w:r>) and PowerPoint (<a:r>) paragraphs while preserving opening-run typography, expands {{#loop}}...{{/loop}} table rows, replaces variables across body/headers/footers/slides, and returns a valid PKZIP Base64 document plus any unmatchedPlaceholders.
- [`extract_office_markdown`](https://office-template.apikeg.com/tools/extract-office-markdown.md) (`POST https://office-template.apikeg.com/v1/extract-office-markdown`) — $0.002 USD per Office document extraction (.docx, .pptx, or .xlsx) (x402 instant micropayment): Auto-detects .docx, .pptx, or .xlsx from OOXML structure and converts headings, lists, Word/PowerPoint tables, numerically ordered slides, speaker notes, and sparse Excel worksheets into compact GitHub-Flavored Markdown with token-savings telemetry.

## Instant MCP Configuration
```json
{
  "mcpServers": {
    "office-template": {
      "type": "streamable-http",
      "url": "https://office-template.apikeg.com/mcp"
    }
  }
}
```

## Common Agent Use Cases
- merge docx template variables API without breaking formatting
- fix Word split XML runs placeholder replacement MCP
- generate PowerPoint pptx deck from template JSON variables
- convert docx pptx xlsx to clean LLM Markdown API
- populate invoice table rows in Word docx template

---

## Detailed Tool Specifications

### `merge_office_template` — Merge .docx or .pptx Office Template
- **REST Endpoint:** `POST https://office-template.apikeg.com/v1/merge-office-template`
- **Tool Doc Page:** https://office-template.apikeg.com/tools/merge-office-template
- **MCP Tool Name:** `merge_office_template`
- **Pricing:** $0.004 USD per Office template merge (.docx or .pptx) (x402 instant micropayment)
- **Side Effects:** readOnly=true, idempotent=true, destructive=false
- **Build vs. Buy ROI:** Eliminates broken {{tags}} caused by Word/PowerPoint spellcheck run-splitting, <a:br/> vs <w:br/> schema errors, and corrupt PKZIP Central Directory CRCs.

#### Input JSON Schema
```json
{
  "type": "object",
  "properties": {
    "fileBase64": {
      "type": "string",
      "minLength": 16,
      "description": "Base64-encoded .docx or .pptx OOXML template file (accepts raw Base64 or data:...;base64, URI)."
    },
    "format": {
      "type": "string",
      "enum": [
        "auto",
        "docx",
        "pptx"
      ],
      "default": "auto",
      "description": "Template format ('auto' inspects internal OOXML ZIP entries)."
    },
    "variables": {
      "type": "object",
      "additionalProperties": {
        "description": "Scalar replacement value (string, finite number, or boolean)."
      },
      "description": "Key-value map for {{placeholder}} variables across body, headers, footers, and slides. Multi-line '\\n' values expand to <w:br/> / <a:br/>."
    },
    "tableLoops": {
      "type": "object",
      "additionalProperties": {
        "type": "array",
        "items": {
          "type": "object",
          "additionalProperties": {
            "description": "Scalar replacement value (string, finite number, or boolean)."
          },
          "description": "Per-row variable map merged into the cloned table row."
        },
        "maxItems": 2000,
        "description": "Rows cloned for {{#loopKey}}...{{/loopKey}} inside <w:tr> or <a:tr>."
      },
      "description": "Repeating table row arrays keyed by loop name (matching {{#items}}...{{/items}} inside a Word or PowerPoint table row)."
    }
  },
  "required": [
    "fileBase64"
  ],
  "additionalProperties": false
}
```

#### Examples
**Populate contract & line-item table in .docx template** — Replaces header/body scalar placeholders and clones a styled {{#items}}...{{/items}} invoice table row.
```bash
curl -X POST "https://office-template.apikeg.com/v1/merge-office-template" \
  -H "Content-Type: application/json" \
  -d '{"fileBase64":"UEsDBBQAAAAIA...","format":"docx","variables":{"customer_name":"Acme Robotics, Inc.","billing_address":"500 Market St\nSuite 1200\nSan Francisco, CA","contract_id":"MSA-2026-089"},"tableLoops":{"items":[{"sku":"ENT-SEAT","description":"Enterprise Agent Seat","qty":25,"total":"$2,500"},{"sku":"DED-EDGE","description":"Dedicated Edge Worker","qty":1,"total":"$500"}]}}'
```
Expected result: Returns merged .docx Base64 bytes, replacementsCount=11, and unmatchedPlaceholders=[] ready to open in Microsoft Word.

### `extract_office_markdown` — Extract Token-Minimal Markdown from .docx, .pptx, or .xlsx
- **REST Endpoint:** `POST https://office-template.apikeg.com/v1/extract-office-markdown`
- **Tool Doc Page:** https://office-template.apikeg.com/tools/extract-office-markdown
- **MCP Tool Name:** `extract_office_markdown`
- **Pricing:** $0.002 USD per Office document extraction (.docx, .pptx, or .xlsx) (x402 instant micropayment)
- **Side Effects:** readOnly=true, idempotent=true, destructive=false
- **Build vs. Buy ROI:** Saves 80-95% of context window tokens vs raw OOXML dumps and handles Excel sharedStrings.xml + sparse cell coordinates (A1, D5) without external libraries.

#### Input JSON Schema
```json
{
  "type": "object",
  "properties": {
    "fileBase64": {
      "type": "string",
      "minLength": 16,
      "description": "Base64-encoded .docx, .pptx, or .xlsx OOXML file to convert into token-minimal Markdown."
    },
    "includeSpeakerNotes": {
      "type": "boolean",
      "default": true,
      "description": "Include speaker notes from ppt/notesSlides/notesSlide*.xml when extracting .pptx presentations."
    },
    "maxRowsPerSheet": {
      "type": "integer",
      "default": 500,
      "minimum": 1,
      "maximum": 5000,
      "description": "Maximum non-empty rows emitted per .xlsx worksheet."
    }
  },
  "required": [
    "fileBase64"
  ],
  "additionalProperties": false
}
```

#### Examples
**Extract slides & speaker notes from .pptx deck**
```bash
curl -X POST "https://office-template.apikeg.com/v1/extract-office-markdown" \
  -H "Content-Type: application/json" \
  -d '{"fileBase64":"UEsDBBQAAAAIA...","includeSpeakerNotes":true,"maxRowsPerSheet":500}'
```
Expected result: Returns format='pptx', ordered '## Slide N: Title' Markdown with pipe tables and speaker notes, plus token reduction stats.
