{
  "openapi": "3.1.0",
  "info": {
    "title": "Contrie API",
    "version": "1.0.0",
    "description": "Web data infrastructure for AI agents. POST a URL plus a natural-language description or a JSON Schema; get back validated JSON with a quality score, a grounding ratio, the full escalation trace, and the model cost of the call. Free during beta.",
    "contact": { "email": "hello@contrie.com" }
  },
  "servers": [{ "url": "https://contrie.com" }],
  "security": [{ "bearerAuth": [] }],
  "paths": {
    "/api/v1/scrape": {
      "post": {
        "operationId": "scrape",
        "summary": "Fetch a URL and extract structured data or markdown",
        "description": "Fetches the given URL and runs it through the extraction pipeline (heuristic -> classify -> route -> extract -> validate -> escalate). Send header 'Accept: application/x-ndjson' to receive newline-delimited trace events instead of a single JSON response.",
        "security": [{ "bearerAuth": [] }],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": { "$ref": "#/components/schemas/ScrapeRequest" }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Extraction result",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/ExtractionResponse" }
              },
              "application/x-ndjson": {
                "schema": {
                  "type": "string",
                  "description": "Newline-delimited JSON. Each line is { event: 'trace', ...TraceEntry } or a final { event: 'result', success, data, markdown?, metadata }."
                }
              }
            }
          },
          "400": { "description": "Invalid request", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } } },
          "401": { "description": "Unauthorized", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } } },
          "422": { "description": "Fetch failed or render required", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } } },
          "429": { "description": "Rate limited or monthly credit quota reached", "headers": { "Retry-After": { "schema": { "type": "integer" }, "description": "Seconds until the caller may retry" } }, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } } },
          "500": { "description": "Extraction failed", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } } },
          "503": { "description": "Service unavailable", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } } }
        }
      }
    },
    "/api/v1/extract": {
      "post": {
        "operationId": "extract",
        "summary": "Extract structured data or markdown from raw HTML",
        "description": "Identical pipeline to /api/v1/scrape but performs no fetch: the caller supplies the page HTML directly.",
        "security": [{ "bearerAuth": [] }],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": { "$ref": "#/components/schemas/ExtractRequest" }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Extraction result",
            "content": {
              "application/json": {
                "schema": { "$ref": "#/components/schemas/ExtractionResponse" }
              },
              "application/x-ndjson": {
                "schema": {
                  "type": "string",
                  "description": "Newline-delimited JSON trace events followed by a final result line."
                }
              }
            }
          },
          "400": { "description": "Invalid request", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } } },
          "401": { "description": "Unauthorized", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } } },
          "429": { "description": "Rate limited or monthly credit quota reached", "headers": { "Retry-After": { "schema": { "type": "integer" }, "description": "Seconds until the caller may retry" } }, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } } },
          "500": { "description": "Extraction failed", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } } },
          "503": { "description": "Service unavailable", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } } }
        }
      }
    },
    "/api/health": {
      "get": {
        "operationId": "health",
        "summary": "Service health check",
        "security": [],
        "responses": {
          "200": {
            "description": "Service is healthy",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": { "status": { "type": "string", "enum": ["ok"] } },
                  "required": ["status"]
                }
              }
            }
          }
        }
      }
    },
    "/mcp": {
      "post": {
        "operationId": "mcp",
        "summary": "MCP Streamable HTTP endpoint",
        "description": "Hosted Model Context Protocol server over the Streamable HTTP transport. Exposes tools contrie_extract { url, extract?, schema? } and contrie_read { url } (markdown). Send 'Authorization: Bearer <key>'; without a key only the sample URLs succeed. Not a plain REST endpoint — connect with an MCP client rather than calling it directly.",
        "security": [{ "bearerAuth": [] }],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": { "type": "object", "description": "JSON-RPC 2.0 message per the MCP Streamable HTTP transport spec." }
            }
          }
        },
        "responses": {
          "200": { "description": "MCP JSON-RPC response or event stream" }
        }
      }
    }
  },
  "components": {
    "securitySchemes": {
      "bearerAuth": {
        "type": "http",
        "scheme": "bearer",
        "bearerFormat": "ck_live_...",
        "description": "API key created at https://contrie.com/dashboard/keys. Configure via environment variable, never pasted into a URL or agent chat."
      }
    },
    "schemas": {
      "ScrapeRequest": {
        "type": "object",
        "required": ["url"],
        "properties": {
          "url": { "type": "string", "format": "uri", "description": "Target page. Must be http or https." },
          "extract": { "type": "string", "description": "Natural-language description of the data to extract." },
          "schema": { "$ref": "#/components/schemas/JsonSchemaSubset" },
          "format": { "type": "string", "enum": ["json", "markdown", "both"], "default": "json" },
          "options": {
            "type": "object",
            "properties": {
              "timeout": { "type": "integer", "minimum": 1000, "maximum": 30000, "description": "Fetch timeout in milliseconds." }
            }
          }
        }
      },
      "ExtractRequest": {
        "type": "object",
        "required": ["html", "url"],
        "properties": {
          "html": { "type": "string", "maxLength": 5000000, "description": "Raw page HTML, up to 5 MB." },
          "url": { "type": "string", "format": "uri", "description": "Used for context and resolving relative links; no fetch is performed." },
          "extract": { "type": "string", "description": "Natural-language description of the data to extract." },
          "schema": { "$ref": "#/components/schemas/JsonSchemaSubset" },
          "format": { "type": "string", "enum": ["json", "markdown", "both"], "default": "json" }
        }
      },
      "JsonSchemaSubset": {
        "type": "object",
        "description": "JSON Schema subset. Supported types: object, array, string, number, integer, boolean. Supported keywords: properties, required, items, enum, description.",
        "properties": {
          "type": { "type": "string", "enum": ["object", "array", "string", "number", "integer", "boolean"] },
          "properties": { "type": "object" },
          "required": { "type": "array", "items": { "type": "string" } },
          "items": { "type": "object" },
          "enum": { "type": "array" },
          "description": { "type": "string" }
        }
      },
      "ExtractionResponse": {
        "type": "object",
        "required": ["success", "metadata"],
        "properties": {
          "success": { "type": "boolean" },
          "data": { "description": "Extracted result matching the requested schema, or null.", "nullable": true },
          "markdown": { "type": "string", "description": "Present when format is 'markdown' or 'both'." },
          "metadata": {
            "type": "object",
            "required": ["url", "extractionMethod", "qualityScore", "escalations", "latencyMs", "costUsd", "trace", "pagesUsed"],
            "properties": {
              "url": { "type": "string", "format": "uri" },
              "extractionMethod": { "type": "string", "enum": ["heuristic", "ai", "hybrid", "markdown"] },
              "model": { "type": "string", "description": "Model that produced the final result, if any." },
              "qualityScore": { "type": "integer", "minimum": 0, "maximum": 100 },
              "grounding": { "type": "number", "minimum": 0, "maximum": 1, "description": "Fraction of extracted values verified verbatim against the page text." },
              "escalations": { "type": "integer", "minimum": 0, "maximum": 2 },
              "latencyMs": { "type": "integer" },
              "costUsd": { "type": "number" },
              "tokensUsed": {
                "type": "object",
                "properties": {
                  "input": { "type": "integer" },
                  "output": { "type": "integer" }
                }
              },
              "trace": { "type": "array", "items": { "$ref": "#/components/schemas/TraceEntry" } },
              "credits": { "type": "integer", "description": "Credits charged for this call: 0 unless it delivered an answer; 1 markdown/heuristic/free/budget, 3 standard/vision/premium, 10 frontier" }
            }
          }
        }
      },
      "TraceEntry": {
        "type": "object",
        "required": ["stage", "detail"],
        "properties": {
          "stage": { "type": "string", "enum": ["heuristic", "classify", "route", "extract", "validate", "escalate", "markdown"] },
          "detail": { "type": "string" },
          "model": { "type": "string" },
          "tier": { "type": "string" },
          "quality": { "type": "integer" },
          "ms": { "type": "integer" }
        }
      },
      "ErrorResponse": {
        "type": "object",
        "required": ["success", "error"],
        "properties": {
          "success": { "type": "boolean", "enum": [false] },
          "error": {
            "type": "object",
            "required": ["code", "message"],
            "properties": {
              "code": {
                "type": "string",
                "enum": [
                  "INVALID_REQUEST",
                  "INVALID_URL",
                  "UNAUTHORIZED",
                  "FETCH_FAILED",
                  "RENDER_REQUIRED",
                  "RATE_LIMITED",
                  "PAGE_LIMIT_REACHED",
                  "SERVICE_UNAVAILABLE",
                  "EXTRACTION_FAILED"
                ]
              },
              "message": { "type": "string" }
            }
          }
        }
      }
    }
  }
}
