# Sheet SQL & Multi-Tab XLSX Engine API (v1.0.0)

> Run real SQLite JOINs and window functions over messy CSV/JSON tables and export styled multi-tab .xlsx workbooks in milliseconds.

Ephemeral SQLite analytics sandbox for multi-table CSV/TSV and JSON datasets (JOINs, CTEs, window functions, automatic currency coercion) plus zero-dependency OpenXML multi-sheet .xlsx workbook generation.

## Why Agents Use This API Instead of DIY
Eliminates spinning up Python/pandas/openpyxl sandboxes, avoids LLM arithmetic hallucinations on large CSVs, strips '$1,250.50' currency strings automatically, and emits genuine frozen-header Excel formulas.

## Connection & Payment (x402 Default + Optional Bearer API Key)
- **MCP Server (Streamable HTTP):** `https://sheet-sql.apikeg.com/mcp` (Registry ID: `com.apikeg/sheet-sql` — `initialize`, `tools/list`, `resources/*`, and `prompts/*` are free)
- **OpenAPI 3.1 Spec:** [openapi.json](https://sheet-sql.apikeg.com/openapi.json)
- **Full Schema & Examples:** [llms-full.txt](https://sheet-sql.apikeg.com/llms-full.txt)
- **RFC 9727 API Catalog:** [.well-known/api-catalog](https://sheet-sql.apikeg.com/.well-known/api-catalog)
- **x402 Bazaar Manifest:** [.well-known/x402.json](https://sheet-sql.apikeg.com/.well-known/x402.json)
- **MCP Discovery Manifest:** [.well-known/mcp.json](https://sheet-sql.apikeg.com/.well-known/mcp.json)
- **A2A Agent Card:** [.well-known/agent-card.json](https://sheet-sql.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
- [`query_tabular_data`](https://sheet-sql.apikeg.com/tools/query-tabular-data.md) (`POST https://sheet-sql.apikeg.com/v1/query-tabular-data`) — $0.002 base (up to $0.01 max $0.002 base + $0.001 per 1,000 total input rows (capped at $0.01), x402 variable settlement): Ingests 1–10 named RFC 4180 CSV/TSV or JSON row-array datasets into an ephemeral zero-retention SQLite sandbox, coerces currency columns (e.g. '$1,250.50' -> 1250.5), runs read-only SQL (JOIN, GROUP BY, CTEs, window functions), and returns typed rows, Markdown preview, inferred schemas, and optional .xlsx export.
- [`build_xlsx_workbook`](https://sheet-sql.apikeg.com/tools/build-xlsx-workbook.md) (`POST https://sheet-sql.apikeg.com/v1/build-xlsx-workbook`) — $0.003 USD per multi-sheet .xlsx workbook generation (x402 instant micropayment): Compiles 1–20 structured JSON datasets into a genuine Office Open XML (.xlsx) workbook with bold shaded headers, frozen top rows, auto-sized columns, numeric formatting, formula-injection protection, and live Excel summary formulas (SUM, AVERAGE, MIN, MAX, COUNT).

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

## Common Agent Use Cases
- run SQL query on CSV and JSON files MCP tool
- join multiple CSV tables with SQLite window functions API
- generate multi-sheet Excel xlsx workbook with SUM formulas without Python
- clean currency columns $1,250.50 and aggregate revenue CSV API
- convert JSON data to styled Excel spreadsheet API

---

## Detailed Tool Specifications

### `query_tabular_data` — Query CSV & JSON Tables with SQLite
- **REST Endpoint:** `POST https://sheet-sql.apikeg.com/v1/query-tabular-data`
- **Tool Doc Page:** https://sheet-sql.apikeg.com/tools/query-tabular-data
- **MCP Tool Name:** `query_tabular_data`
- **Pricing:** $0.002 base (up to $0.01 max $0.002 base + $0.001 per 1,000 total input rows (capped at $0.01), x402 variable settlement)
- **Side Effects:** readOnly=true, idempotent=true, destructive=false
- **Build vs. Buy ROI:** Replaces fragile regex CSV parsers, LLM mental math errors, and heavy container sandboxes; runs real SQLite in <25ms with guaranteed ephemeral wipe.

#### Input JSON Schema
```json
{
  "type": "object",
  "properties": {
    "tables": {
      "type": "object",
      "additionalProperties": {
        "type": "string",
        "minLength": 1,
        "maxLength": 3800000,
        "description": "Raw RFC 4180 CSV/TSV string (auto-detecting ',', ';', or '\\t') or serialized JSON row-array string."
      },
      "description": "Map of 1 to 10 SQL table names (e.g. 'orders', 'customers') to CSV/TSV or JSON row-array payloads."
    },
    "sql": {
      "type": "string",
      "minLength": 1,
      "maxLength": 32768,
      "description": "Read-only SQLite SELECT or WITH (CTE) query supporting JOIN, GROUP BY, HAVING, and window functions (ROW_NUMBER() OVER (...), SUM, AVG)."
    },
    "coerceCurrencyNumbers": {
      "type": "boolean",
      "default": true,
      "description": "Automatically strip $, €, £, ¥ symbols, thousands commas, and accounting parentheses (e.g. '$1,250.50' -> 1250.5) when an entire column is numeric."
    },
    "maxRows": {
      "type": "integer",
      "minimum": 1,
      "maximum": 5000,
      "default": 1000,
      "description": "Maximum result rows returned in `rows` (1–5000, default 1000)."
    },
    "markdownPreviewRows": {
      "type": "integer",
      "minimum": 1,
      "maximum": 100,
      "default": 20,
      "description": "Maximum rows rendered in `markdownPreview` (1–100, default 20)."
    },
    "exportXlsx": {
      "type": "boolean",
      "default": false,
      "description": "When true, also exports the query result set as a styled OpenXML .xlsx workbook in `xlsxBase64`."
    },
    "xlsxSheetName": {
      "type": "string",
      "minLength": 1,
      "maxLength": 64,
      "description": "Optional worksheet tab name when `exportXlsx` is true (default 'Query Results')."
    },
    "xlsxSummaryRowFormulas": {
      "type": "object",
      "additionalProperties": {
        "type": "string",
        "enum": [
          "SUM",
          "AVERAGE",
          "MIN",
          "MAX",
          "COUNT",
          "COUNTA"
        ],
        "description": "Spreadsheet summary aggregation function (SUM, AVERAGE, MIN, MAX, COUNT, COUNTA)."
      },
      "description": "Optional summary row formulas keyed by output column name when `exportXlsx` is true (e.g. { total_revenue: 'SUM' })."
    }
  },
  "required": [
    "tables",
    "sql"
  ],
  "additionalProperties": false
}
```

#### Examples
**JOIN orders CSV with customers JSON and rank revenue per region**
```bash
curl -X POST "https://sheet-sql.apikeg.com/v1/query-tabular-data" \
  -H "Content-Type: application/json" \
  -d '{"coerceCurrencyNumbers":true,"maxRows":100,"markdownPreviewRows":10,"exportXlsx":true,"tables":{"orders":"order_id,customer_id,amount\n101,c1,\"$1,250.50\"\n102,c1,\"$749.50\"\n103,c2,\"$500.00\"","customers":"[{\"id\":\"c1\",\"name\":\"Acme Corp\",\"region\":\"US\"},{\"id\":\"c2\",\"name\":\"Globex\",\"region\":\"EU\"}]"},"sql":"SELECT c.name, c.region, SUM(o.amount) AS total_spend, ROW_NUMBER() OVER (ORDER BY SUM(o.amount) DESC) AS spend_rank FROM customers c LEFT JOIN orders o ON c.id = o.customer_id GROUP BY c.id, c.name, c.region ORDER BY total_spend DESC"}'
```
Expected result: Returns typed rows (Acme Corp total_spend=2000, spend_rank=1), GFM markdownPreview, inferredSchemas showing amount coerced to REAL, and base64 .xlsx.

### `build_xlsx_workbook` — Build Styled Multi-Sheet XLSX Workbook
- **REST Endpoint:** `POST https://sheet-sql.apikeg.com/v1/build-xlsx-workbook`
- **Tool Doc Page:** https://sheet-sql.apikeg.com/tools/build-xlsx-workbook
- **MCP Tool Name:** `build_xlsx_workbook`
- **Pricing:** $0.003 USD per multi-sheet .xlsx workbook generation (x402 instant micropayment)
- **Side Effects:** readOnly=true, idempotent=true, destructive=false
- **Build vs. Buy ROI:** Generates compliant PKZIP/OpenXML spreadsheets at the edge in <15ms without Python, openpyxl, SheetJS bloat, or broken CSV exports.

#### Input JSON Schema
```json
{
  "type": "object",
  "properties": {
    "fileName": {
      "type": "string",
      "default": "workbook.xlsx",
      "minLength": 1,
      "maxLength": 128,
      "description": "Output .xlsx filename metadata (automatically suffixed with .xlsx if omitted)."
    },
    "sheets": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "name": {
            "type": "string",
            "minLength": 1,
            "maxLength": 64,
            "description": "Worksheet tab name (sanitized and capped at Excel's 31-character limit)."
          },
          "columns": {
            "type": "array",
            "items": {
              "type": "string",
              "minLength": 1,
              "maxLength": 128
            },
            "minItems": 1,
            "maxItems": 200,
            "description": "Optional explicit column order. If omitted, column keys are inferred from `rows` in insertion order."
          },
          "headers": {
            "type": "object",
            "additionalProperties": {
              "type": "string",
              "minLength": 1,
              "maxLength": 128
            },
            "description": "Optional human-friendly header display labels keyed by column name (e.g. { mrr_usd: 'MRR (USD)' })."
          },
          "rows": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {},
              "additionalProperties": true,
              "description": "Row object mapping column names to typed cell values (number, string, boolean, or null)."
            },
            "minItems": 0,
            "maxItems": 10000,
            "description": "Structured JSON rows to populate on this worksheet."
          },
          "freezeHeader": {
            "type": "boolean",
            "default": true,
            "description": "Freeze top header row (`<pane ySplit=\"1\" state=\"frozen\"/>`)."
          },
          "coerceCurrencyNumbers": {
            "type": "boolean",
            "default": false,
            "description": "Coerce currency-formatted string cells (e.g. '$1,250.50') into typed numeric Excel cells."
          },
          "allowCellFormulas": {
            "type": "boolean",
            "default": false,
            "description": "When true, string cells starting with '=' (e.g. '=B2*C2') emit native OpenXML <f> formulas; when false, they stay literal strings to prevent formula injection."
          },
          "summaryRowFormulas": {
            "type": "object",
            "additionalProperties": {
              "type": "string",
              "enum": [
                "SUM",
                "AVERAGE",
                "MIN",
                "MAX",
                "COUNT",
                "COUNTA"
              ],
              "description": "Spreadsheet summary aggregation function (SUM, AVERAGE, MIN, MAX, COUNT, COUNTA)."
            },
            "description": "Optional summary row formulas keyed by column name (e.g. { revenue: 'SUM', deal_size: 'AVERAGE' })."
          },
          "summaryRowLabel": {
            "type": "string",
            "minLength": 1,
            "maxLength": 64,
            "description": "Optional label placed in column A of the summary row (default 'Total')."
          }
        },
        "required": [
          "name",
          "rows"
        ],
        "additionalProperties": false,
        "description": "Worksheet definition for an OpenXML .xlsx workbook."
      },
      "minItems": 1,
      "maxItems": 20,
      "description": "1 to 20 worksheets to compile into the multi-tab .xlsx archive."
    }
  },
  "required": [
    "sheets"
  ],
  "additionalProperties": false
}
```

#### Examples
**Generate a two-tab CFO revenue workbook with SUM and AVERAGE formulas**
```bash
curl -X POST "https://sheet-sql.apikeg.com/v1/build-xlsx-workbook" \
  -H "Content-Type: application/json" \
  -d '{"fileName":"q4-revenue-summary.xlsx","sheets":[{"name":"Regional Revenue","freezeHeader":true,"coerceCurrencyNumbers":true,"allowCellFormulas":false,"summaryRowFormulas":{"q4_revenue":"SUM","win_rate":"AVERAGE"},"rows":[{"region":"North America","q4_revenue":125000.5,"win_rate":0.34},{"region":"Europe","q4_revenue":84500.25,"win_rate":0.29}]}]}'
```
Expected result: Returns base64-encoded OpenXML .xlsx archive with frozen headers, auto-sized columns, numeric formatting, and =SUM(B2:B3) / =AVERAGE(C2:C3) summary row.
