# Document Redline & Table Diff Edge API (v1.0.0)

> Deterministic Myers redlines, numeric/date edit alerts, Word .docx Track Changes, and composite-key table diffs in milliseconds.

Deterministic two-level Myers O(ND) paragraph and word-level document diffing, automatic numeric/currency/percentage/duration/date change extraction, native OpenXML .docx Track Changes generation, and composite-key CSV/JSON table diffing.

## Why Agents Use This API Instead of DIY
Prevents middle-of-context LLM skimming misses on buried numeric/date edits, cuts 40-page document review payloads by 90-98% in tokens, and emits real OpenXML <w:ins>/<w:del> .docx archives without brittle Python/LibreOffice dependencies.

## Connection & Payment (x402 Default + Optional Bearer API Key)
- **MCP Server (Streamable HTTP):** `https://doc-redline.apikeg.com/mcp` (Registry ID: `com.apikeg/doc-redline` — `initialize`, `tools/list`, `resources/*`, and `prompts/*` are free)
- **OpenAPI 3.1 Spec:** [openapi.json](https://doc-redline.apikeg.com/openapi.json)
- **Full Schema & Examples:** [llms-full.txt](https://doc-redline.apikeg.com/llms-full.txt)
- **RFC 9727 API Catalog:** [.well-known/api-catalog](https://doc-redline.apikeg.com/.well-known/api-catalog)
- **x402 Bazaar Manifest:** [.well-known/x402.json](https://doc-redline.apikeg.com/.well-known/x402.json)
- **MCP Discovery Manifest:** [.well-known/mcp.json](https://doc-redline.apikeg.com/.well-known/mcp.json)
- **A2A Agent Card:** [.well-known/agent-card.json](https://doc-redline.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
- [`diff_documents`](https://doc-redline.apikeg.com/tools/diff-documents.md) (`POST https://doc-redline.apikeg.com/v1/diff-documents`) — $0.002 USD per document redline comparison (x402 instant micropayment): Runs two-level Myers O(ND) section/paragraph and inline word-and-punctuation diffing across two document versions, returning sectionBreadcrumb-tagged hunks, CriticMarkup ({--old--}{++new++}), inline HTML (<del>/<ins>), dedicated numericAndDateChanges alerts, and optional native .docx Track Changes.
- [`diff_tables`](https://doc-redline.apikeg.com/tools/diff-tables.md) (`POST https://doc-redline.apikeg.com/v1/diff-tables`) — $0.002 USD per structured table or catalog diff (x402 instant micropayment): Compares two JSON object arrays or RFC 4180 CSV strings keyed by a single or composite primaryKey, returning exact summary counts, added rows, removed rows, and cell-level modified diffs with exact decimal numericDelta.

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

## Common Agent Use Cases
- deterministic document redline diff API MCP
- generate Word docx Track Changes w:ins w:del API
- compare two SOW RFP versions CriticMarkup HTML diff
- extract numeric currency duration date changes between documents
- diff two CSV or JSON catalogs by composite primary key

---

## Detailed Tool Specifications

### `diff_documents` — Redline & Audit Two Document Versions
- **REST Endpoint:** `POST https://doc-redline.apikeg.com/v1/diff-documents`
- **Tool Doc Page:** https://doc-redline.apikeg.com/tools/diff-documents
- **MCP Tool Name:** `diff_documents`
- **Pricing:** $0.002 USD per document redline comparison (x402 instant micropayment)
- **Side Effects:** readOnly=true, idempotent=true, destructive=false
- **Build vs. Buy ROI:** Eliminates 95% of unchanged context tokens on multi-section specs/RFPs/SOWs, catches every altered number/currency/duration/date deterministically, and packages valid ECMA-376 .docx Track Changes ZIP archives on the edge.

#### Input JSON Schema
```json
{
  "type": "object",
  "properties": {
    "original": {
      "type": "string",
      "maxLength": 900000,
      "description": "Baseline/original document text or Markdown (e.g. RFP, SOW, specification, SLA, or policy v1)."
    },
    "revised": {
      "type": "string",
      "maxLength": 900000,
      "description": "Revised/updated document text or Markdown to compare deterministically against original."
    },
    "changedHunksOnly": {
      "type": "boolean",
      "default": true,
      "description": "When true (default), omits 100% identical sections from hunks, criticMarkup, and htmlRedline so multi-page documents shrink by 90-98% in tokens."
    },
    "contextParagraphs": {
      "type": "integer",
      "default": 0,
      "minimum": 0,
      "maximum": 5,
      "description": "Number of surrounding unchanged paragraphs to include around each changed hunk (0-5)."
    },
    "ignoreWhitespace": {
      "type": "boolean",
      "default": true,
      "description": "Normalize repeated inline whitespace when aligning paragraphs while preserving exact text inside word-level diffs."
    },
    "includeDocxTrackChanges": {
      "type": "boolean",
      "default": false,
      "description": "When true, generates a base64 OpenXML .docx archive containing native Microsoft Word Track Changes (<w:ins> and <w:del>/<w:delText>) for Accept/Reject review."
    },
    "docxAuthor": {
      "type": "string",
      "default": "API Keg Redline Engine",
      "maxLength": 120,
      "description": "Author attribution recorded on OpenXML <w:ins> and <w:del> Track Changes tags when includeDocxTrackChanges is true."
    },
    "docxTitle": {
      "type": "string",
      "maxLength": 200,
      "description": "Optional document title stored in .docx Dublin Core package metadata."
    }
  },
  "required": [
    "original",
    "revised"
  ],
  "additionalProperties": false
}
```

#### Examples
**Audit SOW revision with numeric duration & fee edits** — Extracts changed hunks, CriticMarkup, HTML redlines, numericAndDateChanges, and a Word Track Changes .docx file.
```bash
curl -X POST "https://doc-redline.apikeg.com/v1/diff-documents" \
  -H "Content-Type: application/json" \
  -d '{"original":"# Statement of Work\n\n## Section 4.2: Payment Terms\nCustomer shall pay all undisputed invoices within 30 days of receipt at $150/hour.","revised":"# Statement of Work\n\n## Section 4.2: Payment Terms\nCustomer shall pay all undisputed invoices within 45 days of receipt at $175/hour.","changedHunksOnly":true,"contextParagraphs":0,"ignoreWhitespace":true,"includeDocxTrackChanges":true,"docxAuthor":"Procurement Ops Bot"}'
```
Expected result: 1 changed hunk under 'Statement of Work > Section 4.2: Payment Terms', 2 numericAndDateChanges ('30 days' -> '45 days', '$150' -> '$175'), and a valid base64 .docx with <w:del> and <w:ins>.

### `diff_tables` — Compare Two Structured CSV or JSON Tables by Primary Key
- **REST Endpoint:** `POST https://doc-redline.apikeg.com/v1/diff-tables`
- **Tool Doc Page:** https://doc-redline.apikeg.com/tools/diff-tables
- **MCP Tool Name:** `diff_tables`
- **Pricing:** $0.002 USD per structured table or catalog diff (x402 instant micropayment)
- **Side Effects:** readOnly=true, idempotent=true, destructive=false
- **Build vs. Buy ROI:** Avoids row-order false positives in line-based diffs and floating-point drift on price/inventory catalogs; supports composite keys like ['sku', 'region'] in <10ms.

#### Input JSON Schema
```json
{
  "type": "object",
  "properties": {
    "before": {
      "description": "Table dataset passed either as a JSON array of row objects (e.g. [{\"sku\":\"A1\",\"region\":\"US\",\"price\":49.99}]) or an RFC 4180 CSV string with a header row."
    },
    "after": {
      "description": "Table dataset passed either as a JSON array of row objects (e.g. [{\"sku\":\"A1\",\"region\":\"US\",\"price\":49.99}]) or an RFC 4180 CSV string with a header row."
    },
    "primaryKey": {
      "description": "Single primary-key column name (e.g. \"sku\") or composite primary-key column list (e.g. [\"sku\", \"region\"])."
    },
    "ignoreFields": {
      "type": "array",
      "items": {
        "type": "string",
        "minLength": 1,
        "maxLength": 128
      },
      "maxItems": 64,
      "description": "Optional column names (such as \"updated_at\" or \"etag\") to exclude from cell comparison."
    },
    "csvDelimiter": {
      "type": "string",
      "default": ",",
      "minLength": 1,
      "maxLength": 1,
      "description": "Single-character column delimiter used when before or after is a CSV string (default ',')."
    },
    "coerceCsvTypes": {
      "type": "boolean",
      "default": true,
      "description": "Automatically parse unquoted numeric and boolean literals in CSV cells while preserving leading-zero identifiers."
    },
    "numericTolerance": {
      "type": "number",
      "default": 0,
      "minimum": 0,
      "maximum": 1000000,
      "description": "Optional non-negative tolerance; numeric cell differences with |delta| <= numericTolerance are treated as unchanged."
    }
  },
  "required": [
    "before",
    "after",
    "primaryKey"
  ],
  "additionalProperties": false
}
```

#### Examples
**Diff regional SKU price catalog by composite key** — Detects added/removed SKUs and exact per-cell numericDelta across regions.
```bash
curl -X POST "https://doc-redline.apikeg.com/v1/diff-tables" \
  -H "Content-Type: application/json" \
  -d '{"primaryKey":["sku","region"],"csvDelimiter":",","coerceCsvTypes":true,"numericTolerance":0,"before":"sku,region,price,stock\nPRO-100,US,49.99,120\nPRO-100,EU,54.99,80\nLEGACY-1,US,19.00,10","after":"sku,region,price,stock\nPRO-100,US,59.99,95\nPRO-100,EU,54.99,80\nNEW-200,US,99.00,250"}'
```
Expected result: unchangedCount=1, addedCount=1 (NEW-200::US), removedCount=1 (LEGACY-1::US), modifiedCount=1 (PRO-100::US price +10, stock -25).
