Skip to main content
Glama
StructuraMCP

StructuraMCP

StructuraMCP

Messy construction & procurement PDFs in, schema-strict JSON and CSV out.

StructuraMCP turns multi-page Bills of Quantities, supplier quotes, commercial/VAT invoices and technical spec sheets into validated JSON (and CSV) through both a Model Context Protocol server (Streamable HTTP + stdio) and a REST API. It runs a free deterministic parser first (PyMuPDF + pdfplumber) and pays for an LLM only on pages it could not read with confidence, which keeps cost of goods well under $0.01 per page while charging $0.08 per parsed page.

MCP endpoint

POST/GET /mcp (Streamable HTTP), or structura-mcp --transport stdio

REST

/v1/..., OpenAPI at /openapi.json, docs at /docs

Agent discovery

/llms.txt, /openapi.json, /.well-known/mcp.json

Schemas

boq, invoice, quote, spec_sheet

Billing

$0.08/page, prepaid credits, Stripe metered subscriptions, or X-Payment-Proof per request


How it works

PDF ──► sha256 + schema fingerprint ──► Redis result cache ──(hit)──► response (no extraction, no LLM)
             │ miss
             ▼
   single-flight Redis lock (identical concurrent requests wait for the first one)
             ▼
   Deterministic extractor (src/extractors/deterministic.py)
     1. PyMuPDF find_tables()         ruled/grid tables
     2. pdfplumber extract_tables()   second opinion
     3. word-geometry "virtual table" borderless tables (header words become column anchors)
     + header→field synonym matching, multi-page stitching, section headings, wrapped
       descriptions, totals / carried-forward rows, EU & US number formats, units normalisation,
       header fields (invoice no., dates, parties, VAT IDs, currency, validity, standards)
             ▼
   Pydantic v2 validation ──► confidence score (header coverage, row quality,
                              qty×rate=amount, totals reconcile, completeness, identity)
             │ score ≥ 0.80 → done
             ▼
   Guardrails: margin circuit-breaker, per-document budget (pages × $0.01), per-key monthly cap
             ▼
   LLM fallback on weak pages only (text layer, or a 100-dpi image for scanned pages),
   provider-native JSON-schema structured outputs, one repair retry, LLM response cached
   separately so the same document+schema is never paid for twice
             ▼
   merge → re-score → keep the better result → cache → failure log (if still weak)

Low-confidence results are appended to logs/failed_extractions.jsonl (and a capped Redis list) with unmapped headers and sample rows. scripts/self_heal_agent.py reads those logs nightly and drafts parser patches (see Self-healing loop).


Related MCP server: document-to-json-mcp

Quick start

Docker Compose (API + Redis)

cp .env.example .env            # set STRUCTURA_ADMIN_TOKEN at minimum
docker compose up -d --build
curl localhost:8000/healthz

# self-serve: anyone can get a key with STRUCTURA_FREE_TRIAL_PAGES free pages (one per email)
curl -s -X POST localhost:8000/v1/keys -H 'content-type: application/json' -d '{"email": "you@example.com"}'

# admin: create an API key with 500 prepaid pages
curl -s -X POST localhost:8000/admin/keys \
  -H "X-Admin-Token: $STRUCTURA_ADMIN_TOKEN" -H 'content-type: application/json' \
  -d '{"customer":"acme","plan":"prepaid","credits":500}'

Local (uv)

uv sync
redis-server --daemonize yes
uv run structura-mcp                         # REST + MCP on :8000
uv run structura-mcp --transport stdio        # MCP over stdio
uv run structura-mcp --transport streamable-http   # MCP only, via mcp.run(transport="streamable-http")
uv run pytest -q

Parse a document

# multipart upload
curl -s localhost:8000/v1/parse -H "Authorization: Bearer $KEY" \
  -F file=@boq.pdf -F schema=boq -F output_format=json

# URL or base64 (JSON body); CSV output
curl -s localhost:8000/v1/parse/url -H "Authorization: Bearer $KEY" -H 'content-type: application/json' \
  -d '{"schema":"invoice","pdf_url":"https://example.com/invoice.pdf","output_format":"csv"}'

Response (abridged):

