openapi: 3.0.0
info:
  title: Lots of CSVs API
  description: |
    A minimalist data warehouse for storing and retrieving CSV files via HTTP.

    **Attachments.** A row can carry files and images. A dataset column can be declared an `attachment` column (with
    the multipart append below, with MCP `create_dataset` `column_types`, or later with
    `PATCH /api/datasets/{id}/columns/{name}`). Each cell of such a column holds zero or more attachment URIs,
    separated by a single space:

    ```text
    attachment:///<userName>/<attachmentId>     e.g. attachment:///britt/att_01JC8X3V5ZQ8M2T9K4R7B6N1PD
    ```

    The id is `att_` plus a 26-character ULID. The URI is a stable reference, not a link: it never expires and grants
    nothing by itself, so it is safe to keep in a CSV or hand to someone else. The file is read with
    `GET /api/attachments/{attachmentId}`, which checks that the caller owns it. The bytes are kept in a private
    Cloudflare R2 bucket and are only ever served through that route; there are no public or presigned URLs.

    Files are uploaded either with the rows (a `multipart/form-data` append whose cells say `upload:<part>`) or first,
    with `POST /api/datasets/{id}/attachments`, and referenced later. A file belongs to at most one row of the dataset
    it was uploaded to. Writes to an `attachment` column are checked: every URI must name an uploaded file of this
    account and this dataset that no other row uses. Updating a row so it no longer references a file, deleting the
    row, or deleting the dataset deletes the file. An upload no row references is deleted after 24 hours.

    | Limit | Default |
    | --- | --- |
    | Size per file | 25 MB (`413`) |
    | Size per request | 100 MB (`413`) |
    | Files per row | 10 (`413`) |
    | Inline base64 per MCP call | 5 MB |
    | Unreferenced upload kept for | 24 hours |

    Allowed types, decided from the file's bytes rather than its name or declared type (`415` otherwise, or when the
    declared type disagrees): `image/png`, `image/jpeg`, `image/gif`, `image/webp`, `image/avif`, `image/heic`,
    `application/pdf`, `text/plain`, `text/csv` and `application/json`. SVG and HTML are always rejected.
  version: 1.0.0
servers:
  - url: https://www.lotsofcsvs.com
    description: Main server
