Skip to main content
Glama
README.md
# excel-to-api

Turn a supported Excel workbook (`.xlsx` / `.xlsm`) into a **serverless REST API**, **OpenAPI 3.1 spec**, **Streamable HTTP MCP server**, and **interactive browser Try-It** on Cloudflare Workers — powered by [Formualizer](https://github.com/PSU3D0/formualizer) Rust-to-WASM and [SheetPort](https://github.com/PSU3D0/sheetport-spec).

The Worker evaluates supported worksheet formulas with WebAssembly. The bundled demos measured 2–4 ms for warm evaluations locally. Workbook size, formula coverage and cold starts affect latency.

---

## Quickstart with your workbook

Use Node 22.12 or newer, npm, Python 3 and Git. A Cloudflare deployment of this starter requires **Workers Paid ($5/month minimum)** for its configured CPU limit. The WASM module is about 10.7 MiB raw and 3.78 MiB gzip. Compare the uncompressed upload size from `npm run deploy:dry-run` against Cloudflare's current 64 MiB Worker limit. [Cloudflare pricing](https://developers.cloudflare.com/workers/platform/pricing/) · [Worker limits](https://developers.cloudflare.com/workers/platform/limits/#worker-size)

```bash
npx degit PSU3D0/excel-to-api#v0.2.0 pricing-model-api
# Alternative: git clone --depth 1 --branch v0.2.0 https://github.com/PSU3D0/excel-to-api.git pricing-model-api
cd pricing-model-api
npm ci
npm run doctor
npm run init -- ../pricing-model.xlsx --slug pricing-model
```

Open `workbooks/pricing-model/preflight/PREFLIGHT.md` and fill the generated `fio.yaml` and `verification.json` using the [agent skill's complete examples](skills/excel-to-api/SKILL.md). The starter preserves `.xlsm` filenames and serves the formula-driven behavior. Use `npm run eval -- pricing-model --inputs '{"seats":8}'` to generate an engine regression vector. Use Excel-checked scenarios to establish independent parity, especially for blank or error baselines. Preflight exits 0 for ready, 1 for a blocking verdict, and 2 for invalid input.

```bash
npm test
npm run deploy:dry-run
npx wrangler whoami
npm run deploy    # use --secrets-file for a keyed deploy as described below
npm run smoke -- --url https://pricing-model-api.<your-subdomain>.workers.dev
```

With no API key configured the Worker is public. For keyed access, deploy with `npm run deploy -- --secrets-file /secure/path/to/worker-secrets.json`, where the private JSON file contains `{"API_KEY":"<your-generated-secret>"}`. You can also set a secret on an existing Worker with `npx wrangler secret put API_KEY`. Callers send `Authorization: Bearer <key>` or `x-api-key: <key>`. `GET /health` and CORS preflight stay accessible. The keyed browser Try-It opens at `/health?try=1` and loads the workbook contract after the visitor enters the key. Set `EXPOSE_TRACE` in Wrangler `vars` to override the default, which is on when keyed and off when public. The switch controls formula traces and port bindings across REST, OpenAPI, Try-It and MCP.

For keyed smoke tests, set `API_KEY` in the shell or pass `--api-key`. For GitHub Actions deployment, copy [the workflow](templates/deploy.yml) and [deployment notes](templates/DEPLOY.md) into your project. The smoke command prints the handover with URLs, request examples and verification results.

## Try the demos locally

```bash
git clone --depth 1 --branch v0.2.0 https://github.com/PSU3D0/excel-to-api.git
cd excel-to-api
npm ci
npm test
npm run dev       # http://localhost:8787
```

The registry falls back to `examples/` when `workbooks/` has no bundle directories. Run `npm run gen-registry` after adding or removing bundles. Builds use the first registered workbook by default, and `DEFAULT_WORKBOOK=<slug>` overrides it.

## What You Get Out of the Box

Every configured workbook automatically serves:

| Endpoint | Method | Description |
|---|---|---|
| `/` | `GET` | Interactive Try-It web UI (or JSON summary with `Accept: application/json` / `?format=json`) |
| `/evaluate` | `POST` | Typed JSON inputs -> recalculated outputs, optional cell formula trace when enabled (`trace: true`), latency & engine metadata |
| `/evaluate-batch` | `POST` | Batch-evaluate multiple scenarios against the same warm isolate baseline |
| `/openapi.json` | `GET` | OpenAPI 3.1.0 specification generated directly from `fio.yaml` port schemas and constraints |
| `/ports` | `GET` | Typed input/output port definitions, constraints, defaults, presets, and A1 bindings when trace is enabled |
| `/mcp` | `POST` | Streamable HTTP JSON-RPC 2.0 MCP server exposing `inspect_workbook` and `evaluate_workbook` |
| `/workbooks` | `GET` | Lists all bundled workbooks with scoped routes (`/workbooks/:slug/evaluate`, `/openapi.json`, `/mcp`) |
| `/health` | `GET` | Health status, workbook slugs, auth posture, trace setting, and engine version |

---

## Live API & MCP Examples

### 1. Evaluate via REST (`POST /evaluate`)

Default workbook: **U.S. SBA 7(a) FY 2026 Guaranty Fee Calculator** (`examples/sba-7a-guaranty-fee/`):

```bash
curl -s -X POST http://localhost:8787/evaluate \
  -H 'content-type: application/json' \
  -d '{
    "inputs": {
      "non_express_loan_amount": 500000
    }
  }'
```

Flat JSON payloads (`-d '{"non_express_loan_amount": 500000}'`) are also supported. Example response:

```json
{
  "workbook": {
    "slug": "sba-7a-guaranty-fee",
    "id": "sba-7a-guaranty-fee-2026",
    "title": "SBA 7(a) Guaranty Fee Calculator (FY 2026)",
    "edition": "2026"
  },
  "outputs": {
    "non_express_guaranty_pct": 0.75,
    "non_express_guaranty_amount": 375000,
    "non_express_guaranty_rate": 0.03,
    "non_express_guaranty_fee": 11250,
    "fee_for_this_loan_guaranty": 11250,
    "total_fee_due_new_loan": 11250,
    "total_fees_all_loans": 11250
  },
  "meta": {
    "engine": "formualizer-wasm@0.14.0",
    "elapsedMs": 4,
    "warm": true,
    "inputCount": 1,
    "outputCount": 11
  }
}
```

### 2. Call Any Workbook via MCP (`POST /mcp`)

Point Claude Desktop, Cursor, Codex, or any Streamable HTTP MCP client at `http://localhost:8787/mcp` (or your deployed `*.workers.dev/mcp` URL):

```json
{
  "mcpServers": {
    "excel-to-api": {
      "type": "http",
      "url": "http://localhost:8787/mcp"
    }
  }
}
```

Test directly with `curl`:

```bash
# List tools (inspect_workbook, evaluate_workbook)
curl -s -X POST http://localhost:8787/mcp \
  -H 'content-type: application/json' \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}'

# Evaluate the bundled SaaS Unit Economics workbook via MCP
curl -s -X POST http://localhost:8787/mcp \
  -H 'content-type: application/json' \
  -d '{
    "jsonrpc": "2.0",
    "id": 2,
    "method": "tools/call",
    "params": {
      "name": "evaluate_workbook",
      "arguments": {
        "workbook": "saas-unit-economics",
        "inputs": {
          "plan_tier": "Enterprise",
          "seats": 120,
          "billing_cycle": "Annual"
        }
      }
    }
  }'
```

---

## Architecture

```mermaid
flowchart LR
  XLSX["workbook.xlsx + fio.yaml + manifest.json"] -->|"Wrangler Data/Text imports"| Worker
  subgraph Worker["Cloudflare Worker Isolate (V8)"]
    WASM["Formualizer 0.14.0 WASM\n(1 warm baseline / isolate)"]
    Queue["Serialized Eval Queue\nbeginAction -> writeInputs -> evaluateOnce -> undo"]
    Router["src/worker.ts\n/ | /evaluate | /openapi.json | /mcp"]
    Router --> Queue --> WASM
  end
  Client["REST / Browser / cURL"] --> Router
  Agent["Claude / Cursor / Codex (MCP)"] --> Router
```

Each Worker isolate instantiates the pre-compiled Formualizer WebAssembly module once, loads the workbook into a warm baseline, and wraps every evaluation in `beginAction()` → `writeInputs()` → `evaluateOnce({ freezeVolatile: true })` → `endAction()` → `undo()`. If rollback ever fails, the isolate baseline is immediately discarded and rebuilt — preventing any cross-request state leakage.

---

## Included Verified Demos (`examples/`)

All shipped demos have public-domain or MIT provenance and match their exposed saved Excel outputs at the configured tolerance. The HUD contract exposes comparable 1 of the form’s five comparables, plus subject fields. Whole-workbook parity is reported separately.

| Demo Slug | Provenance / License | Formulas | Ports (In/Out) | Cached-Excel Parity | Warm Eval (`verify.mjs` / `wrangler dev`) |
|---|---|---:|---:|---:|---:|
| [`sba-7a-guaranty-fee`](examples/sba-7a-guaranty-fee/) *(default)* | U.S. SBA FY 2026 (`public-domain-gov`) | 114 | 4 / 11 | **11 / 11** | **1.7 ms** / **4 ms** |
| [`hud-section-8-market-rent`](examples/hud-section-8-market-rent/) | U.S. HUD Form 92273-S8 (`public-domain-gov`) | 61 | 11 / 9 | **9 / 9** | **1.0 ms** / **< 5 ms** |
| [`saas-unit-economics`](examples/saas-unit-economics/) | MIT Open Source (with `build_workbook.py`) | 35 | 7 / 11 | **11 / 11** | **0.7 ms** / **2 ms** |

*(Local benchmarks measured with Node.js + `wrangler dev --local` running `formualizer` 0.14.0 WASM on Linux x86_64.)*

---

## Project Structure

```text
├── wrangler.jsonc                 # Cloudflare Worker config (Data/Text rules for .xlsx & .yaml)
├── src/
│   ├── worker.ts                  # HTTP router (/, /evaluate, /evaluate-batch, /openapi.json, /mcp)
│   ├── sheetport.ts               # Formualizer 0.14.0 WASM runtime, warm cache, rollback & cell trace
│   ├── openapi.ts                 # OpenAPI 3.1.0 generator from fio.yaml
│   ├── mcp.ts                     # Streamable HTTP JSON-RPC 2.0 MCP server
│   ├── ui.ts                      # Zero-dependency interactive Try-It & API Explorer HTML
│   ├── registry.ts                # Generated registry for custom workbooks or demos
│   └── types.ts                   # TypeScript types for SheetPort & API envelopes
├── scripts/
│   ├── preflight.py               # Stage 1: Standalone OOXML DAG Pre-Flight analyzer (Python stdlib)
│   ├── verify.mjs                 # Stage 3: Standalone Formualizer WASM + Excel cache parity oracle
│   └── smoke-worker.mjs           # End-to-end live `wrangler dev --local` HTTP & MCP test suite
├── skills/excel-to-api/SKILL.md   # Portable Agent Skill for coding agents
├── workbooks/                     # Custom bundles created by init
├── templates/                     # GitHub Actions and deployment notes
├── examples/                      # Three verified public-domain / MIT demo workbooks
└── tests/sheetport.test.mjs       # Node.js unit & integration tests
```

---

## Running Tests

```bash
npm run typecheck       # TypeScript strict check
npm run verify          # Verify all custom bundles, or demos when no custom bundles exist
npm run test:unit       # Stage 1 + Stage 3 integration tests
npm run test:smoke      # Live `wrangler dev --local` HTTP, OpenAPI & MCP smoke suite
npm run deploy:dry-run  # Verify Cloudflare Worker bundle compilation without deploying
```

---

## Need Multi-Workbook Hosting, Versioned Editions or Managed Keys?

This starter is MIT-licensed and ready to self-host on Cloudflare Workers for single or small sets of workbooks. For teams managing large workbook fleets with versioned annual editions, multiple API keys, key rotation, governance, and audit logs, check out **[Formualizer Catalog & Cloud](https://formualizer.com)**.

## License

MIT — see [LICENSE](LICENSE). Bundled government workbooks (`examples/sba-7a-guaranty-fee/workbook.xlsx` and `examples/hud-section-8-market-rent/workbook.xlsx`) are U.S. Federal Government works in the public domain.