{
  "schema": "boq", "pages": 2, "method": "deterministic", "confidence": 1.0,
  "confidence_breakdown": {"header_coverage": 1.0, "row_quality": 1.0, "arithmetic": 1.0, "totals": 1.0, "completeness": 1.0},
  "needs_review": false, "cache_hit": false, "warnings": [],
  "billing": {"pages_charged": 2, "amount_usd": 0.16, "repeat_within_24h_free": false, "credit_balance_pages": 498},
  "document": {
    "project_name": "Riverside Clinic Extension", "currency": "USD",
    "items": [{"item_code": "1.01", "description": "Excavate oversite to remove topsoil 150mm deep",
               "unit": "m2", "qty": 1250.0, "rate": 4.5, "amount": 5625.0,
               "section": "BILL NO. 1 - SUBSTRUCTURE", "page": 1, "arithmetic_ok": true}],
    "stated_total": 160925.13, "computed_total": 160925.13, "totals_reconcile": true
  }
}

MCP

Tools

Tool

Cost

Purpose

parse_document(schema, pdf_url | pdf_base64, output_format, allow_llm)

$0.08/page

Extract a PDF into a schema; returns document, CSV, confidence, warnings, billing

validate_boq_schema(document)

free

Strict validation + qty×rate=amount + totals reconciliation

list_schemas(include_json_schema)

free

Schema names, versions, fingerprints, CSV columns, JSON Schemas

compare_supplier_quotes(quotes)

free

Line up parsed quotes, cheapest supplier per line and overall

Tool errors are raised as MCP tool errors whose text is the same structured JSON as the REST API (code, message, hint, valid_schemas, did_you_mean, payment_options, ...), so an agent can correct itself and retry.

claude_desktop_config.json

Remote server (hosted instance) through the mcp-remote bridge:

{
  "mcpServers": {
    "structura": {
      "command": "npx",
      "args": [
        "-y", "mcp-remote", "https://api-production-50c65b43.up.railway.app/mcp",
        "--header", "Authorization: Bearer ${STRUCTURA_API_KEY}"
      ],
      "env": { "STRUCTURA_API_KEY": "sk_struct_..." }
    }
  }
}

Local stdio server (runs the parser on your machine, bills against your key in your Redis):

{
  "mcpServers": {
    "structura-local": {
      "command": "uv",
      "args": ["--directory", "/path/to/structura-mcp", "run", "structura-mcp", "--transport", "stdio"],
      "env": {
        "REDIS_URL": "redis://localhost:6379/0",
        "STRUCTURA_API_KEY": "sk_struct_...",
        "STRUCTURA_LLM_PROVIDER": "anthropic",
        "ANTHROPIC_API_KEY": "sk-ant-..."
      }
    }
  }
}

Clients with native remote-MCP support (Claude connectors, Cursor, VS Code, the MCP Inspector) can point straight at https://api-production-50c65b43.up.railway.app/mcp with an Authorization: Bearer header.

MCP marketplace / registry listing metadata

The live listing is server.json (remote-only), published to the official MCP Registry by .github/workflows/publish-mcp-registry.yml (run it from the Actions tab, or push a v* tag after bumping version). The fuller template below also covers a PyPI package:

{
  "name": "io.github.your-org/structura-mcp",
  "title": "StructuraMCP",
  "description": "Convert messy construction & procurement PDFs (Bills of Quantities, supplier quotes, VAT invoices, spec sheets) into schema-strict JSON and CSV. Deterministic parsing first, LLM fallback only when needed. $0.08 per page.",
  "version": "1.0.0",
  "websiteUrl": "https://api-production-50c65b43.up.railway.app",
  "repository": { "url": "https://github.com/your-org/structura-mcp", "source": "github" },
  "remotes": [
    {
      "type": "streamable-http",
      "url": "https://api-production-50c65b43.up.railway.app/mcp",
      "headers": [
        { "name": "Authorization", "description": "Bearer API key (sk_struct_...)", "isRequired": true, "isSecret": true }
      ]
    }
  ],
  "packages": [
    {
      "registryType": "pypi",
      "identifier": "structura-mcp",
      "version": "1.0.0",
      "transport": { "type": "stdio" },
      "environmentVariables": [
        { "name": "STRUCTURA_API_KEY", "isRequired": true, "isSecret": true },
        { "name": "REDIS_URL", "isRequired": true }
      ]
    }
  ]
}

