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 |
|
REST |
|
Agent discovery |
|
Schemas |
|
Billing | $0.08/page, prepaid credits, Stripe metered subscriptions, or |
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 -qParse 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 |
| $0.08/page | Extract a PDF into a schema; returns document, CSV, confidence, warnings, billing |
| free | Strict validation + qty×rate=amount + totals reconciliation |
| free | Schema names, versions, fingerprints, CSV columns, JSON Schemas |
| 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_quotesPricing: $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 |
| – | Service card (endpoints, tools, pricing) |
| – | Agent discovery manifest ( |
| – | OpenAPI 3.1 |
| – | MCP endpoint manifest |
| – | Liveness / readiness (Redis, LLM, breaker) |
| – | Schema catalog / single JSON Schema |
| key or proof | Multipart: |
| key or proof | JSON: |
| – | Validate a BoQ document |
| – | Compare parsed quotes |
| key | Pages, amount, cache hits, LLM pages, balance |
| key | Stripe Checkout URL for page credits |
| Stripe signature | Credits, suspension / reactivation |
|
| 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
Prepaid credits:
POST /v1/credits/checkout {"pages": 500}returns a Stripe Checkout URL; thecheckout.session.completedwebhook adds the pages.Metered subscription (
plan=metered): every charge is queued and flushed to Stripe Billing Meters (event_name=STRIPE_METER_EVENT_NAME,payload.value= pages, idempotentidentifier) 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.deletedsuspend the key;invoice.paidreactivates it.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 forSTRUCTURA_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_usdper key (defaultSTRUCTURA_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):
Runs the unit tests.
scripts/self_heal_agent.py nightlyregenerates 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 withtests/fixtures/baseline_accuracy.json.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 = amountrelationships) and drafts a patch to theHEADER_SYNONYMSblock insrc/extractors/deterministic.py.The patch is kept only if accuracy does not get worse; the baseline is raised when it improves.
If accuracy dropped or a patch was drafted,
peter-evans/create-pull-requestopens a PR with the patch andreports/self_heal_report.md. Nothing merges without review. WithSTRUCTURA_LLM_PROVIDERset, 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.
Activate your Stripe account (business details and identity verification).
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.
Set
STRIPE_SECRET_KEYandSTRIPE_WEBHOOK_SECRETin.env, create the Billing Meter, and point a webhook athttps://<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 |
|
| Cache, credits, usage, breaker |
|
|
|
| provider default |
|
| 0.10 / 0.50 | Prices used for cost accounting; set them for your model |
| 0.80 | Below this, the LLM fallback runs |
| 0.08 | Revenue per page |
| 0.25 | Breaker trips above this cost/revenue ratio |
| – | 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 insrc/, sosrcis 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_sheetschema (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
SupplierQuoteper PDF pluscompare_quotes()/ thecompare_supplier_quotestool to compare several suppliers.Numbers are
Decimalinternally 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-Proofis 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 anmppxproxy 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-5at $0.10/$0.50 per MTok;gpt-6-lunafor OpenAI). Check OpenAI's current standard-tier price for your model and set the*_USD_PER_MTOKvariables.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 toolscompare_supplier_quotesCompare supplier quotesARead-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 schemasBRead-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/CSVARead-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 QuantitiesBRead-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
Scored across 4 tools
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.
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.
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.
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
Related MCP Connectors
Construction & procurement PDFs (BoQs, quotes, invoices, spec sheets) to schema-strict JSON/CSV.
Extract custom JSON schemas and Excel/CSV tables from PDFs, invoices, statements, and receipts.
Turn any PDF into structured JSON via AI + OCR: invoices, bank statements, contracts.
Turn PDFs, scans and photos into a queryable database. Invoices, CVs, receipts, in bulk.
Related MCP Servers
- AlicenseNot gradedqualityFmaintenanceEnables 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
- AlicenseAqualityDmaintenanceConvert PDFs to structured JSON. Extract invoices, bank statements, contracts, and more. Pay per call via x402 USDC.58MIT
- AlicenseNot gradedqualityDmaintenanceConverts architectural PDF plans into dimension-verified millimetre geometry, IFC models, and CPU-rendered views, with built-in validation for boundaries, areas, and overlaps.MIT
- FlicenseNot gradedqualityDmaintenanceEnables reading entire PDF documents into validated structured JSON, including tables, key-values, and markdown, with read-only extraction tools and layout reconstruction.-