{
  "openapi": "3.1.0",
  "info": {
    "title": "Tax-Anything API",
    "version": "1.0.0",
    "summary": "Deterministic 5-domain tax calculation & Peppol UBL 2.1 validation engine with exact Decimal math and SHA-256 receipts.",
    "description": "Polymorphic deterministic tax calculation and e-invoice format validation across US Economic Nexus (50 states + DC), EU 27 VAT/OSS & Reverse Charge, Peppol BIS Billing 3.0 UBL 2.1 XML validation, HS Cross-Border Landed Cost, and Bilateral WHT/DST. Every request emits a tamper-evident SHA-256 TaxReceipt. HTTP 422 invalid inputs, malformed XML, and errors are strictly billed $0 (billed_micros = 0). Zero customer data or tax payload resale guarantee. Software disclaimer: deterministic tax calculation and e-invoice validation tooling only; not a licensed CPA firm or tax advice.",
    "contact": {
      "name": "Tax-Anything Operations",
      "email": "ops@fastmesh.dev",
      "url": "https://tax.fastmesh.dev"
    }
  },
  "servers": [
    {
      "url": "https://tax.fastmesh.dev",
      "description": "Public HTTPS Gateway Mount"
    },
    {
      "url": "http://127.0.0.1:9003",
      "description": "Local Runtime Server"
    }
  ],
  "tags": [
    { "name": "Health", "description": "Service liveness and readiness probes" },
    { "name": "Calculation", "description": "Single and batch deterministic 5-domain tax calculation & UBL validation" },
    { "name": "Receipts", "description": "Tamper-evident SHA-256 TaxReceipt lookup and validation" },
    { "name": "MCP", "description": "Native flat JSON-RPC 2.0 Model Context Protocol endpoint" },
    { "name": "Billing", "description": "Creem HMAC-SHA256 prepaid credit webhook settlement" }
  ],
  "paths": {
    "/health": {
      "get": {
        "operationId": "getHealth",
        "tags": ["Health"],
        "summary": "Check Tax-Anything service health",
        "responses": {
          "200": {
            "description": "Service is healthy and ready",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/HealthResponse" },
                "example": {
                  "status": "ok",
                  "service": "tax-anything",
                  "version": "1.0.0",
                  "public_host": "tax.fastmesh.dev",
                  "port": 9003,
                  "domains": [
                    "us_nexus",
                    "eu_vat_oss",
                    "ubl_peppol",
                    "hs_landed_cost",
                    "wht_dst"
                  ],
                  "ledger_enabled": true,
                  "mcp_enabled": true,
                  "timestamp_utc": "2026-12-02T12:00:00+00:00"
                }
              }
            }
          }
        }
      }
    },
    "/calculate": {
      "post": {
        "operationId": "calculateSingle",
        "tags": ["Calculation"],
        "summary": "Calculate tax or validate UBL 2.1 e-invoice across any of the 5 supported domains",
        "description": "Returns a deterministic, exact-Decimal, SHA-256 signed TaxReceipt. Strictly bills $0 (`billed_micros = 0`) on 422 invalid input, malformed XML, unsupported country, or error.",
        "parameters": [
          {
            "name": "X-Tenant-Id",
            "in": "header",
            "required": false,
            "schema": { "type": "string" },
            "description": "Optional tenant identifier for prepaid ledger accounting and 10% recheck pricing."
          },
          {
            "name": "X-API-Key",
            "in": "header",
            "required": false,
            "schema": { "type": "string" },
            "description": "Optional prepaid API key (omittable for zero-signup Try-Now sandbox)."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": { "$ref": "#/components/schemas/TaxCalculationRequest" },
              "examples": {
                "us_nexus_ny_breached": {
                  "summary": "Domain 1: US Economic Nexus (NY $500k AND 100 transactions)",
                  "value": {
                    "domain": "us_nexus",
                    "state": "NY",
                    "sales_amount": "525000.00",
                    "transaction_count": 115
                  }
                },
                "eu_vat_oss_reverse_charge": {
                  "summary": "Domain 2: EU B2B Reverse Charge with valid EU VAT ID checksum",
                  "value": {
                    "domain": "eu_vat_oss",
                    "seller_country": "DE",
                    "customer_country": "IE",
                    "customer_type": "B2B",
                    "customer_vat_id": "IE6388047V",
                    "net_amount": "1000.00",
                    "supply_type": "saas"
                  }
                },
                "ubl_peppol_valid": {
                  "summary": "Domain 3: Peppol BIS Billing 3.0 UBL 2.1 XML validation",
                  "value": {
                    "domain": "ubl_peppol",
                    "target": "INV-2026-001",
                    "xml": "<Invoice xmlns=\"urn:oasis:names:specification:ubl:schema:xsd:Invoice-2\" xmlns:cac=\"urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2\" xmlns:cbc=\"urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2\"><cbc:CustomizationID>urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0</cbc:CustomizationID><cbc:ProfileID>urn:fdc:peppol.eu:2017:poacc:billing:01:1.0</cbc:ProfileID><cbc:ID>INV-2026-001</cbc:ID><cbc:IssueDate>2026-12-01</cbc:IssueDate><cbc:DocumentCurrencyCode>EUR</cbc:DocumentCurrencyCode><cac:AccountingSupplierParty><cac:Party><cbc:EndpointID schemeID=\"0088\">7300010000001</cbc:EndpointID></cac:Party></cac:AccountingSupplierParty><cac:AccountingCustomerParty><cac:Party><cbc:EndpointID schemeID=\"0106\">12345678</cbc:EndpointID></cac:Party></cac:AccountingCustomerParty><cac:TaxTotal><cbc:TaxAmount currencyID=\"EUR\">21.00</cbc:TaxAmount><cac:TaxSubtotal><cbc:TaxableAmount currencyID=\"EUR\">100.00</cbc:TaxableAmount><cbc:TaxAmount currencyID=\"EUR\">21.00</cbc:TaxAmount><cac:TaxCategory><cbc:ID>S</cbc:ID><cbc:Percent>21.00</cbc:Percent><cac:TaxScheme><cbc:ID>VAT</cbc:ID></cac:TaxScheme></cac:TaxCategory></cac:TaxSubtotal></cac:TaxTotal><cac:LegalMonetaryTotal><cbc:LineExtensionAmount currencyID=\"EUR\">100.00</cbc:LineExtensionAmount><cbc:TaxExclusiveAmount currencyID=\"EUR\">100.00</cbc:TaxExclusiveAmount><cbc:TaxInclusiveAmount currencyID=\"EUR\">121.00</cbc:TaxInclusiveAmount><cbc:PayableAmount currencyID=\"EUR\">121.00</cbc:PayableAmount></cac:LegalMonetaryTotal><cac:InvoiceLine><cbc:ID>1</cbc:ID><cbc:InvoicedQuantity unitCode=\"EA\">2</cbc:InvoicedQuantity><cbc:LineExtensionAmount currencyID=\"EUR\">100.00</cbc:LineExtensionAmount><cac:Price><cbc:PriceAmount currencyID=\"EUR\">50.00</cbc:PriceAmount></cac:Price></cac:InvoiceLine></Invoice>"
                  }
                },
                "hs_landed_cost_cn_us": {
                  "summary": "Domain 4: HS Landed Cost (CN->US with Section 301 & De Minimis check)",
                  "value": {
                    "domain": "hs_landed_cost",
                    "hs_code": "847130",
                    "origin_country": "CN",
                    "destination_country": "US",
                    "incoterm": "FOB",
                    "goods_value": "2500.00",
                    "freight_cost": "180.00",
                    "insurance_cost": "20.00"
                  }
                },
                "wht_dst_us_ie": {
                  "summary": "Domain 5: Bilateral WHT Treaty (US->IE SaaS + W-8BEN-E) & DST Check",
                  "value": {
                    "domain": "wht_dst",
                    "payer_country": "US",
                    "payee_country": "IE",
                    "payment_type": "saas_subscription",
                    "gross_amount": "10000.00",
                    "treaty_claim_valid": true
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Deterministic calculation completed with signed TaxReceipt",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/TaxReceipt" }
              }
            }
          },
          "422": {
            "description": "Invalid input, malformed XML, DOCTYPE/XXE, negative monetary value, or unsupported jurisdiction — strictly $0 billed",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/ZeroBillErrorResponse" },
                "example": {
                  "ok": false,
                  "error": "invalid_input_422",
                  "detail": "Negative amount or unsupported country code.",
                  "billed_micros": 0,
                  "zero_bill_reason": "invalid_input_422"
                }
              }
            }
          }
        }
      }
    },
    "/calculate/batch": {
      "post": {
        "operationId": "calculateBatch",
        "tags": ["Calculation"],
        "summary": "Calculate a heterogeneous CSV or JSON tax batch with hard budget cap",
        "description": "Executes concurrent multi-domain calculations bounded by `max_budget_micros`. Any row that fails input validation (422) is strictly billed $0.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": { "$ref": "#/components/schemas/BatchCalculateRequest" },
              "example": {
                "tenant_id": "tenant_demo",
                "max_budget_micros": 250000,
                "items": [
                  { "domain": "us_nexus", "state": "CA", "revenue_usd": "520000.00", "transactions": 40 },
                  { "domain": "eu_vat_oss", "seller_country": "DE", "buyer_country": "FR", "amount": "100.00", "cross_border_annual_eur": "15000.00" },
                  { "domain": "wht_dst", "payer_country": "US", "payee_country": "IE", "income_type": "saas_subscription", "gross_amount": "5000.00", "has_w8bene": true }
                ]
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Batch execution summary and per-item TaxReceipts",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/BatchCalculateResponse" }
              }
            }
          },
          "422": {
            "description": "Invalid batch request — strictly $0 billed",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/ZeroBillErrorResponse" }
              }
            }
          }
        }
      }
    },
    "/receipt/{receipt_id}": {
      "get": {
        "operationId": "getReceipt",
        "tags": ["Receipts"],
        "summary": "Fetch a stored TaxReceipt and verify its SHA-256 attestation",
        "parameters": [
          {
            "name": "receipt_id",
            "in": "path",
            "required": true,
            "schema": { "type": "string" },
            "description": "Unique TaxReceipt ID"
          }
        ],
        "responses": {
          "200": {
            "description": "Receipt retrieved with cryptographic attestation check",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "ok": { "type": "boolean" },
                    "signature_valid": { "type": "boolean" },
                    "receipt": { "$ref": "#/components/schemas/TaxReceipt" }
                  }
                }
              }
            }
          },
          "404": {
            "description": "Receipt ID not found",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/ZeroBillErrorResponse" }
              }
            }
          }
        }
      }
    },
    "/mcp": {
      "post": {
        "operationId": "mcpJsonRpc",
        "tags": ["MCP"],
        "summary": "Native flat JSON-RPC 2.0 MCP endpoint",
        "description": "Supports initialize, notifications/initialized, ping, tools/list, and tools/call for tax_calculate, tax_calculate_batch, and tax_verify_receipt.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": { "$ref": "#/components/schemas/McpJsonRpcRequest" },
              "examples": {
                "initialize": {
                  "summary": "MCP Initialize Handshake",
                  "value": {
                    "jsonrpc": "2.0",
                    "id": 1,
                    "method": "initialize",
                    "params": {
                      "protocolVersion": "2025-03-26",
                      "clientInfo": { "name": "agent-client", "version": "1.0.0" }
                    }
                  }
                },
                "tools_list": {
                  "summary": "List Flat MCP Tools",
                  "value": {
                    "jsonrpc": "2.0",
                    "id": 2,
                    "method": "tools/list",
                    "params": {}
                  }
                },
                "tools_call_tax_calculate": {
                  "summary": "Invoke tax_calculate Tool",
                  "value": {
                    "jsonrpc": "2.0",
                    "id": 3,
                    "method": "tools/call",
                    "params": {
                      "name": "tax_calculate",
                      "arguments": {
                        "domain": "us_nexus",
                        "state": "CA",
                        "revenue_usd": "520000.00",
                        "transactions": 25
                      }
                    }
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "JSON-RPC 2.0 response payload",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/McpJsonRpcResponse" }
              }
            }
          },
          "202": {
            "description": "Accepted notification (notifications/initialized without id)"
          }
        }
      }
    },
    "/webhooks/creem": {
      "post": {
        "operationId": "creemWebhook",
        "tags": ["Billing"],
        "summary": "Creem HMAC-SHA256 payment webhook ingress",
        "description": "Verifies `creem-signature` HMAC-SHA256 using `CREEM_WEBHOOK_SECRET` from environment variables, deduplicates by `event_id`, and atomically credits the tenant wallet inside a SQLite WAL `BEGIN IMMEDIATE` transaction.",
        "parameters": [
          {
            "name": "creem-signature",
            "in": "header",
            "required": true,
            "schema": { "type": "string" },
            "description": "HMAC-SHA256 hex digest (or sha256=<hex>) computed over the raw HTTP request body."
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": { "$ref": "#/components/schemas/CreemWebhookPayload" },
              "example": {
                "id": "evt_creem_tax_01",
                "eventType": "checkout.completed",
                "object": {
                  "product_id": "prod_tax_anything_pro_29",
                  "amount": 2900,
                  "currency": "USD",
                  "customer": { "email": "buyer@example.com" },
                  "metadata": { "tenant_id": "tenant_acme", "sku_id": "sku_tax_pro_29" }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Event verified and atomically settled (or deduplicated idempotently)",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "ok": { "type": "boolean" },
                    "event_id": { "type": "string" },
                    "tenant_id": { "type": "string" },
                    "credits_granted_micros": { "type": "integer" },
                    "balance_micros": { "type": "integer" },
                    "replayed": { "type": "boolean" },
                    "status": { "type": "string" }
                  }
                }
              }
            }
          },
          "401": {
            "description": "Invalid or missing creem-signature HMAC-SHA256 digest"
          }
        }
      }
    }
  },
  "components": {
    "schemas": {
      "HealthResponse": {
        "type": "object",
        "required": ["status", "service"],
        "properties": {
          "status": { "type": "string", "enum": ["ok"] },
          "service": { "type": "string" },
          "version": { "type": "string" },
          "public_host": { "type": "string" },
          "port": { "type": "integer" },
          "domains": { "type": "array", "items": { "type": "string" } },
          "pricing": { "type": "object" },
          "cache_stats": { "type": "object" },
          "ledger_enabled": { "type": "boolean" },
          "mcp_enabled": { "type": "boolean" },
          "timestamp_utc": { "type": "string", "format": "date-time" }
        }
      },
      "TaxCalculationRequest": {
        "type": "object",
        "required": ["domain"],
        "properties": {
          "domain": {
            "type": "string",
            "enum": [
              "us_nexus",
              "eu_vat_oss",
              "ubl_peppol",
              "hs_landed_cost",
              "wht_dst"
            ]
          },
          "target": { "type": "string" },
          "recheck": { "type": "boolean", "default": false },
          "tenant_id": { "type": "string" },
          "payload": { "type": "object" },
          "options": { "type": "object" }
        }
      },
      "TaxReceipt": {
        "type": "object",
        "required": [
          "receipt_id",
          "domain",
          "verdict",
          "payload_sha256",
          "sha256_attestation",
          "billed_micros",
          "base_price_micros",
          "timestamp_utc"
        ],
        "properties": {
          "receipt_id": { "type": "string" },
          "domain": {
            "type": "string",
            "enum": [
              "us_nexus",
              "eu_vat_oss",
              "ubl_peppol",
              "hs_landed_cost",
              "wht_dst"
            ]
          },
          "target": { "type": "string" },
          "verdict": { "type": "string" },
          "status": { "type": "string" },
          "confidence": { "type": "number", "minimum": 0, "maximum": 1 },
          "checks": { "type": "array", "items": { "type": "object" } },
          "evidence_sources": { "type": "array", "items": { "type": "object" } },
          "calculation": { "type": "object" },
          "payload_sha256": { "type": "string" },
          "sha256_attestation": { "type": "string" },
          "billed_micros": { "type": "integer", "minimum": 0 },
          "base_price_micros": { "type": "integer", "minimum": 0 },
          "cache_hit": { "type": "boolean" },
          "cache_tier": { "type": "string", "enum": ["live", "shared_cache", "recheck_10pct"] },
          "timestamp_utc": { "type": "string", "format": "date-time" },
          "zero_bill_reason": { "type": "string" },
          "disclaimer": { "type": "string" }
        }
      },
      "BatchCalculateRequest": {
        "type": "object",
        "properties": {
          "items": {
            "type": "array",
            "items": { "$ref": "#/components/schemas/TaxCalculationRequest" }
          },
          "csv_text": { "type": "string" },
          "max_budget_micros": { "type": "integer", "minimum": 0 },
          "tenant_id": { "type": "string" },
          "recheck": { "type": "boolean", "default": false },
          "max_workers": { "type": "integer", "minimum": 1, "maximum": 16 }
        }
      },
      "BatchCalculateResponse": {
        "type": "object",
        "properties": {
          "batch_id": { "type": "string" },
          "tenant_id": { "type": "string" },
          "total_items": { "type": "integer" },
          "processed_items": { "type": "integer" },
          "stopped_by_budget": { "type": "boolean" },
          "skipped_by_budget_count": { "type": "integer" },
          "cache_hits": { "type": "integer" },
          "zero_billed_rows": { "type": "integer" },
          "max_budget_micros": { "type": ["integer", "null"] },
          "total_billed_micros": { "type": "integer" },
          "elapsed_ms": { "type": "integer" },
          "timestamp_utc": { "type": "string", "format": "date-time" },
          "batch_sha256": { "type": "string" },
          "results": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "row_index": { "type": "integer" },
                "skipped_by_budget": { "type": "boolean" },
                "receipt": { "$ref": "#/components/schemas/TaxReceipt" }
              }
            }
          }
        }
      },
      "ZeroBillErrorResponse": {
        "type": "object",
        "required": ["ok", "error", "billed_micros"],
        "properties": {
          "ok": { "type": "boolean" },
          "error": { "type": "string" },
          "detail": { "type": "string" },
          "billed_micros": { "type": "integer", "enum": [0] },
          "zero_bill_reason": { "type": "string" }
        }
      },
      "McpJsonRpcRequest": {
        "type": "object",
        "required": ["jsonrpc", "method"],
        "properties": {
          "jsonrpc": { "type": "string", "enum": ["2.0"] },
          "id": { "type": ["string", "integer", "null"] },
          "method": { "type": "string" },
          "params": { "type": "object" }
        }
      },
      "McpJsonRpcResponse": {
        "type": "object",
        "required": ["jsonrpc"],
        "properties": {
          "jsonrpc": { "type": "string", "enum": ["2.0"] },
          "id": { "type": ["string", "integer", "null"] },
          "result": { "type": "object" },
          "error": { "type": "object" }
        }
      },
      "CreemWebhookPayload": {
        "type": "object",
        "required": ["id", "eventType", "object"],
        "properties": {
          "id": { "type": "string" },
          "eventType": { "type": "string" },
          "object": { "type": "object" }
        }
      }
    }
  }
}