Listing copy:

  • Category: Data extraction · Construction · Procurement · Finance

  • Tagline: BoQs, quotes and invoices from PDF to clean JSON in one tool call.

  • Tools: parse_document, validate_boq_schema, list_schemas, compare_supplier_quotes

  • Pricing: $0.08 per parsed page; validation, schema listing and quote comparison are free; repeat parses of the same document within 24h are free.

  • Auth: API key (Bearer) or per-request Stripe payment proof (X-Payment-Proof).

  • Keywords: bill of quantities, BoQ, quantity surveying, tender, supplier quote, RFQ, commercial invoice, VAT, HS code, spec sheet, PDF tables, structured output.


REST API

Method & path

Auth

Description

GET /

–

Service card (endpoints, tools, pricing)

GET /llms.txt

–

Agent discovery manifest (public/llms.txt, base URL and price filled in)

GET /openapi.json, /docs

–

OpenAPI 3.1

GET /.well-known/mcp.json

–

MCP endpoint manifest

GET /healthz, /readyz

–

Liveness / readiness (Redis, LLM, breaker)

GET /v1/schemas, /v1/schemas/{name}

–

Schema catalog / single JSON Schema

POST /v1/parse

key or proof

Multipart: file, schema, output_format, allow_llm

POST /v1/parse/url

key or proof

JSON: schema + pdf_url or pdf_base64

POST /v1/validate/boq

–

Validate a BoQ document

POST /v1/compare/quotes

–

Compare parsed quotes

GET /v1/usage?month=YYYY-MM

key

Pages, amount, cache hits, LLM pages, balance

POST /v1/credits/checkout

key

Stripe Checkout URL for page credits

POST /billing/stripe/webhook

Stripe signature

Credits, suspension / reactivation

POST /admin/keys, /admin/keys/{id}/credits, GET /admin/breaker, POST /admin/breaker/reset

X-Admin-Token

Operations

output_format=csv returns text/csv with X-Structura-Confidence, X-Structura-Method, X-Structura-Pages-Charged and X-Structura-Needs-Review headers.

Actionable errors

Every error is JSON an agent can act on:

{"error": {"code": "unsupported_schema", "message": "Unknown schema 'boqx'.",
           "hint": "GET /v1/schemas and use one of valid_schemas.", "retryable": false,
           "docs": "https://api-production-50c65b43.up.railway.app/llms.txt#errors",
           "valid_schemas": ["boq", "invoice", "quote", "spec_sheet"], "did_you_mean": "boq"}}

Codes: unsupported_schema, missing_document, ambiguous_document, invalid_url, url_forbidden, url_not_pdf, url_fetch_failed, invalid_base64, invalid_pdf, corrupt_pdf, encrypted_pdf, empty_document, too_many_pages, file_too_large, invalid_request (with fields), invalid_api_key, account_suspended, payment_required, insufficient_credits, payment_not_settled, invalid_payment_proof, payment_proof_reused.


Billing, metering & guardrails

Price: STRUCTURA_PRICE_PER_PAGE_USD=0.08. Pages are counted before extraction and deducted atomically in Redis (Lua script) from the key's credit balance; if extraction fails the pages are refunded. Re-parsing the same document + schema with the same key within 24h is free.

Ways to pay

  1. Prepaid credits: POST /v1/credits/checkout {"pages": 500} returns a Stripe Checkout URL; the checkout.session.completed webhook adds the pages.

  2. Metered subscription (plan=metered): every charge is queued and flushed to Stripe Billing Meters (event_name=STRIPE_METER_EVENT_NAME, payload.value = pages, idempotent identifier) by a background reporter. Create a meter in the Stripe dashboard and attach a metered price of $0.08/unit to the customer's subscription. invoice.payment_failed / customer.subscription.deleted suspend the key; invoice.paid reactivates it.

  3. X-Payment-Proof (no account needed): a succeeded USD Stripe PaymentIntent id. It is verified once with Stripe, converted to pages at $0.08, and can't be redeemed twice; unspent pages stay attached to that proof.

