# DOM Harvest & Table Grid Edge API (v1.0.0)

> Turn noisy HTML tables, repeating product grids, and JSON-LD into clean typed JSON with >90% LLM token reduction.

Pure-TypeScript HTML structure harvester that resolves complex multi-row rowspan/colspan tables into typed 2D JSON matrices, auto-detects 100-500 repeating product/listing cards without selectors, extracts JSON-LD & OpenGraph metadata, and executes declarative CSS-schema scraping.

## Why Agents Use This API Instead of DIY
Dumping raw 300KB HTML into an LLM burns $0.05-$0.30 in context tokens and truncates past item 20; DIY regex/table parsers break on multi-row thead colspan + rowspan merges. DOM Harvest extracts all 500 items deterministically in <20ms for $0.001-$0.002.

## Connection & Payment (x402 Default + Optional Bearer API Key)
- **MCP Server (Streamable HTTP):** `https://dom-harvest.apikeg.com/mcp` (Registry ID: `com.apikeg/dom-harvest` — `initialize`, `tools/list`, `resources/*`, and `prompts/*` are free)
- **OpenAPI 3.1 Spec:** [openapi.json](https://dom-harvest.apikeg.com/openapi.json)
- **Full Schema & Examples:** [llms-full.txt](https://dom-harvest.apikeg.com/llms-full.txt)
- **RFC 9727 API Catalog:** [.well-known/api-catalog](https://dom-harvest.apikeg.com/.well-known/api-catalog)
- **x402 Bazaar Manifest:** [.well-known/x402.json](https://dom-harvest.apikeg.com/.well-known/x402.json)
- **MCP Discovery Manifest:** [.well-known/mcp.json](https://dom-harvest.apikeg.com/.well-known/mcp.json)
- **A2A Agent Card:** [.well-known/agent-card.json](https://dom-harvest.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
- [`harvest_page_structures`](https://dom-harvest.apikeg.com/tools/harvest-page-structures.md) (`POST https://dom-harvest.apikeg.com/v1/harvest-page-structures`) — $0.002 USD per HTML page structure harvest (x402 instant micropayment): Zero-selector structural HTML harvester: extracts canonical/OpenGraph/Twitter metadata, Schema.org JSON-LD, normalized 2D tables (resolving multi-header rowspan/colspan merges + cell links), and repeating sibling card collections across 100-500 items without truncation.
- [`extract_by_schema`](https://dom-harvest.apikeg.com/tools/extract-by-schema.md) (`POST https://dom-harvest.apikeg.com/v1/extract-by-schema`) — $0.001 USD per declarative CSS-schema extraction (x402 instant micropayment): Deterministic CSS-selector record extractor supporting descendant/child/attribute/group selectors, relative URL resolution against baseUrl, numeric currency/comma coercion, boolean flags, inner HTML serialization, and multi-value arrays.

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

## Common Agent Use Cases
- parse HTML table with rowspan and colspan to JSON API
- extract all product cards from raw HTML without CSS selectors MCP
- reduce HTML scraping LLM token usage structured JSON
- declarative CSS selector HTML to typed JSON schema API
- extract Schema.org JSON-LD and OpenGraph metadata from HTML

---

## Detailed Tool Specifications

### `harvest_page_structures` — Auto-Harvest Tables, Repeating Cards & Metadata
- **REST Endpoint:** `POST https://dom-harvest.apikeg.com/v1/harvest-page-structures`
- **Tool Doc Page:** https://dom-harvest.apikeg.com/tools/harvest-page-structures
- **MCP Tool Name:** `harvest_page_structures`
- **Pricing:** $0.002 USD per HTML page structure harvest (x402 instant micropayment)
- **Side Effects:** readOnly=true, idempotent=true, destructive=false
- **Build vs. Buy ROI:** Compresses 250KB+ noisy DOMs by >90% tokens without dropping items 21-500 or misaligning colspan/rowspan financial columns; runs deterministically in <20ms at $0.002.

#### Input JSON Schema
```json
{
  "type": "object",
  "properties": {
    "html": {
      "type": "string",
      "minLength": 1,
      "maxLength": 4000000,
      "description": "Raw HTML page or fragment to tokenize and harvest into structured JSON."
    },
    "baseUrl": {
      "type": "string",
      "maxLength": 2048,
      "description": "Optional origin/page URL used to resolve relative href, src, canonical, and OpenGraph URLs."
    },
    "includeMatrix": {
      "type": "boolean",
      "default": true,
      "description": "Include the resolved 2D string matrix alongside typed row records on each extracted table."
    },
    "minCollectionItems": {
      "type": "integer",
      "default": 3,
      "minimum": 2,
      "maximum": 50,
      "description": "Minimum repeating sibling cards required to emit an auto-detected repeatingCollection."
    }
  },
  "required": [
    "html"
  ],
  "additionalProperties": false
}
```

#### Examples
**Harvest merged financial table and product cards** — Resolves hierarchical Q1/Q2 colspan headers, rowspan regions, JSON-LD, and repeating cards.
```bash
curl -X POST "https://dom-harvest.apikeg.com/v1/harvest-page-structures" \
  -H "Content-Type: application/json" \
  -d '{"baseUrl":"https://shop.example.com/catalog","includeMatrix":true,"minCollectionItems":3,"html":"<html><head><title>Catalog</title></head><body><table><thead><tr><th rowspan='2'>Region</th><th colspan='2'>Q1 2026</th></tr><tr><th>Revenue</th><th>Growth</th></tr></thead><tbody><tr><td>NA</td><td>$1,200,000</td><td>18%</td></tr></tbody></table></body></html>"}'
```
Expected result: Returns metadata, jsonLd, normalized tables with 'Q1 2026 / Revenue' typed numeric rows, repeatingCollections, and token-reduction metrics.

### `extract_by_schema` — Extract Records by Declarative CSS Schema
- **REST Endpoint:** `POST https://dom-harvest.apikeg.com/v1/extract-by-schema`
- **Tool Doc Page:** https://dom-harvest.apikeg.com/tools/extract-by-schema
- **MCP Tool Name:** `extract_by_schema`
- **Pricing:** $0.001 USD per declarative CSS-schema extraction (x402 instant micropayment)
- **Side Effects:** readOnly=true, idempotent=true, destructive=false
- **Build vs. Buy ROI:** Eliminates brittle ad-hoc cheerio/regex glue code and runs identically at the Cloudflare edge in <10ms for $0.001.

#### Input JSON Schema
```json
{
  "type": "object",
  "properties": {
    "html": {
      "type": "string",
      "minLength": 1,
      "maxLength": 4000000,
      "description": "Raw HTML page or fragment."
    },
    "baseUrl": {
      "type": "string",
      "maxLength": 2048,
      "description": "Optional page URL used to resolve relative URLs when field type is 'url'."
    },
    "itemSelector": {
      "type": "string",
      "minLength": 1,
      "maxLength": 512,
      "description": "CSS selector matching each repeating record element (or 'body' / 'html' for single-object page extraction)."
    },
    "fields": {
      "type": "object",
      "additionalProperties": {
        "type": "object",
        "properties": {
          "selector": {
            "type": "string",
            "minLength": 1,
            "maxLength": 512,
            "description": "CSS selector evaluated within each matched item element (use ':scope' to target the item element itself)."
          },
          "attribute": {
            "type": "string",
            "minLength": 1,
            "maxLength": 128,
            "description": "Optional HTML attribute name to read (e.g. 'href', 'src', 'data-price'). Omit to extract text or inner HTML."
          },
          "type": {
            "type": "string",
            "enum": [
              "string",
              "number",
              "url",
              "boolean",
              "html"
            ],
            "default": "string",
            "description": "Coercion type: 'string', 'number' (strips currency/commas), 'url' (resolves against baseUrl), 'boolean', or 'html'."
          },
          "multiple": {
            "type": "boolean",
            "default": false,
            "description": "When true, extracts an array across all matching elements inside each item instead of the first match."
          }
        },
        "required": [
          "selector"
        ],
        "additionalProperties": false,
        "description": "Declarative extraction rule for a single field."
      },
      "description": "Map of output property names to declarative CSS selector + type coercion rules."
    }
  },
  "required": [
    "html",
    "itemSelector",
    "fields"
  ],
  "additionalProperties": false
}
```

#### Examples
**Extract typed e-commerce product records**
```bash
curl -X POST "https://dom-harvest.apikeg.com/v1/extract-by-schema" \
  -H "Content-Type: application/json" \
  -d '{"baseUrl":"https://store.example.com/deals/","itemSelector":"article.product-card","fields":{"sku":{"selector":":scope","attribute":"data-sku","type":"string"},"title":{"selector":"h3.title","type":"string"},"url":{"selector":"a.card-link","attribute":"href","type":"url"},"price":{"selector":".price-current","type":"number"},"inStock":{"selector":".badge-in-stock","type":"boolean"},"tags":{"selector":"ul.tags > li","type":"string","multiple":true}},"html":"<div class='grid'><article class='product-card' data-sku='SKU-9'><a class='card-link' href='../p/sku-9'><h3 class='title'>Pro Dock</h3></a><span class='price-current'>$189.99</span><span class='badge-in-stock'>In Stock</span><ul class='tags'><li>USB4</li><li>100W PD</li></ul></article></div>"}'
```
Expected result: Returns 1 typed item with url='https://store.example.com/p/sku-9', price=189.99, inStock=true, tags=['USB4', '100W PD'].