paths:
  /u/{username}/{dataset}:
    parameters:
      - name: username
        in: path
        required: true
        description: The registered username of the user.
        schema:
          type: string
      - name: dataset
        in: path
        required: true
        description: The path to the dataset, treated as a unique identifier.
        schema:
          type: string    
    get:
      summary: Fetch a dataset
      description: |
        Retrieve a dataset. The format comes from the suffix on the last path segment, which is stripped
        before the dataset is looked up:

        - no suffix or `.csv` — an RFC 4180 formatted CSV, also selected by `?plaintext=true` for `text/plain`
        - `.json` — an array of objects, also selected by `?json=true` or `Accept: application/json`
        - `.sqlite` — a SQLite database holding one table named after the dataset (the full path, so quote it in
          SQL). Its first column is `timestamp`, the row's append time in epoch milliseconds, followed by the
          dataset's columns in header order. Column types are a best-effort `INTEGER` / `REAL` / `TEXT` inferred
          from the stored values; empty cells are `NULL`. Inference never rewrites a value to fit a type: a
          column holding zero-padded numbers such as `01234`, or whole numbers too large to represent exactly
          (beyond 2^53, like a 19-digit id), is `TEXT`, so the digits come back exactly as they were stored.
          An `attachment` column is always `TEXT` and holds the URIs. The file also holds an `_attachments` table
          (`uri, file_name, content_type, size, sha256, row_timestamp`) listing every attached file of the rows it
          contains, so a cell can be joined to its file's metadata offline on `uri`; the table is empty for a dataset
          without attachments, and is named `_attachments_2` if the dataset itself is called `_attachments`. File
          bytes are never embedded.

        **Attachment cells** come back exactly as stored in every format: the space-separated `attachment:///` URIs
        (see the API description). Read a file with `GET /api/attachments/{attachmentId}`.

        **Row ids.** Every row has an integer id, unique within the account and increasing as rows are appended
        (`POST` returns the ids it wrote as `row_ids`). JSON reads always include it as a `row_id` key, right after
        `timestamp`. CSV reads include it as a `row_id` column, second after `timestamp`, only with
        `?include=row_id`, so a CSV download without that parameter is byte-for-byte what it has always been. The
        `.sqlite` file does not include it.

        **Reading only new rows.** `?after_row_id=N` returns only the rows whose id is greater than `N`, ordered by
        id, in every format: pass the last `row_id` you have seen to fetch everything appended since. When `N` is
        at or past the last row the result has no rows (the CSV header line only, or an empty table).
      operationId: fetchDataset
      parameters:
        - $ref: '#/components/parameters/username'
        - $ref: '#/components/parameters/dataset'
        - name: include
          in: query
          required: false
          description: |
            Extra columns for a CSV read, as a comma-separated list. `row_id` adds each row's id as the second
            column, after `timestamp`. Unknown names are ignored. JSON reads always include `row_id`, so it changes
            nothing there.
          schema:
            type: string
          example: row_id
        - name: after_row_id
          in: query
          required: false
          description: |
            Only return rows whose id is greater than this, ordered by id. Must be an integer (digits, optionally
            preceded by `-`); anything else, such as `abc` or `1.5`, is rejected with `400`.
          schema:
            type: integer
          example: 1042
      responses:
        '200':
          description: Successful response with the dataset in the requested format
          content:
            text/csv:
              schema:
                type: string
                format: binary
            application/json:
              schema:
                type: array
                items:
                  type: object
                  description: |
                    One object per row: `timestamp` (epoch milliseconds), then `row_id`, then the dataset's columns
                    by name. Values that look numeric are returned as numbers.
                  properties:
                    timestamp:
                      type: integer
                    row_id:
                      type: integer
                      description: The row's id; pass it as `after_row_id` to read only later rows.
                  additionalProperties: true
              example:
                - { timestamp: 1700000001000, row_id: 1041, name: Bob, age: 35, city: Chicago }
                - { timestamp: 1700000001000, row_id: 1042, name: Charlie, age: 40, city: Boston }
            application/vnd.sqlite3:
              schema:
                type: string
                format: binary
        '400':
          description: '`after_row_id` is not an integer.'
          content:
            text/plain:
              schema:
                type: string
              example: 'Invalid after_row_id: must be an integer'
        '404':
          description: |
            No such dataset. Only the `.sqlite` format reports this; the CSV and JSON formats return an empty
            `200` for a dataset that does not exist.
      security:
        - bearerAuth: []
    post:
      summary: Create or append to a dataset
      description: |
        Add rows to a dataset. If the dataset does not exist, it is created from the column names the body carries,
        so a first write must name its columns: send JSON objects, or send CSV or JSON arrays with `header=present`
        on the `Content-Type`.

        Every write follows the same rules as the other entry points:

        - Cells are stored exactly as sent. Nothing is coerced, so `07030` stays `07030`.
        - Rows are laid out in the dataset's column order. Bodies that name their columns (JSON objects, CSV or JSON
          arrays with `header=present`) are matched by name: a missing column is an empty cell and an unknown column
          is ignored. Bodies that do not (headerless CSV, JSON arrays without `header=present`) are positional and
          must have exactly the dataset's column count.
        - Blank and comma-only rows are dropped silently.
        - A row that cannot be stored, or an invalid column name on a new dataset, rejects the whole request with
          `400` and stores nothing (see the `400` response).
        - Cells of `attachment` columns must hold only `attachment:///` URIs of uploaded files of this account and
          this dataset that no other row uses (or `upload:<part>` placeholders, in a multipart body). Anything else
          rejects the whole request: `400` for a malformed value, `409` for a file that is unknown, another account's,
          another dataset's, already used by a row or referenced twice, and `413` for a row with more than 10 files.
          Columns that are not `attachment` columns are not checked: a URI there is just text.

        **Rows and files in one request.** With `Content-Type: multipart/form-data` the body holds a `rows` part
        carrying the rows in either form above (its own `Content-Type` decides: `text/csv`, optionally with
        `header=present`, or `application/json`; a plain field is JSON when it starts with `[`, CSV otherwise;
        `header=present` on the request's own `Content-Type` also counts) plus one file part per file. A cell says
        `upload:<part name>` to reference a file of the same request, and is stored as that file's new
        `attachment:///` URI. Every file is checked first (size, request size, sniffed type, as on
        `POST /api/datasets/{id}/attachments`), then every row, so a rejected request stores nothing. When the
        dataset does not exist yet (`header=present`), it is created and every column holding an `upload:`
        placeholder becomes an `attachment` column.

        Unlike `GET`, no format suffix is stripped: `POST` and `DELETE` address the dataset the path literally
        names, so posting to `.../cool_data.csv` writes a dataset called `cool_data.csv`. This keeps a write from
        ever landing on a dataset other than the one in the URL, and makes a dataset whose name really does end in
        `.csv`, `.json` or `.sqlite` reachable.
      operationId: createOrAppendDataset
      parameters:
        - $ref: '#/components/parameters/username'
        - $ref: '#/components/parameters/dataset'
      requestBody:
        required: true
        description: |
          The `Content-Type` selects the shape. The media-type parameter `header=present` (for example
          `text/csv; header=present` or `application/json; header=present`) says that the first record names the
          columns; it is what creates a dataset from a CSV or JSON-array body, and on an existing dataset it lets
          the rows be matched by name. JSON objects always name their columns, so the parameter is not needed.
        content:
          text/csv:
            schema:
              type: string
              description: |
                RFC 4180 CSV. With `header=present` the first line names the columns; without it every line is a
                data row in the dataset's column order.
            examples:
              withHeader:
                summary: 'CSV with a header line (`Content-Type: text/csv; header=present`)'
                value: |
                  name,age,city
                  Bob,35,Chicago
                  Charlie,40,Boston
              headerless:
                summary: 'Data rows only, for an existing dataset (`Content-Type: text/csv`)'
                value: |
                  Dana,29,Denver
          application/json:
            schema:
              type: array
              minItems: 1
              description: |
                A non-empty array of rows. Each row is an object keyed by column name, or an array of cells in the
                dataset's column order (with `header=present`, the first array names the columns instead).
              items:
                oneOf:
                  - type: object
                    additionalProperties: true
                  - type: array
                    items: {}
            examples:
              objects:
                summary: Objects, matched to columns by key
                value:
                  - { name: Bob, age: '35', city: Chicago }
                  - { name: Charlie, age: '40', city: Boston }
              arraysWithHeader:
                summary: 'Arrays whose first row names the columns (`Content-Type: application/json; header=present`)'
                value:
                  - [name, age, city]
                  - [Bob, '35', Chicago]
              arrays:
                summary: 'Arrays in column order, for an existing dataset (`Content-Type: application/json`)'
                value:
                  - [Dana, '29', Denver]
              attachmentUri:
                summary: 'A file uploaded earlier with `POST /api/datasets/{id}/attachments`, referenced by its URI'
                value:
                  - { date: '2026-11-03', amount: '12.50', receipt: 'attachment:///britt/att_01JC8X3V5ZQ8M2T9K4R7B6N1PD' }
          multipart/form-data:
            schema:
              type: object
              required: [rows]
              properties:
                rows:
                  type: string
                  description: |
                    The rows, as CSV or as a JSON array, in which `attachment` cells may say `upload:<part name>`.
                    Give the part its own `Content-Type` (`application/json`, or `text/csv; header=present` to name
                    the columns), or send it as a plain field.
                  example: '[{"date":"2026-11-03","amount":"12.50","receipt":"upload:r1"}]'
              additionalProperties:
                type: string
                format: binary
                description: A file part, referenced from the rows as `upload:<part name>`. Part names must be unique.
            encoding:
              rows:
                contentType: application/json, text/csv
      responses:
        '200':
          description: The rows were stored. The dataset was created first if it did not exist.
          content:
            application/json:
              schema:
                type: object
                required: [rows_inserted, row_ids]
                properties:
                  rows_inserted:
                    type: integer
                    description: How many rows were stored, after blank and comma-only rows were dropped.
                  row_ids:
                    type: array
                    items:
                      type: integer
                    description: |
                      The ids of the stored rows, in the order they were sent (blank rows have none). They are the
                      `row_id` values reads return, and the last one is what to pass as `after_row_id` later.
                  attachments:
                    type: array
                    description: Multipart bodies only. The files stored by this request, in part order.
                    items:
                      $ref: '#/components/schemas/StoredUpload'
              examples:
                rows:
                  summary: A CSV or JSON append
                  value:
                    rows_inserted: 2
                    row_ids: [1041, 1042]
                multipart:
                  summary: A multipart append with one file
                  value:
                    rows_inserted: 1
                    row_ids: [1043]
                    attachments:
                      - part: r1
                        uri: attachment:///britt/att_01JC8X3V5ZQ8M2T9K4R7B6N1PD
                        size: 48213
                        content_type: image/jpeg
        '400':
          description: |
            The write was rejected and nothing was stored, not even a new dataset. Some rejections are plain text:
            an unsupported `Content-Type`, an empty or non-array JSON body (`Invalid JSON`), a body with no data rows
            left after blank rows are dropped (`No data to insert`), or a positional body for a dataset that does
            not exist yet (it has nothing to name the columns with). Two cases answer with a JSON body listing every
            problem:

            - **A row that cannot be stored**, such as one with an unmatched double quote (`"lunch,12.50`) or, for a
              positional body, a row with the wrong number of cells. `rows` lists every bad row by its 0-based
              position among the data rows (after the header line, when there is one) with a reason. Blank and
              comma-only rows are not errors; they are dropped silently.
            - **Invalid column names on a new dataset.** Names are trimmed, then an empty name, a name used twice, or
              the reserved name `timestamp` (every read adds it as the first column) is rejected; so is a header
              line that cannot be read, such as one with an unmatched double quote. `headers` lists every bad name by
              its 0-based position with a reason, and `rows` is empty. Existing datasets are never re-checked.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/WriteRejected'
              examples:
                unmatchedQuote:
                  summary: A row with an unmatched double quote
                  value:
                    error: '1 invalid row: row 0: unmatched double quote'
                    rows:
                      - index: 0
                        reason: unmatched double quote
                duplicateHeader:
                  summary: A new dataset with a duplicated column name
                  value:
                    error: 'invalid headers: column 2 ("a"): duplicate name'
                    rows: []
                    headers:
                      - index: 1
                        name: a
                        reason: duplicate name
                malformedAttachment:
                  summary: An `attachment` cell holding something that is not an attachment URI
                  value:
                    error: '1 invalid attachment reference: row 0, column "receipt": not an attachment:/// URI'
                    rows: []
                    attachments:
                      - index: 0
                        column: receipt
                        value: https://example.com/receipt.jpg
                        reason: not an attachment:/// URI
                        status: 400
                multipart:
                  summary: 'A multipart body without exactly one `rows` part (also: invalid multipart, an empty file, two file parts with the same name)'
                  value:
                    error: A multipart body needs exactly one "rows" part
        '409':
          description: |
            Nothing was stored. An `attachment` cell references a file that is unknown, another account's, another
            dataset's, already used by another row, or referenced twice. `attachments` lists every problem.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/WriteRejected'
              example:
                error: '1 invalid attachment reference: row 0, column "receipt": attachment is already attached to row 1041'
                rows: []
                attachments:
                  - index: 0
                    column: receipt
                    value: attachment:///britt/att_01JC8X3V5ZQ8M2T9K4R7B6N1PD
                    reason: attachment is already attached to row 1041
                    status: 409
        '413':
          description: |
            Nothing was stored. A row references more than `MAX_ATTACHMENTS_PER_ROW` files (10; `attachments` lists
            it), or, for a multipart body, a file is over `MAX_ATTACHMENT_BYTES` (25 MB) or the request is over
            `MAX_ATTACHMENT_REQUEST_BYTES` (100 MB).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '415':
          description: |
            Multipart bodies only; nothing was stored. A file's type, sniffed from its bytes, is not on the allowlist
            or does not match the type the part declared. SVG and HTML are always rejected.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
      security:
        - bearerAuth: []
    delete:
      summary: Delete a dataset
      description: |
        Deletes the dataset the path literally names (no format suffix is stripped, as on `POST`): its rows, its
        columns, its description jobs and its definition, in one step. Every attachment of the dataset reads `404`
        as soon as the response is sent, and its bytes are removed from storage right after; anything the request
        does not finish is removed by a sweep that runs every ten minutes.

        Same authorisation as `GET`: the session or a bearer token must belong to `username`.
      operationId: deleteDataset
      parameters:
        - $ref: '#/components/parameters/username'
        - $ref: '#/components/parameters/dataset'
      responses:
        '200':
          description: The dataset was deleted.
          content:
            text/plain:
              schema:
                type: string
              example: Deleted
        '404':
          description: No such dataset.
          content:
            text/plain:
              schema:
                type: string
              example: Not found
      security:
        - bearerAuth: []
  /api/uploads/text:
    post:
      summary: Upload plain text as a single-column dataset
      description: |
        Accepts a raw text body and stores it as rows in a dataset with a single
        column named `text`. If `dataset_id` is provided or `dataset_name` matches
        an existing single-column text dataset for the caller, the rows are
        appended; otherwise a new dataset is created. The dataset name is
        auto-generated when neither parameter is provided.
      operationId: uploadPlainText
      parameters:
        - name: dataset_id
          in: query
          required: false
          description: Existing dataset id to append to. Must belong to the caller.
          schema:
            type: string
        - name: dataset_name
          in: query
          required: false
          description: Name for a new dataset, or the name of an existing single-column text dataset to append to.
          schema:
            type: string
        - name: row_split
          in: query
          required: false
          description: How to split the payload into rows. `whole` (default) treats the entire payload as one row; `line` splits on newlines and skips blank lines.
          schema:
            type: string
            enum: [whole, line]
            default: whole
      requestBody:
        required: true
        content:
          text/plain:
            schema:
              type: string
              format: binary
      responses:
        '200':
          description: Upload accepted; an import job has been queued.
          content:
            application/json:
              schema:
                type: object
                required: [import_job_id, dataset_id, r2_object_url]
                properties:
                  import_job_id:
                    type: string
                  dataset_id:
                    type: string
                    description: The id of the target (or newly created) dataset.
                  r2_object_url:
                    type: string
                    format: uri
        '400':
          description: Invalid Content-Type or query parameters.
        '401':
          description: Authentication required.
        '403':
          description: The caller does not own the referenced dataset.
        '404':
          description: The referenced `dataset_id` does not exist.
        '409':
          description: The target dataset's schema is not a single text column.
        '413':
          description: Payload exceeds the size limit (100 MB).
      security:
        - bearerAuth: []
  /api/u/{userName}/datasets:
    get:
      summary: List the caller's dataset names
      description: |
        Returns the names of all datasets owned by `userName`. The caller must
        be `userName` (authenticated via session cookie or bearer token). Pass
        `text_only=1` to restrict the result to single-column text datasets
        (i.e. valid append targets for `/api/uploads/text`).
      operationId: listUserDatasets
      parameters:
        - name: userName
          in: path
          required: true
          description: The registered username of the caller.
          schema:
            type: string
        - name: text_only
          in: query
          required: false
          description: When `1`, restrict the result to single-column text datasets.
          schema:
            type: string
            enum: ['1']
      responses:
        '200':
          description: A JSON list of dataset names.
          content:
            application/json:
              schema:
                type: object
                required: [datasets]
                properties:
                  datasets:
                    type: array
                    items:
                      type: string
        '401':
          description: Authentication required or `userName` does not match the caller.
      security:
        - bearerAuth: []
  /api/u/{userName}.{format}:
    get:
      summary: Download a whole-account export
      description: |
        Returns everything the account holds as a single file. The export is built asynchronously by the
        `lotsofcsvs-file-export` worker and cached in R2, so the first call for an account — and the first call
        after any dataset changed — answers `202` and queues the job. Poll the URL in `Location` after
        `Retry-After` seconds until it answers `200`; polling while a job is running does not queue a second one.

        The format is the suffix on the path:

        - `.sqlite` — one SQLite database with a table per dataset, plus an `_attachments` table
          (`dataset, uri, file_name, content_type, size, sha256, row_timestamp`) listing every attached file; join it
          to a dataset's table on `uri`. `attachment` columns are `TEXT` and hold the URIs; file bytes are not
          embedded. If a dataset is itself named `_attachments`, the listing is `_attachments_2`.
        - `.zip` — an archive of one CSV per dataset at `csvs/<userName>/<dataset>.csv`, every attached file at
          `attachments/<dataset>/<attachmentId>-<fileName>`, and an `attachments.csv` manifest
          (`dataset,uri,path,file_name,content_type,size,sha256`) that maps each URI in the CSVs to its file in the
          archive. An account without attachments gets a header-only manifest. Only files bound to a row are
          included.
        - `.tar.gz` — the same archive, gzipped

        Changing a row (append, update or delete), a dataset, or an attachment makes the export stale, so the next
        request rebuilds it.

        The caller must be `userName`, authenticated with a session cookie or a bearer token. The file is
        streamed through this endpoint from a private bucket; there is no redirect to an R2 URL. Authorisation
        failures redirect (`302`) to sign-in or to `/`, the same as the other `/api/u` routes, rather than
        returning `401` or `403`.
      operationId: exportAccount
      parameters:
        - name: userName
          in: path
          required: true
          description: The registered username of the caller.
          schema:
            type: string
        - name: format
          in: path
          required: true
          description: The export format, taken from the suffix on the path.
          schema:
            type: string
            enum: [sqlite, zip, tar.gz]
      responses:
        '200':
          description: |
            The export, streamed from R2 as an attachment named `<userName>.<format>`.
          headers:
            Content-Disposition:
              description: 'Always `attachment; filename="<userName>.<format>"`.'
              schema:
                type: string
            ETag:
              description: The entity tag of the stored R2 object.
              schema:
                type: string
          content:
            application/vnd.sqlite3:
              schema:
                type: string
                format: binary
            application/zip:
              schema:
                type: string
                format: binary
            application/gzip:
              schema:
                type: string
                format: binary
        '202':
          description: |
            The export is being prepared. A job was queued unless one was already running.
          headers:
            Location:
              description: The URL to poll — the requested URL.
              schema:
                type: string
            Retry-After:
              description: Seconds to wait before polling again.
              schema:
                type: integer
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PendingExport'
        '302':
          description: |
            Neither the session nor a bearer token authorises the caller: a redirect to sign-in when there is no
            session, or to `/` when the signed-in user is somebody other than `userName`.
        '400':
          description: The path does not end in `.sqlite`, `.zip` or `.tar.gz`.
        '404':
          description: |
            No such account; the account holds no datasets to export; or the export job deliberately skipped this
            format and recorded why — the worker does that for `.sqlite` when the account holds more rows than its
            `MAX_SQLITE_ROWS` limit, or when the database cannot be built. The body is that reason as plain text.
            It is a `404` rather than a `202` because re-running the job would reach the same verdict, so there is
            nothing to poll for; the other formats keep returning `200`.
      security:
        - bearerAuth: []
  /api/datasets/{id}/description:
    parameters:
      - $ref: '#/components/parameters/datasetId'
    get:
      summary: Read a dataset's description
      description: |
        Returns the dataset's description, where it came from, when it was last written, and the most
        recent description job (automatic or on-demand) if there has ever been one. This is the endpoint
        the dataset page polls while a generation job runs.

        The caller is resolved from the session cookie or a bearer API token. Datasets that do not exist
        and datasets belonging to another user are both reported as `404`.
      operationId: getDatasetDescription
      responses:
        '200':
          description: The dataset's description and the state of its most recent job.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DatasetDescription'
        '401':
          description: Authentication required.
        '404':
          description: No such dataset, or it belongs to another user.
      security:
        - bearerAuth: []
    patch:
      summary: Set or clear a dataset's description
      description: |
        Stores a human-written description. The value is trimmed before it is measured and saved, and the
        description's source becomes `user`, which stops the automatic sweep from ever replacing it.

        Sending `null` clears the description, its source and its timestamp together, making the dataset
        eligible for automatic description again.
      operationId: updateDatasetDescription
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [description]
              properties:
                description:
                  type: string
                  nullable: true
                  maxLength: 1000
                  description: The new description, or `null` to clear it. Trimmed before the length limit is applied.
            examples:
              set:
                summary: Set a description
                value:
                  description: Daily sales totals by store, one row per day.
              clear:
                summary: Clear the description
                value:
                  description: null
      responses:
        '200':
          description: The stored description, in the same shape as `GET`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DatasetDescription'
        '400':
          description: The body is not JSON, has no `description`, or `description` is neither a string nor `null` or is longer than 1000 characters after trimming.
        '401':
          description: Authentication required.
        '404':
          description: No such dataset, or it belongs to another user.
      security:
        - bearerAuth: []
  /api/datasets/{id}/description/generate:
    parameters:
      - $ref: '#/components/parameters/datasetId'
    post:
      summary: Generate a description for a dataset
      description: |
        Queues an on-demand description job and returns immediately. Poll
        `GET /api/datasets/{id}/description` for the result: `latest_job.status` moves from `pending`
        through `processing` to `completed` or `failed`.

        One job may be in flight per dataset, and the number of on-demand jobs per dataset per rolling
        24 hours is capped by the `MANUAL_DAILY_LIMIT` setting (10 by default). The request body is
        ignored.
      operationId: generateDatasetDescription
      responses:
        '202':
          description: A job has been created and queued.
          content:
            application/json:
              schema:
                type: object
                required: [job_id, status]
                properties:
                  job_id:
                    type: string
                    format: uuid
                  status:
                    type: string
                    enum: [pending]
        '401':
          description: Authentication required.
        '404':
          description: No such dataset, or it belongs to another user.
        '409':
          description: A description job for this dataset is already `pending` or `processing`.
        '422':
          description: The dataset has no rows, so there is nothing to describe.
        '429':
          description: The dataset has reached its limit of on-demand descriptions for the last 24 hours.
      security:
        - bearerAuth: []
  /api/datasets/{id}/rows/{rowId}:
    parameters:
      - $ref: '#/components/parameters/datasetId'
      - name: rowId
        in: path
        required: true
        description: The row's id, as returned in `row_ids` by an append and in `row_id` by reads.
        schema:
          type: integer
          format: int64
    put:
      summary: Replace one row
      description: |
        Replaces every cell of the row. The row keeps its id and its `timestamp` (the moment it was appended);
        the time of the update is stored separately and returned as `updated_at`. The row goes through the same
        checks as an append, and a rejected request changes nothing.

        The body is one row, in one of three forms:

        - `application/json`: one object mapping column names to values. Keys are matched to the columns after
          trimming; a column with no key becomes an empty cell and an unknown key is ignored, as on append.
        - `text/csv`: one CSV record, positional, with exactly the dataset's number of cells. With
          `header=present` the first record names the columns and the second is the row.
        - `multipart/form-data`: a `row` part holding the row in either form above (a part with its own
          `Content-Type`, or a plain field: JSON when it starts with `{`, CSV otherwise), plus file parts. A cell
          of an `attachment` column may hold `upload:<part>` to reference a file of the same request; it is
          stored under the per-file and per-request limits and with the type checks of
          `POST /api/datasets/{id}/attachments`, and replaced by its new `attachment:///` URI.

        Cells of `attachment` columns may also hold URIs of the row's current files (to keep them) and of
        `pending` uploads of this dataset. Every file the row held and no longer references is deleted: it reads
        `404` as soon as the response is sent and its bytes are removed from storage right after.

        Owner only: the caller is resolved from the session cookie or a bearer API token. A dataset that does not
        exist or belongs to another user, and a row that is missing or belongs to another dataset, are all `404`.
      operationId: updateRow
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              additionalProperties: true
            example:
              date: '2026-11-03'
              amount: '12.50'
              receipt: attachment:///britt/att_01JC8X3V5ZQ8M2T9K4R7B6N1PD
          text/csv:
            schema:
              type: string
            example: 2026-11-03,12.50,attachment:///britt/att_01JC8X3V5ZQ8M2T9K4R7B6N1PD
          multipart/form-data:
            schema:
              type: object
              required: [row]
              properties:
                row:
                  type: string
                  description: The row, as a JSON object or one CSV record, with `upload:<part>` placeholders.
                  example: '{"date":"2026-11-03","amount":"12.50","receipt":"upload:r1"}'
              additionalProperties:
                type: string
                format: binary
                description: A file part, referenced from the row as `upload:<part name>`.
      responses:
        '200':
          description: The row was replaced.
          content:
            application/json:
              schema:
                type: object
                required: [row_id, timestamp, updated_at, removed_attachments]
                properties:
                  row_id:
                    type: integer
                  timestamp:
                    type: integer
                    description: The row's unchanged `timestamp` (epoch milliseconds).
                  updated_at:
                    type: integer
                    description: When the row was replaced (epoch milliseconds).
                  removed_attachments:
                    type: array
                    items:
                      type: string
                    description: The URIs of the files the row no longer references, which have been deleted.
                  attachments:
                    type: array
                    description: Multipart only, when files were sent. The files stored by this request.
                    items:
                      type: object
                      required: [part, uri, size, content_type]
                      properties:
                        part:
                          type: string
                        uri:
                          type: string
                        size:
                          type: integer
                        content_type:
                          type: string
              example:
                row_id: 1042
                timestamp: 1762128000000
                updated_at: 1762214400000
                removed_attachments: [attachment:///britt/att_01JC8X3V5ZQ8M2T9K4R7B6N1PD]
                attachments:
                  - part: r1
                    uri: attachment:///britt/att_01JC9A0000000000000000000A
                    size: 48213
                    content_type: image/jpeg
        '400':
          description: |
            Nothing was changed. The body is not one row (invalid JSON, a JSON value that is not an object, no row,
            a blank row, more than one row, or an unsupported `Content-Type`), the row cannot be stored (an unmatched
            double quote, or the wrong number of cells for a positional row: listed in `rows`), or an `attachment`
            cell holds something that is not an `attachment:///` URI or a known `upload:` placeholder (listed in
            `attachments`).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/WriteRejected'
        '401':
          description: Authentication required.
        '404':
          description: No such dataset, it belongs to another user, or the row is missing or belongs to another dataset.
        '409':
          description: |
            Nothing was changed. An `attachment` cell references a file that is unknown, another user's, another
            dataset's, bound to another row, or referenced twice. Every problem is listed in `attachments` with its
            `index`, `column`, `value`, `reason` and `status`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/WriteRejected'
        '413':
          description: Nothing was changed. The row holds more than `MAX_ATTACHMENTS_PER_ROW` files (10), or a file or the request is over its size limit.
        '415':
          description: Nothing was changed. A file's sniffed type is not allowed or does not match its declared type.
      security:
        - bearerAuth: []
    delete:
      summary: Delete one row
      description: |
        Deletes the row. Every file the row held reads `404` as soon as the response is sent, and its bytes are
        removed from storage right after.

        Owner only, with the same `404` rules as `PUT`.
      operationId: deleteRow
      responses:
        '200':
          description: The row was deleted.
          content:
            application/json:
              schema:
                type: object
                required: [row_id, rows_deleted, removed_attachments]
                properties:
                  row_id:
                    type: integer
                  rows_deleted:
                    type: integer
                    enum: [1]
                  removed_attachments:
                    type: array
                    items:
                      type: string
                    description: The URIs of the row's files, which have been deleted.
              example:
                row_id: 1042
                rows_deleted: 1
                removed_attachments: [attachment:///britt/att_01JC8X3V5ZQ8M2T9K4R7B6N1PD]
        '401':
          description: Authentication required.
        '404':
          description: No such dataset, it belongs to another user, or the row is missing or belongs to another dataset.
      security:
        - bearerAuth: []
  /api/datasets/{id}/columns/{name}:
    parameters:
      - $ref: '#/components/parameters/datasetId'
      - name: name
        in: path
        required: true
        description: The column's name, exactly as stored (URL-encode it).
        schema:
          type: string
    patch:
      summary: Declare or clear a column's type
      description: |
        Makes an existing column an `attachment` column (`{"type": "attachment"}`), or clears its type
        (`{"type": null}`). This is how a dataset created before attachments existed, or created without
        `column_types`, gets an attachment column.

        Clearing is always allowed; the cells keep their URIs as plain text and are no longer checked. Setting
        `attachment` checks every existing cell first: each must be empty or hold only space-separated URIs of
        uploaded files of this account and this dataset, none bound to a different row. Otherwise the answer is
        `409` listing up to ten offending cells, and the type is unchanged.

        Owner only: the caller is resolved from the session cookie or a bearer API token. A dataset that does not
        exist or belongs to another user is `404`.
      operationId: setColumnType
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [type]
              properties:
                type:
                  type: string
                  nullable: true
                  enum: [attachment, null]
            examples:
              set:
                value: { type: attachment }
              clear:
                value: { type: null }
      responses:
        '200':
          description: The column with its new type.
          content:
            application/json:
              schema:
                type: object
                required: [name, type, index]
                properties:
                  name:
                    type: string
                  type:
                    type: string
                    nullable: true
                    enum: [attachment, null]
                  index:
                    type: integer
                    description: The column's 0-based position among the dataset's headers.
              example:
                name: receipt
                type: attachment
                index: 1
        '400':
          description: The body is not JSON, or `type` is neither `"attachment"` nor `null`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '401':
          description: Authentication required.
        '404':
          description: No such dataset, it belongs to another user, or it has no column with this name.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '409':
          description: |
            Some existing cells are not empty or valid attachment references of this dataset (`cells` lists up to
            ten, `invalid_cells` counts them all), or rows kept arriving while the column was being checked (an
            `Error` body; try again).
          content:
            application/json:
              schema:
                type: object
                required: [error]
                properties:
                  error:
                    type: string
                  invalid_cells:
                    type: integer
                  cells:
                    type: array
                    items:
                      type: object
                      required: [row_id, value, reason]
                      properties:
                        row_id:
                          type: integer
                        value:
                          type: string
                        reason:
                          type: string
                          enum:
                            - not an attachment URI
                            - attachment URI of another account
                            - no such attachment in this dataset
                            - attachment already used by another row
              example:
                error: 'Column "receipt" has 1 cell that is not empty or attachment URIs of this dataset'
                invalid_cells: 1
                cells:
                  - row_id: 1041
                    value: receipt.jpg
                    reason: not an attachment URI
      security:
        - bearerAuth: []
  /api/datasets/{id}/attachments:
    parameters:
      - $ref: '#/components/parameters/datasetId'
    post:
      summary: Upload files to reference from rows later
      description: |
        Stores one or more files for the dataset and returns their `attachment:///` URIs. Each file is `pending`:
        no row references it yet. Put the URI in an `attachment` cell with an ordinary CSV or JSON append, a
        multipart append, or `PUT /api/datasets/{id}/rows/{rowId}` to bind it to that row. A file no row references
        within 24 hours is deleted. A pending file cannot be downloaded yet.

        Every file part of the `multipart/form-data` body is a file (field names are ignored). All of them are
        checked before anything is stored, so a rejected request stores nothing: each file at most
        `MAX_ATTACHMENT_BYTES` (25 MB) and not empty, the request at most `MAX_ATTACHMENT_REQUEST_BYTES` (100 MB),
        and the type sniffed from the bytes on the allowlist and in agreement with the part's declared type. File
        names are sanitised (every character other than a letter, digit, `.` or `-` becomes `_`) and capped at
        255 bytes.

        Owner only: the caller is resolved from the session cookie or a bearer API token. A dataset that does not
        exist or belongs to another user is `404`.
      operationId: uploadAttachments
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              additionalProperties:
                type: string
                format: binary
      responses:
        '201':
          description: The files were stored as `pending` attachments of the dataset, in part order.
          content:
            application/json:
              schema:
                type: object
                required: [attachments]
                properties:
                  attachments:
                    type: array
                    items:
                      type: object
                      required: [uri, file_name, content_type, size, status]
                      properties:
                        uri:
                          type: string
                          example: attachment:///britt/att_01JC8X3V5ZQ8M2T9K4R7B6N1PD
                        file_name:
                          type: string
                          description: The sanitised file name.
                        content_type:
                          type: string
                          description: The sniffed type.
                        size:
                          type: integer
                        status:
                          type: string
                          enum: [pending]
              example:
                attachments:
                  - uri: attachment:///britt/att_01JC8X3V5ZQ8M2T9K4R7B6N1PD
                    file_name: receipt.jpg
                    content_type: image/jpeg
                    size: 48213
                    status: pending
        '400':
          description: The body is not valid multipart, holds no file part, or a file is empty.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '401':
          description: Authentication required.
        '404':
          description: No such dataset, or it belongs to another user.
        '413':
          description: A file is over `MAX_ATTACHMENT_BYTES`, or the request is over `MAX_ATTACHMENT_REQUEST_BYTES`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '415':
          description: |
            The request is not `multipart/form-data`, or a file's sniffed type is not on the allowlist or does not
            match its declared type. SVG and HTML are always rejected.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
      security:
        - bearerAuth: []
  /api/attachments/usage:
    get:
      summary: Attachment storage used by the caller's account
      description: |
        The number and total size of the caller's attachments, `pending` uploads included. There is no per-account
        quota; the same numbers are shown on the profile page. The caller is resolved from the session cookie or a
        bearer API token.
      operationId: getAttachmentUsage
      responses:
        '200':
          description: The account's usage.
          headers:
            Cache-Control:
              schema:
                type: string
              description: Always `private, no-store`.
          content:
            application/json:
              schema:
                type: object
                required: [count, bytes]
                properties:
                  count:
                    type: integer
                  bytes:
                    type: integer
              example:
                count: 12
                bytes: 5242880
        '401':
          description: Authentication required.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
      security:
        - bearerAuth: []
  /api/attachments/{attachmentId}:
    parameters:
      - name: attachmentId
        in: path
        required: true
        description: The id from an `attachment:///<userName>/<attachmentId>` URI.
        schema:
          type: string
          pattern: '^att_[0-7][0-9A-HJKMNP-TV-Z]{25}$'
        example: att_01JC8X3V5ZQ8M2T9K4R7B6N1PD
    get:
      summary: Download an attachment, or read its metadata
      description: |
        Streams the file from private storage. This is the only way to read an attachment's bytes; the dataset page
        links each file here.

        Only the file's owner can read it, with a session cookie or a bearer API token; the owner is taken from the
        stored attachment, never from the URL. Everything else is the same `404`, so ids cannot be probed: no
        credentials, another account's credentials, an unknown or malformed id, a file not yet referenced by a row
        (`pending`), a file being deleted, and a file whose dataset is gone.

        With `?meta=1` the answer is the file's metadata as JSON instead of its bytes.

        The bytes are served as the type sniffed at upload (text types with `; charset=utf-8`), with
        `X-Content-Type-Options: nosniff` and `Content-Security-Policy: sandbox; default-src 'none'`.
        `Content-Disposition` is `inline` for raster images and PDF, so they open in the browser, and `attachment`
        for everything else. Responses carry an `ETag`, and `If-None-Match` is answered with `304`; a single
        `Range` is answered with `206` (or `416` when it starts past the end; a multi-range header is ignored).
        `Cache-Control` is always `private, max-age=300`.
      operationId: getAttachment
      parameters:
        - name: meta
          in: query
          required: false
          description: '`1` returns the metadata as JSON instead of the file.'
          schema:
            type: string
            enum: ['1']
        - name: Range
          in: header
          required: false
          description: A single byte range, e.g. `bytes=0-1023`.
          schema:
            type: string
        - name: If-None-Match
          in: header
          required: false
          schema:
            type: string
      responses:
        '200':
          description: The file, or with `?meta=1` its metadata.
          headers:
            ETag:
              schema:
                type: string
            Content-Disposition:
              description: '`inline; filename="<name>"` for raster images and PDF, otherwise `attachment; filename="<name>"`.'
              schema:
                type: string
            Cache-Control:
              schema:
                type: string
              description: '`private, max-age=300`.'
          content:
            application/octet-stream:
              schema:
                type: string
                format: binary
            application/json:
              schema:
                type: object
                required: [uri, file_name, content_type, size, sha256, dataset_id, row_id, created_at]
                properties:
                  uri:
                    type: string
                  file_name:
                    type: string
                  content_type:
                    type: string
                  size:
                    type: integer
                  sha256:
                    type: string
                    description: Lower-case hex SHA-256 of the file, taken at upload.
                  dataset_id:
                    type: integer
                  row_id:
                    type: integer
                    description: The row that references the file.
                  created_at:
                    type: string
                    format: date-time
              example:
                uri: attachment:///britt/att_01JC8X3V5ZQ8M2T9K4R7B6N1PD
                file_name: receipt.jpg
                content_type: image/jpeg
                size: 48213
                sha256: 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08
                dataset_id: 42
                row_id: 1043
                created_at: '2026-11-03T12:00:00.000Z'
        '206':
          description: The requested byte range, with `Content-Range`.
        '304':
          description: '`If-None-Match` matched the current `ETag`.'
        '404':
          description: Not found, or not readable by the caller (see above).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
              example:
                error: Attachment not found
        '416':
          description: The `Range` cannot be satisfied; `Content-Range` gives the size.
      security:
        - bearerAuth: []
  /api/oauth/token:
    post:
      summary: OAuth 2.1 Token Endpoint
      description: |
        Issue access tokens using OAuth 2.1 flows.
        Supports client_credentials, authorization_code, and refresh_token grant types.
      operationId: getToken
      requestBody:
        required: true
        content:
          application/x-www-form-urlencoded:
            schema:
              type: object
              required:
                - grant_type
                - client_id
                - client_secret
              properties:
                grant_type:
                  type: string
                  enum: [client_credentials, authorization_code, refresh_token]
                  description: The OAuth grant type
                client_id:
                  type: string
                  description: OAuth client ID
                client_secret:
                  type: string
                  description: OAuth client secret
                code:
                  type: string
                  description: Authorization code (required for authorization_code grant)
                redirect_uri:
                  type: string
                  description: Redirect URI (required for authorization_code grant)
                refresh_token:
                  type: string
                  description: Refresh token (required for refresh_token grant)
                scope:
                  type: string
                  description: Space-separated list of scopes
      responses:
        '200':
          description: Successful token response
          content:
            application/json:
              schema:
                type: object
                properties:
                  access_token:
                    type: string
                    description: JWT access token
                  token_type:
                    type: string
                    example: Bearer
                  expires_in:
                    type: integer
                    example: 3600
                  refresh_token:
                    type: string
                    description: Refresh token (only for authorization_code and refresh_token grants)
                  scope:
                    type: string
                    description: Granted scopes
        '400':
          description: Invalid request
        '401':
          description: Invalid client credentials
  /api/oauth/jwks.json:
    get:
      summary: JSON Web Key Set
      description: Public keys for verifying JWT access tokens
      operationId: getJWKS
      responses:
        '200':
          description: JWKS response
          content:
            application/json:
              schema:
                type: object
                properties:
                  keys:
                    type: array
                    items:
                      type: object
  /api/oauth/authorize:
    get:
      summary: OAuth Authorization Endpoint
      description: Begin OAuth authorization_code flow
      operationId: authorize
      parameters:
        - name: client_id
          in: query
          required: true
          schema:
            type: string
        - name: redirect_uri
          in: query
          required: true
          schema:
            type: string
        - name: response_type
          in: query
          required: true
          schema:
            type: string
            enum: [code]
        - name: scope
          in: query
          schema:
            type: string
        - name: state
          in: query
          schema:
            type: string
      responses:
        '302':
          description: Redirect to login or callback
  /api/oauth/clients:
    get:
      summary: List OAuth clients
      description: List all OAuth clients for the authenticated user
      operationId: listClients
      security:
        - bearerAuth: []
      responses:
        '200':
          description: List of clients
          content:
            application/json:
              schema:
                type: object
                properties:
                  clients:
                    type: array
                    items:
                      type: object
    post:
      summary: Create OAuth client
      description: Register a new OAuth client
      operationId: createClient
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - name
                - allowed_grants
                - allowed_scopes
              properties:
                name:
                  type: string
                redirect_uris:
                  type: array
                  items:
                    type: string
                allowed_grants:
                  type: array
                  items:
                    type: string
                    enum: [client_credentials, authorization_code, refresh_token]
                allowed_scopes:
                  type: array
                  items:
                    type: string
                    enum: [mcp.ingest, mcp.read, mcp.write, mcp.admin]
      responses:
        '201':
          description: Client created
          content:
            application/json:
              schema:
                type: object
                properties:
                  client:
                    type: object
                  client_secret:
                    type: string
                  warning:
                    type: string
  /api/oauth/register:
    post:
      summary: Dynamic Client Registration
      description: |
        RFC 7591: OAuth 2.0 Dynamic Client Registration Protocol.
        Allows clients to register programmatically with the authorization server.
        Requires user authentication - the client will be associated with the authenticated user.
      operationId: registerClient
      security:
        - bearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - client_name
              properties:
                client_name:
                  type: string
                  description: Human-readable name of the client
                  example: "My MCP Client"
                redirect_uris:
                  type: array
                  items:
                    type: string
                    format: uri
                  description: Array of redirect URIs (required for authorization_code grant)
                  example: ["https://example.com/callback"]
                grant_types:
                  type: array
                  items:
                    type: string
                    enum: [client_credentials, authorization_code, refresh_token]
                  default: ["client_credentials"]
                  description: OAuth 2.0 grant types to be used by the client
                scope:
                  type: string
                  default: "mcp.read mcp.ingest"
                  description: Space-separated list of scope values
                  example: "mcp.read mcp.ingest"
                token_endpoint_auth_method:
                  type: string
                  enum: [client_secret_post, client_secret_basic]
                  default: "client_secret_post"
                  description: Authentication method for the token endpoint
            examples:
              mcp_client:
                summary: MCP Client (default)
                value:
                  client_name: "Claude Desktop"
                  grant_types: ["client_credentials"]
                  scope: "mcp.read mcp.ingest"
              oauth_client:
                summary: OAuth Authorization Code Client
                value:
                  client_name: "My Web App"
                  redirect_uris: ["https://myapp.com/callback"]
                  grant_types: ["authorization_code", "refresh_token"]
                  scope: "mcp.read mcp.write"
      responses:
        '201':
          description: Client successfully registered
          content:
            application/json:
              schema:
                type: object
                required:
                  - client_id
                  - client_secret
                  - client_id_issued_at
                properties:
                  client_id:
                    type: string
                    description: OAuth 2.0 client identifier string
                    example: "client_abc123..."
                  client_secret:
                    type: string
                    description: OAuth 2.0 client secret string (only shown once)
                    example: "secret_xyz789..."
                  client_id_issued_at:
                    type: integer
                    description: Unix timestamp when the client_id was issued
                  client_secret_expires_at:
                    type: integer
                    description: Unix timestamp when client_secret expires (0 = never)
                  client_name:
                    type: string
                  redirect_uris:
                    type: array
                    items:
                      type: string
                  grant_types:
                    type: array
                    items:
                      type: string
                  token_endpoint_auth_method:
                    type: string
                  scope:
                    type: string
        '400':
          description: Invalid client metadata
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
                    enum: [invalid_client_metadata, invalid_redirect_uri]
                  error_description:
                    type: string
        '401':
          description: Unauthorized - authentication required
        '500':
          description: Server error
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
                    enum: [server_error]
                  error_description:
                    type: string
  /.well-known/oauth-authorization-server:
    get:
      summary: OAuth 2.0 Authorization Server Metadata
      description: RFC 8414 metadata endpoint for OAuth discovery
      operationId: getAuthServerMetadata
      responses:
        '200':
          description: Authorization server metadata
          content:
            application/json:
              schema:
                type: object
                properties:
                  issuer:
                    type: string
                  token_endpoint:
                    type: string
                  jwks_uri:
                    type: string
                  scopes_supported:
                    type: array
                    items:
                      type: string
  /.well-known/oauth-protected-resource:
    get:
      summary: OAuth 2.0 Protected Resource Metadata
      description: Declares this server as an OAuth-protected resource
      operationId: getResourceMetadata
      responses:
        '200':
          description: Protected resource metadata
          content:
            application/json:
              schema:
                type: object
                properties:
                  resource:
                    type: string
                  authorization_servers:
                    type: array
                    items:
                      type: string
                  mcp_endpoint:
                    type: string
  /api/mcp:
    post:
      summary: Model Context Protocol (MCP) Endpoint
      description: |
        JSON-RPC 2.0 endpoint implementing the Model Context Protocol.
        Provides tools, resources, and prompts for AI assistants to interact with CSV datasets.

        **Supported Methods:**
        - `initialize` - Initialize MCP session
        - `tools/list` - List available dataset operations
        - `tools/call` - Execute dataset operations
        - `resources/list` - List user's datasets as resources
        - `resources/read` - Read dataset contents (`dataset:///<userName>/<datasetName>`), or an attachment's bytes
          as a base64 `blob` (`attachment:///<userName>/<attachmentId>`, up to 5 MB; larger files are read from
          `GET /api/attachments/{attachmentId}`). Other users' resources are an error.
        - `resources/templates/list` - The `attachment:///{userName}/{attachmentId}` template (attachments are not
          listed by `resources/list`)
        - `prompts/list` - List available prompts
        - `prompts/get` - Get prompt content

        **Tools** (`tools/list` returns their full schemas):

        | Tool | What | Scope |
        | --- | --- | --- |
        | `list_datasets` | The caller's datasets | `mcp.read` |
        | `get_dataset_info` | A dataset's columns, with `type: attachment` on attachment columns | `mcp.read` |
        | `read_dataset` | Rows as CSV; `limit`, `offset`, `order`, `include_row_ids`, `after_row_id`, and `attachments: "metadata"` to also list each URI's file name, type and size (never bytes) | `mcp.read` |
        | `create_dataset` | A new dataset; `column_types: {"receipt": "attachment"}` declares attachment columns | `mcp.write` |
        | `append_rows` | Rows as CSV records; `attachments: [{ name, file_name, content_type, data_base64 }]` (≤ 5 MB per call) that rows reference as `upload:<name>`; returns the new row ids and URIs | `mcp.write` or `mcp.ingest` |
        | `upload_attachment` | One base64 file → a `pending` URI to use in a later append or update | `mcp.write` or `mcp.ingest` |
        | `update_row` | Replace a row by `row_id`, with the same `attachments` argument; files it no longer references are deleted | `mcp.write` |
        | `delete_row` | Delete a row by `row_id`, and its files | `mcp.write` |
        | `delete_dataset` | Delete a dataset, its rows and its files | `mcp.admin` |
      operationId: mcpJsonRpc
      security:
        - oauth2: [mcp.read]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - jsonrpc
                - method
              properties:
                jsonrpc:
                  type: string
                  enum: ["2.0"]
                  description: JSON-RPC version
                method:
                  type: string
                  description: MCP method name
                  enum:
                    - initialize
                    - tools/list
                    - tools/call
                    - resources/list
                    - resources/read
                    - resources/templates/list
                    - prompts/list
                    - prompts/get
                params:
                  type: object
                  description: Method parameters
                id:
                  oneOf:
                    - type: string
                    - type: number
                    - type: "null"
                  description: Request ID
            examples:
              initialize:
                summary: Initialize MCP session
                value:
                  jsonrpc: "2.0"
                  method: initialize
                  id: 1
              tools_list:
                summary: List available tools
                value:
                  jsonrpc: "2.0"
                  method: tools/list
                  id: 2
              tools_call:
                summary: Call a tool
                value:
                  jsonrpc: "2.0"
                  method: tools/call
                  params:
                    name: read_dataset
                    arguments:
                      dataset_name: sales_data
                      limit: 100
                  id: 3
              resources_list:
                summary: List datasets as resources
                value:
                  jsonrpc: "2.0"
                  method: resources/list
                  id: 4
              resources_read:
                summary: Read a dataset resource
                value:
                  jsonrpc: "2.0"
                  method: resources/read
                  params:
                    uri: "dataset:///username/sales_data"
                  id: 5
      responses:
        '200':
          description: JSON-RPC response
          content:
            application/json:
              schema:
                type: object
                properties:
                  jsonrpc:
                    type: string
                    enum: ["2.0"]
                  result:
                    type: object
                    description: Method result (on success)
                  error:
                    type: object
                    description: Error details (on failure)
                    properties:
                      code:
                        type: integer
                      message:
                        type: string
                      data:
                        type: object
                  id:
                    oneOf:
                      - type: string
                      - type: number
                      - type: "null"
        '401':
          description: Unauthorized - missing or invalid OAuth token
        '403':
          description: Forbidden - insufficient scope
components:
  parameters:
    username:
      name: username
      in: path
      required: true
      description: The registered username of the user.
      schema:
        type: string
    dataset:
      name: dataset
      in: path
      required: true
      description: The path to the dataset, treated as a unique identifier.
      schema:
        type: string
    datasetId:
      name: id
      in: path
      required: true
      description: |
        The numeric id of the dataset. It is returned as `dataset_id` by `POST /api/uploads/text` and by an
        attachment's `GET /api/attachments/{attachmentId}?meta=1`.
      schema:
        type: integer
        format: int64
  schemas:
    WriteRejected:
      type: object
      required: [error, rows]
      properties:
        error:
          type: string
          description: A one-line summary of every problem listed below.
        rows:
          type: array
          description: Every row that could not be stored. Empty when the problem is the column names.
          items:
            type: object
            required: [index, reason]
            properties:
              index:
                type: integer
                minimum: 0
                description: |
                  0-based position of the row among the data rows: the array index of a JSON row, or the line's
                  position after the header line (when there is one) for CSV. The header line itself is never a
                  row; problems with it are reported under `headers`.
              reason:
                type: string
                example: unmatched double quote
        headers:
          type: array
          description: |
            Present only when a new dataset's column names were rejected. Every bad name is listed. A header line
            that could not be read at all is one entry with `index` 0 and an empty `name`.
          items:
            type: object
            required: [index, name, reason]
            properties:
              index:
                type: integer
                minimum: 0
                description: 0-based position of the column name, after trimming.
              name:
                type: string
                description: The trimmed name that was rejected; empty when the header line could not be read.
              reason:
                type: string
                example: duplicate name
                description: '`empty name`, `duplicate name`, `reserved name`, or why the header line could not be read.'
        attachments:
          type: array
          description: |
            Present only when `attachment` cells were rejected. Every problem is listed; the response's status is the
            most serious kind present (`400`, then `413`, then `409`).
          items:
            type: object
            required: [index, column, value, reason, status]
            properties:
              index:
                type: integer
                minimum: 0
                description: 0-based position of the row among the data rows, as in `rows`.
              column:
                type: string
              value:
                type: string
                description: The offending URI or `upload:` placeholder, or the whole cell when it holds too many files.
              reason:
                type: string
                example: attachment belongs to another dataset
                description: |
                  For example `not an attachment:/// URI`, `unknown attachment`, `no file part named "r2"`, `attachment is referenced more
                  than once`, `attachment belongs to another dataset`, `attachment is already attached to row 1041`,
                  `the URI names another user` or `row holds more than 10 attachments`.
              status:
                type: integer
                enum: [400, 409, 413]
    Error:
      type: object
      required: [error]
      properties:
        error:
          type: string
          example: Attachment not found
    StoredUpload:
      type: object
      description: A file stored by a multipart write, and the URI that replaced its `upload:<part>` placeholder.
      required: [part, uri, size, content_type]
      properties:
        part:
          type: string
        uri:
          type: string
          example: attachment:///britt/att_01JC8X3V5ZQ8M2T9K4R7B6N1PD
        size:
          type: integer
        content_type:
          type: string
          description: The type sniffed from the file's bytes.
    PendingExport:
      type: object
      required: [status, format, location, retry_after, error]
      properties:
        status:
          type: string
          enum: [pending]
        format:
          type: string
          enum: [sqlite, zip, tar.gz]
        location:
          type: string
          description: The URL to poll, the same value as the `Location` header.
        retry_after:
          type: integer
          description: Seconds to wait before polling again, the same value as the `Retry-After` header.
        error:
          type: string
          nullable: true
          description: |
            The error from the failed job the caller is waiting on, or `null`. A format that is merely being rebuilt
            never inherits another format's note, and a format the job deliberately skipped is reported as `404`
            with its reason as the body rather than here.
    DatasetDescription:
      type: object
      required: [description, source, updated_at, latest_job]
      properties:
        description:
          type: string
          nullable: true
          description: The description text, or `null` when the dataset has none.
        source:
          type: string
          nullable: true
          enum: [ai, user, null]
          description: Who wrote the current description. `null` when there is none.
        updated_at:
          type: integer
          format: int64
          nullable: true
          description: When the description was last written, in milliseconds since the Unix epoch.
        latest_job:
          nullable: true
          description: The most recent description job for this dataset, or `null` if there has never been one.
          type: object
          required: [id, trigger, status, error, created_at, completed_at]
          properties:
            id:
              type: string
              format: uuid
            trigger:
              type: string
              enum: [auto, manual]
              description: '`auto` for the background sweep, `manual` for an on-demand request.'
            status:
              type: string
              enum: [pending, processing, completed, failed]
            error:
              type: string
              nullable: true
              description: Why the job failed; `null` unless `status` is `failed`.
            created_at:
              type: string
              nullable: true
              description: UTC timestamp, `YYYY-MM-DD HH:MM:SS`.
            completed_at:
              type: string
              nullable: true
              description: UTC timestamp, `YYYY-MM-DD HH:MM:SS`; `null` until the job finishes.
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
    oauth2:
      type: oauth2
      flows:
        clientCredentials:
          tokenUrl: /api/oauth/token
          scopes:
            mcp.read: Read data from datasets
            mcp.write: Create and manage datasets
            mcp.ingest: Append data to existing datasets
            mcp.admin: Full administrative access including delete
        authorizationCode:
          authorizationUrl: /api/oauth/authorize
          tokenUrl: /api/oauth/token
          scopes:
            mcp.read: Read data from datasets
            mcp.write: Create and manage datasets
            mcp.ingest: Append data to existing datasets
            mcp.admin: Full administrative access including delete