Without credit, paid endpoints answer HTTP 402 with pages_required, amount_due_usd, credit_balance_pages, payment_options, plus X-Price-Per-Page-USD and a WWW-Authenticate: Payment ... header. The PaymentGateMiddleware rejects unauthenticated paid requests before reading the upload.

Guardrails (src/billing/guardrails.py)

  • Margin circuit-breaker: per-minute revenue and LLM-cost buckets in Redis. When LLM cost exceeds 25% of revenue over the last hour (STRUCTURA_MAX_LLM_COST_RATIO, STRUCTURA_BREAKER_WINDOW_S), the LLM fallback is switched off service-wide for STRUCTURA_BREAKER_COOLDOWN_S. Results stay available (deterministic) with a warning.

  • Per-document budget: an LLM call is planned only if its estimated cost is within pages × STRUCTURA_COGS_TARGET_PER_PAGE_USD ($0.01); otherwise the weakest pages that fit are sent.

  • Per-key monthly LLM cap: monthly_llm_cap_usd per key (default STRUCTURA_DEFAULT_MONTHLY_LLM_CAP_USD).

Unit economics. With Claude Haiku 5.5 ($0.10 / $0.50 per million input/output tokens) a dense page is about 1,000 input and 600 output tokens: roughly $0.0004 per LLM page. Most pages never reach the LLM, so COGS stays far below the $0.01/page target and the 25% breaker.


Self-healing maintenance loop

.github/workflows/self-heal.yml runs nightly (and on demand):

  1. Runs the unit tests.

  2. scripts/self_heal_agent.py nightly regenerates the synthetic messy PDFs (tests/fixtures/samples.py: multi-page ruled BoQ with carried/brought-forward rows, borderless EU-format BoQ with wrapped descriptions, unknown header vocabulary, invoice with VAT, borderless quote, spec sheet), scores field-level accuracy against ground truth and compares with tests/fixtures/baseline_accuracy.json.

  3. It reads the production failure log (optionally downloaded from FAILURE_LOG_URL) plus the regression's own failures, profiles every column with an unknown header (unit tokens, long text, code patterns, qty × rate = amount relationships) and drafts a patch to the HEADER_SYNONYMS block in src/extractors/deterministic.py.

  4. The patch is kept only if accuracy does not get worse; the baseline is raised when it improves.

  5. If accuracy dropped or a patch was drafted, peter-evans/create-pull-request opens a PR with the patch and reports/self_heal_report.md. Nothing merges without review. With STRUCTURA_LLM_PROVIDER set, the LLM also reviews each proposed synonym in the report.

Run it yourself:

uv run python scripts/self_heal_agent.py regress                 # accuracy table
uv run python scripts/self_heal_agent.py triage --with-regression # draft patch to patches/*.diff
uv run python scripts/self_heal_agent.py nightly --open-pr        # outside Actions (GITHUB_TOKEN, GITHUB_REPOSITORY)

The shipped boq_unknown_headers sample (headers "Pos. / Narrative / Meas. / Qty / Unit Cost / Extn") is a deliberate self-heal target: the deterministic parser scores 0.03 on it, and the agent's drafted patch (Narrative → description, Meas. → unit, Extn → amount because it equals qty × rate) lifts it to 1.00.


Running on a free host (Railway Free plan)

Railway's Free plan ($0, no card, $5 of usage a month) puts a service to sleep after a few idle minutes without outbound traffic and wakes it on the next request. Set STRUCTURA_IDLE_SLEEP=true so StructuraMCP lets that happen: it skips the background Stripe usage loop, flushes queued usage itself, and closes its Redis connections after STRUCTURA_IDLE_DISCONNECT_S (default 20) seconds without requests. The first request after a sleep takes a few extra seconds while the container and Redis wake up.

Getting paid

All revenue is collected by Stripe: metered subscriptions report usage through Stripe Metered Billing (Billing Meters, STRIPE_METER_EVENT_NAME), and prepaid credit top-ups and X-Payment-Proof payments are ordinary Stripe payments. Money lands in your Stripe balance and Stripe pays it out on its payout schedule.

  1. Activate your Stripe account (business details and identity verification).

  2. Add your payout destination under Settings → Payouts in the Stripe Dashboard (https://dashboard.stripe.com/settings/payouts): a bank account in your account's country (some countries also allow a debit card). Payout timing and options are described in Stripe's guide: https://docs.stripe.com/payouts.

  3. Set STRIPE_SECRET_KEY and STRIPE_WEBHOOK_SECRET in .env, create the Billing Meter, and point a webhook at https://<your-domain>/billing/stripe/webhook (events: checkout.session.completed, invoice.paid, invoice.payment_failed, customer.subscription.created/updated/deleted/resumed).

PayPal: Stripe does not pay out to PayPal. If you want the money in PayPal, either withdraw Stripe payouts to your bank and move them to PayPal from there, or replace the Stripe gateway (StripeGateway / StripeReporter in src/billing/metering.py) with a billing provider that supports PayPal.


Configuration

All settings are environment variables; see .env.example. The important ones:

Variable

Default

Meaning

REDIS_URL

redis://localhost:6379/0

Cache, credits, usage, breaker

STRUCTURA_LLM_PROVIDER

none

none, openai (any OpenAI-compatible endpoint via OPENAI_BASE_URL) or anthropic

STRUCTURA_LLM_MODEL

provider default

claude-haiku-5-5 / gpt-6-luna

STRUCTURA_LLM_INPUT/OUTPUT_USD_PER_MTOK

0.10 / 0.50

Prices used for cost accounting; set them for your model

STRUCTURA_CONFIDENCE_THRESHOLD

0.80

Below this, the LLM fallback runs

STRUCTURA_PRICE_PER_PAGE_USD

0.08

Revenue per page

STRUCTURA_MAX_LLM_COST_RATIO

0.25

Breaker trips above this cost/revenue ratio

STRIPE_SECRET_KEY, STRIPE_WEBHOOK_SECRET, STRIPE_METER_EVENT_NAME

–

Stripe integration


Project layout

structura-mcp/
├── pyproject.toml / uv.lock
├── Dockerfile, docker-compose.yml, .env.example
├── public/llms.txt                 agent discovery manifest
├── src/
│   ├── main.py                     unified FastAPI + FastMCP Streamable HTTP app, CLI
│   ├── mcp_tools.py                MCP tools
│   ├── config.py, services.py      settings, service container, parse orchestration
│   ├── errors.py, documents.py     actionable errors, URL/base64 intake with SSRF guard
│   ├── billing/metering.py         credits, payment proofs, usage, Stripe meters & webhooks
│   ├── billing/guardrails.py       margin circuit-breaker, spend caps
│   ├── extractors/deterministic.py PyMuPDF + pdfplumber table & line-item parser
│   ├── extractors/llm_fallback.py  schema-enforced LLM fallback (OpenAI-compatible / Anthropic)
│   ├── extractors/pipeline.py      hybrid router, confidence scorer, Redis cache
│   └── schemas/                    boq, invoice, quote (+ comparison), spec_sheet
├── scripts/self_heal_agent.py      regression + triage + patch drafting + PR
├── .github/workflows/              ci.yml, self-heal.yml
└── tests/                          test_extractors.py, test_mcp_server.py, fixtures/

Design decisions & assumptions

These were made without further input; change them freely.

  • Package name src. The requested tree puts modules directly in src/, so src is the importable package (uvicorn src.main:app). A few helper modules were added next to the requested ones (config.py, services.py, errors.py, documents.py, schemas/common.py, schemas/spec_sheet.py) to keep the requested files focused.

  • Spec sheets get their own spec_sheet schema (attribute/value/unit), since the brief lists them as an input type but the tree only named three schema files.

  • "Supplier Comparison Quote" is modelled as one SupplierQuote per PDF plus compare_quotes() / the compare_supplier_quotes tool to compare several suppliers.

  • Numbers are Decimal internally and JSON numbers on output. Derived fields (arithmetic_ok, computed_total, totals_reconcile) are computed, and stripped automatically when a document is sent back for validation.

  • Arithmetic mismatches don't fail validation. Source documents often contain them; they're flagged per line and lower the confidence score instead.

  • Cache hits are still billed (the customer gets a result), except repeat parses by the same key within 24h, which are free so retrying agents aren't double-charged. The LLM is never paid twice for the same document + schema + page set.

  • X-Payment-Proof is implemented as a Stripe PaymentIntent id verified server-side through the Stripe API. Stripe's MPP reference server library is Node (mppx); if you want the full MPP challenge/credential flow, put an mppx proxy in front and forward the settled PaymentIntent id in this header.

  • Default LLMs are the cheapest current models with JSON-schema structured outputs (claude-haiku-5-5 at $0.10/$0.50 per MTok; gpt-6-luna for OpenAI). Check OpenAI's current standard-tier price for your model and set the *_USD_PER_MTOK variables.

  • Scanned pages (no text layer) are sent to the LLM as page images, within the same budget rules. There is no OCR engine in the deterministic path.

  • URL fetching blocks private, loopback and link-local addresses (SSRF), follows redirects and re-checks the final host, and caps the download size.

  • API keys are stored only as SHA-256 prefixes in Redis.

License

GNU AGPL-3.0. You can use, modify and self-host StructuraMCP; if you run a modified version as a network service, you must publish your changes under the same license. The hosted service at https://api-production-50c65b43.up.railway.app is the easiest way to use it.

Available Tools

4 tools
compare_supplier_quotesCompare supplier quotesA
Read-onlyIdempotent

Line up several parsed supplier quotes item-by-item and pick the cheapest offer per line. Free.

Inputs: quotes (required). Returns: object

list_schemasList extraction schemasB
Read-onlyIdempotent

List the supported document schemas, their versions, CSV columns and (optionally) JSON Schemas.

Inputs: include_json_schema. Returns: object

parse_documentParse PDF to structured JSON/CSVA
Read-only

Extract line items and header fields from a PDF into the chosen schema.

Returns document (schema-strict JSON), csv (optional), confidence 0-1 with a breakdown, method (deterministic | hybrid | llm), warnings and billing info.

Inputs: schema (required), pdf_url, allow_llm, pdf_base64, +1 more. Returns: object

validate_boq_schemaValidate a Bill of QuantitiesB
Read-onlyIdempotent

Validate a BoQ against the strict schema and check qty x rate = amount and totals. Free.

Inputs: document (required). Returns: object

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A3.6/5.0

    Scored across 4 tools

    Disambiguation4/5

    Each tool has a distinct role: schema listing, PDF parsing, BoQ arithmetic validation, and supplier quote comparison. The only mild overlap is that parse_document emits schema-strict JSON while validate_boq_schema checks schema/arithmetic, so an agent might briefly wonder whether parsing implies validation, but the descriptions clarify that validation is a separate check on an existing BoQ.

    Naming Consistency5/5

    All four names follow a consistent snake_case verb_noun pattern (validate_boq_schema, parse_document, list_schemas, compare_supplier_quotes). Object nouns match their resources clearly.

    Tool Count4/5

    Four focused tools sit comfortably within a reasonable scope for a BoQ/document-extraction server, and each earns its place. It is on the lean side, with no batch-parse or export counterpart, but nothing feels padded.

    Completeness4/5

    The surface covers the core lifecycle: discover schemas, parse documents, validate extracted BoQs, and compare supplier quotes, plus CSV output. Minor gaps remain, such as correcting/editing parsed line items or exporting to spreadsheet formats, but these are workarounds an agent can handle by re-parsing.

    Maintenance

    ActivityMaintained
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      F
      maintenance
      Enables AI agents to extract structured JSON from invoices and receipts in PDF and image formats using Claude Vision. Supports full document parsing, line item extraction, validation, and batch CSV export with API key or cryptocurrency payment options.
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Converts architectural PDF plans into dimension-verified millimetre geometry, IFC models, and CPU-rendered views, with built-in validation for boundaries, areas, and overlaps.
      MIT
    • F
      license
      Not graded
      quality
      D
      maintenance
      Enables reading entire PDF documents into validated structured JSON, including tables, key-values, and markdown, with read-only extraction tools and layout reconstruction.
      -