MDDB API Documentation

Note: The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119.

Table of Contents #

Overview #

MDDB is a lightweight markdown database server built with Go and BoltDB. It provides a RESTful API for storing, retrieving, and managing markdown documents with metadata.

Base URL: http://localhost:11023

API Version: v1

Configuration #

The server can be configured using environment variables:

Variable Default Description
MDDB_ADDR :11023 Server address and port
MDDB_MODE wr Access mode: read, write, or wr (read+write). Also: --mode flag, database.mode in YAML
MDDB_PATH mddb.db Path to the BoltDB database file. Also: --db flag, database.path in YAML
MDDB_EMBEDDING_PROVIDER none Embedding provider: openai, ollama, voyage, cohere, lexical (no model, not meaning-aware), or none
MDDB_EMBEDDING_API_KEY API key for OpenAI or Voyage AI
MDDB_EMBEDDING_API_URL (per provider) API base URL (see Vector Search)
MDDB_EMBEDDING_MODEL (per provider) Embedding model name
MDDB_EMBEDDING_DIMENSIONS (per provider) Vector dimensions
MDDB_FTS_STEMMING true Enable stemming for FTS
MDDB_FTS_DEFAULT_LANG en Default language for FTS stemming and stop words (17 languages supported)
MDDB_FTS_SYNONYMS true Enable synonym expansion for FTS
MDDB_COMPRESSION_ENABLED true Enable adaptive compression (Snappy/Zstd)
MDDB_COMPRESSION_SMALL_THRESHOLD 1024 Snappy compression threshold (bytes)
MDDB_COMPRESSION_MEDIUM_THRESHOLD 10240 Zstd compression threshold (bytes)

Access Modes #

  • read: Read-only mode. Write operations will return 403 Forbidden
  • write: Write-only mode (not commonly used)
  • wr: Read and write mode (recommended for most use cases)

Endpoints #

POST /v1/add #

Add or update a markdown document in a collection.

Request Body:

{
  "collection": "blog",
  "key": "homepage",
  "lang": "en_GB",
  "meta": {
    "category": ["blog", "featured"],
    "author": ["John Doe"],
    "tags": ["golang", "database"]
  },
  "contentMd": "# Welcome\n\nThis is the homepage content."
}

Response:

{
  "id": "blog|homepage|en_gb",
  "key": "homepage",
  "lang": "en_GB",
  "meta": {
    "category": ["blog", "featured"],
    "author": ["John Doe"],
    "tags": ["golang", "database"]
  },
  "contentMd": "# Welcome\n\nThis is the homepage content.",
  "addedAt": 1699296000,
  "updatedAt": 1699296000,
  "revision": "53f8149d734342a9"
}

Optional fields:

  • ttl: seconds until the document expires (0 = never)
  • expectedRevision: write only if the document is still at this revision; otherwise 409 Conflict — see conditional writes
  • ifAbsent (v2.19.6): create only. When the document already exists the answer is 409 Conflict with its currentRevision and an empty expectedRevision, and nothing is written. A document past its TTL counts as absent. Cannot be combined with expectedRevision (400)

Features:

  • Creates a new document or updates an existing one (ifAbsent makes it create-only)
  • Automatically generates a deterministic ID based on collection, key, and lang
  • Maintains revision history
  • Updates metadata indices
  • Tracks addedAt (first creation) and updatedAt (last modification) timestamps

cURL Example:

curl -X POST http://localhost:11023/v1/add \
  -H 'Content-Type: application/json' \
  -d '{
    "collection": "blog",
    "key": "homepage",
    "lang": "en_GB",
    "meta": {
      "category": ["blog"]
    },
    "contentMd": "# Welcome to my blog"
  }'

POST /v1/add-batch #

Add multiple documents to a collection in a single request. Uses the optimized batch processor for high throughput. Fires all post-commit hooks (embedding, FTS indexing, webhooks, TTL, automation triggers).

Request Body:

{
  "collection": "blog",
  "documents": [
    {
      "key": "post1",
      "lang": "en",
      "contentMd": "# Post 1\n\nFirst post content.",
      "meta": {
        "category": ["blog"],
        "author": ["John Doe"]
      },
      "saveRevision": true
    },
    {
      "key": "post2",
      "lang": "en",
      "contentMd": "# Post 2\n\nSecond post content.",
      "meta": {
        "category": ["tutorial"]
      }
    }
  ]
}

Parameters:

  • collection (required): Collection name
  • documents (required): Array of documents to add
    • key (required): Document key
    • lang (required): Language code
    • contentMd (required unless contentBase64 is given): Markdown content
    • format (optional): convert the document from this format (html, pdf, docx, odt, rtf, xlsx, ods, csv, tsv, pptx, odp, epub, eml, mbox, tex, yaml, log, ... — see the format table under /v1/upload). Empty means the key's extension. Without contentBase64, contentMd is the file's text (HTML sent as a string)
    • contentBase64 (optional): the file to convert, base64-encoded. It goes through the same converters as /v1/upload; the stored document is the Markdown, with meta.sourceFormat set. With skipDuplicates the converted Markdown is compared, so an unchanged file is skipped. A format with no converter fails that document (unsupported format: bin), not the batch
    • meta (optional): Metadata key-value pairs
    • saveRevision (optional): Whether to save a revision for this document

Response:

{
  "added": 1,
  "updated": 1,
  "failed": 0,
  "errors": []
}

embeddingDropped appears only when non-zero: that many documents were stored without a vector because the embedding queue was full and the write gave up waiting. failed stays 0 — the documents are in the database; they are simply unreachable by vector and hybrid search until POST /v1/vector-reindex fills them in. See MDDB_EMBEDDING_QUEUE_SIZE and MDDB_EMBEDDING_QUEUE_WAIT.

{
  "added": 4000,
  "updated": 0,
  "failed": 0,
  "embeddingDropped": 1298
}

cURL Example:

curl -X POST http://localhost:11023/v1/add-batch \
  -H 'Content-Type: application/json' \
  -d '{
    "collection": "blog",
    "documents": [
      {"key": "p1", "lang": "en", "contentMd": "# Hello"},
      {"key": "p2", "lang": "en", "contentMd": "# World"}
    ]
  }'

POST /v1/bulk-ingest-job #

Queue a long-running bulk ingest job and return immediately with a job ID. Poll /v1/bulk-ingest-job/{id} or supply callbackUrl for a webhook on completion. Jobs are processed by a single FIFO worker in chunks of 500 documents, so many small jobs queue rather than run in parallel. The whole request body counts against MDDB_MAX_BODY_BYTES (32 MB by default), and ingest options such as profile: fast do not apply here (use /v1/ingest for those). See BULK-IMPORT.

Request Body: same shape as /v1/add-batch, plus optional callbackUrl.

Response: HTTP 202 with {id, collection, status: "pending", total, submittedAt}.

Companion endpoints:

  • GET /v1/bulk-ingest-job/{id} — status poll
  • DELETE /v1/bulk-ingest-job/{id} — cancel (pending jobs only)
  • GET /v1/bulk-ingest-jobs?collection=X — list all jobs, newest first ({"jobs": [...], "total": n}; jobs is [], not null, when there are none)

See BULK-IMPORT for full usage and semantics.


POST /v1/ingest #

Bulk ingest endpoint with advanced features for scraping pipelines and data import workflows. Supports URL key derivation, YAML frontmatter extraction, content deduplication, auto-metadata injection, and collection auto-configuration.

Request Body:

{
  "collection": "imported",
  "documents": [
    {
      "url": "https://example.com/page1",
      "lang": "en",
      "contentMd": "# Page 1\n\nContent here.",
      "scraper": "my-crawler",
      "scrapedAt": 1709500000,
      "ttl": 86400
    },
    {
      "url": "https://example.com/page2",
      "lang": "en",
      "contentMd": "---\ntitle: Page 2\ncategory: tutorial\n---\n# Page 2\n\nMore content.",
      "extractFrontmatter": true
    }
  ],
  "options": {
    "skipDuplicates": true,
    "autoConfigureCollection": true
  }
}

Parameters:

  • collection (required): Collection name
  • documents (required): Array of documents to ingest
    • url (optional): Source URL — used for key derivation and auto-injected as source_url metadata
    • key (optional): Document key — if empty, derived from URL
    • lang (required): Language code
    • contentMd (required): Markdown content
    • meta (optional): Metadata key-value pairs
    • extractFrontmatter (optional): Parse YAML frontmatter from content and merge into metadata
    • scrapedAt (optional): Unix timestamp of when the content was scraped — auto-injected as scraped_at metadata
    • scraper (optional): Scraper identifier — auto-injected as scraper metadata
    • ttl (optional): Time-to-live in seconds
  • options (optional): Ingest options
    • skipDuplicates (optional): Skip documents whose content hasn't changed (CRC32 hash comparison)
    • skipEmbeddings (optional): Skip embedding generation for this batch
    • skipFts (optional): Skip FTS indexing for this batch
    • skipWebhooks (optional): Skip webhook firing for this batch
    • autoConfigureCollection (optional): Auto-configure collection as "scraping" type if it doesn't exist
    • saveRevision (optional): Save revision history for all documents in this batch
    • profile (optional): default or fast — see below
    • textOnly (optional): Extract plain text from html/docx/odt instead of rebuilding Markdown structure. Implied by profile: fast. Applies to documents sent with format/contentBase64.

Response:

{
  "added": 2,
  "updated": 0,
  "skipped": 0,
  "failed": 0,
  "errors": [],
  "collection": "imported",
  "durationMs": 45,
  "profile": "fast"
}

The response also lists conversions: every document converted from a file sent with contentBase64, with its key, the format it came from, conversionConfidence and conversionWarnings (see Conversion confidence below). An email's attachments and a mailbox's messages are stored as documents of their own and listed there too.

The fast ingest profile

MDDB could always ingest faster by skipping steps — the flags existed — but only as separate switches a caller had to discover one at a time, and the wiki importer made the same choice a third way with a skipFts comment reading "faster bulk import". The trade-off was available and undiscoverable.

profile: fast names it. It applies to /v1/ingest, /v1/upload (multipart field profile) and /v1/import-wiki, and the response records which profile actually applied — so a corpus loaded months ago can be explained without guessing which flags the caller sent.

default fast
Heavy-format parsing Full Markdown structure Plain text
Revisions As requested Off
Webhooks Fired Skipped
Duplicates As requested Skipped
Embeddings On On
Full-text index On On

The last two rows are the point. fast means cheaper parsing and less bookkeeping — not a collection you cannot search. Skipping embeddings or FTS stays a separate decision with its own flag, because folding it in would make fast mean something the caller did not ask for.

Any flag set explicitly overrides the preset, so {"profile": "fast", "saveRevision": true} gives fast ingest with revisions kept. An unknown profile name is a 400, never a silent fall back to default — a caller who asked for fast and got default behaviour would see a slow load and no reason why.

What text-only actually buys, measured (200-section documents, -benchtime=2s):

Format Full conversion Text-only
HTML 132 ms 3.2 ms 43× faster
DOCX 147 µs 130 µs 1.13× faster
PDF — — no variant

HTML is where the win is: its Markdown converter makes repeated case-insensitive passes over the whole document for every tag type. The DOCX converter was already efficient, so text-only is barely faster there — its value for .docx is tolerance of documents that odd exporters produce, not speed. PDF has no text-only variant at all: pdfToMarkdown already extracts raw text from content streams and builds no structure, so a second name for it would promise a speedup that does not exist.

Features:

  • URL key derivation: If key is empty, a deterministic key is derived from the URL path
  • Frontmatter extraction: When extractFrontmatter is true, YAML frontmatter is parsed from content and merged into metadata (request metadata takes priority over frontmatter)
  • Auto-metadata injection: source_url, scraped_at, and scraper fields are auto-injected into document metadata
  • Content deduplication: With skipDuplicates, existing documents with identical content (CRC32 hash) are skipped
  • Collection auto-configuration: With autoConfigureCollection, the collection is created with type "scraping" if it doesn't exist
  • Selective hook control: Skip embeddings, FTS, or webhooks per batch via options

cURL Example:

curl -X POST http://localhost:11023/v1/ingest \
  -H 'Content-Type: application/json' \
  -d '{
    "collection": "imported",
    "documents": [
      {"url": "https://example.com/page1", "lang": "en", "contentMd": "# Hello", "scraper": "my-crawler"},
      {"url": "https://example.com/page2", "lang": "en", "contentMd": "# World", "extractFrontmatter": true}
    ],
    "options": {"autoConfigureCollection": true, "skipDuplicates": true}
  }'

POST /v1/upload #

Upload files via multipart/form-data. Files are auto-converted to Markdown and stored as documents. Supports single and batch upload.

Content-Type: multipart/form-data

Form Fields:

  • file or files[] (required): One or more files to upload. Supported formats: .md, .txt, .html, .htm, .pdf, .docx, .odt, .rtf, .xlsx, .ods, .csv, .tsv, .pptx, .odp, .epub, .eml, .mbox, .yaml, .yml, .log, .lex, .tex, .latex (see the table below)
  • collection (required): Target collection name
  • lang (required): Document language code (e.g. en_US, pl_PL)
  • key (optional): Document key — if empty, derived from filename (lowercase, spaces→hyphens, extension stripped). Keys resolve case-insensitively — see below
  • meta (optional): JSON-encoded metadata map, e.g. {"category":["docs"]}
  • ttl (optional): Time-to-live in seconds (0 = no expiry)
  • maxSize (optional): Per-file size limit in bytes (default: 10MB, max: 100MB)
  • profile / textOnly (optional): as for /v1/ingest

Upload, /v1/ingest with contentBase64, and the MCP tools upload_file and ingest_documents share one conversion path, so a format converts the same way whichever door it comes through.

Images #

  • extractImages=true (form field; options.extractImages on /v1/ingest): the images of Markdown files and PDFs become image documents under KEY/images/ with meta.kind: image, meta.parent, meta.altText, meta.caption and meta.page. On by default in a collection of type images, where an image file on its own is an image document too. Image files uploaded with a Markdown file are the files its links name; an upload of only image files elsewhere is 400.
  • fetchRemoteImages=true (options.fetchRemoteImages): fetch Markdown image links to http(s) URLs, through the SSRF guard. Off by default.
  • On /v1/ingest, a Markdown document's images: [{"path": "img/a.png", "contentBase64": "..."}] are the files its relative links name. Under skipDuplicates, an image whose bytes changed is written even when its text did not.
  • GET /v1/image?collection=docs&key=manual%2Fimages%2Fseal.png&lang=en returns an image document's bytes (image/jpeg, image/png, image/gif or image/webp, X-Content-Type-Options: nosniff); 404 when the key holds no image.

What is extracted, what is skipped, and how images come back with search results (includeImages, imageHits, queryImage): SEARCH.

Document keys are case-insensitive #

A document's identity is built by lowercasing (ASCII letters of) the collection, key and language, so README.md, readme.md and ReadMe.md are one document. This is deliberate and suits URL-shaped keys, but it has consequences worth stating plainly, because none of them announce themselves:

  • Writing two spellings leaves one document holding whichever content arrived last. The earlier content is gone.
  • /v1/ingest reports this in a keyCollisions array when a batch contains keys differing only in case. The write still happens — refusing a 200 000 document import over a spelling would be worse — but it is no longer silent.
  • Ingesting a source repository is where this bites: Makefile and makefile, README and readme, Dockerfile and dockerfile are distinct files on a case-sensitive filesystem and one document here.

The key index follows the same rule as the identifier: the key and language are stored with ASCII letters in lower case. A document written as README.md is found as readme.md, ReadMe.MD or any other spelling, and it has one index entry however many spellings were written. Only ASCII letters fold: Ż and ż stay distinct, in the identifier as in the index. Collection names are case-sensitive — Blog and blog are two collections.

A database written by an earlier release stored the key as written; it is migrated when v2.18.9 first opens it (see STORAGE-LAYOUT).

Format Conversion:

Format Extension Conversion
Markdown .md Stored as-is, frontmatter extracted
Plain text .txt Stored as-is, frontmatter extracted
HTML .html, .htm Converted to Markdown (headings, links, lists, bold/italic preserved); head, scripts and styles dropped, all entities decoded
PDF .pdf Text of the content streams, FlateDecode inflated. A scan without a text layer is stored with conversionConfidence 0 and a warning naming the pages without text — the server does no OCR
DOCX .docx Text extracted with headings and list structure preserved
ODT .odt OpenDocument text extracted with headings preserved
RTF .rtf Rich Text Format — text extracted, formatting stripped
XLSX .xlsx Every sheet a ## Sheet section holding a table; dates (by the cell's number format) as ISO 8601, not serial numbers; shared and inline strings, booleans; formulas give their cached value
ODS .ods As XLSX: every table a section; date and time cells as ISO 8601; repeated rows and columns expanded up to 1000
CSV, TSV .csv, .tsv One table; the CSV separator (, ; tab |) detected from the first lines, a UTF-8 BOM dropped
PPTX .pptx One ## Slide N: Title section per slide in presentation order, body paragraphs, then <strong>Notes:</strong> with the speaker notes; slide numbers, dates and footers left out
ODP .odp As PPTX: one section per page, title frame as the title, presentation:notes as notes
EPUB .epub Chapters in spine order (the book's reading order), each through the HTML converter; the book title as the heading
EML .eml Headers to meta (from, to, date as RFC 3339, subject, messageId, attachments); the plain-text body, or the HTML body through the HTML converter (nothing executed); every attachment the server can convert stored as its own document KEY/attachments/NAME with meta.parent = KEY
MBOX .mbox The mailbox document lists its messages; each message is stored as KEY/message-N (as EML, with its own attachments below it)
LaTeX .tex, .latex Converted to Markdown (sections, formatting, environments, math preserved)
YAML .yaml, .yml Wrapped in code block for structured data
Log .log Wrapped in code block
LEX .lex Wrapped in code block

The format is decided by content where it has a signature — %PDF, {\rtf, a zip holding word/document.xml, xl/workbook.xml or ppt/presentation.xml, or an OpenDocument/EPUB mimetype — and by extension otherwise, so a PDF named .txt is converted as a PDF. Binary content that no converter recognises is refused (binary content that is no format the server converts) rather than stored as text. Every converter is pure Go; none adds a dependency.

Conversion confidence: every converted document carries meta.conversionConfidence, a number from 0.00 to 1.00, and meta.conversionWarnings saying what lowered it. It is a heuristic, computed from the converted text and the file — no model, no OCR:

Signal Effect
No letter or digit extracted from a non-empty file 0
PDF pages without text × pages with text / pages (a scan scores 0)
Replacement (U+FFFD) and non-printable characters × (1 − 4 × their share); warned above 1%
Text under 0.5% of the file size (zip and PDF formats) × between 0.5 and 1 — pictures hold the rest
Empty sheets × (1 − 0.5 × empty sheets / sheets)

Find the documents worth a second look with the metadata filter — "filter": {"conversionConfidence": {"lt": 0.5}} compares numerically — and the search advisor (/v1/search-advisor) reports lowConfidenceDocuments and lowConfidenceRatio with a warning when there are any. Markdown and text are not converted and carry no score.

Auto-injected Metadata:

  • upload_format: Original file format (e.g. pdf, html, docx)
  • upload_filename: Original filename
  • upload_converted: "true" if file was converted from non-markdown format
  • conversionConfidence, conversionWarnings: see Conversion confidence above
  • from, to, date, subject, messageId, attachments (email); parent and filename on an attachment's document

A converted file's response also carries conversionConfidence and conversionWarnings, and parts: the further documents it held (a mailbox's messages, an email's attachments), each an upload result of its own.

Single File Response:

{
  "key": "report-2026-q1",
  "format": "pdf",
  "converted": true,
  "document": {
    "id": "doc|docs|report-2026-q1",
    "key": "report-2026-q1",
    "lang": "en_US",
    "meta": {
      "upload_format": ["pdf"],
      "upload_filename": ["report-2026-q1.pdf"],
      "upload_converted": ["true"]
    },
    "contentMd": "# Q1 2026 Report\n\nExtracted text content...",
    "addedAt": 1710000000,
    "updatedAt": 1710000000
  }
}

Batch Response (multiple files):

{
  "added": 3,
  "updated": 0,
  "failed": 0,
  "errors": [],
  "results": [
    {"key": "doc1", "format": "pdf", "converted": true, "document": {...}},
    {"key": "doc2", "format": "html", "converted": true, "document": {...}},
    {"key": "doc3", "format": "txt", "converted": false, "document": {...}}
  ]
}

cURL Examples:

# Single file upload
curl -X POST http://localhost:11023/v1/upload \
  -F "file=@report.pdf" \
  -F "collection=docs" \
  -F "lang=en_US"

# With custom key and metadata
curl -X POST http://localhost:11023/v1/upload \
  -F "file=@manual.docx" \
  -F "collection=docs" \
  -F "key=user-manual" \
  -F "lang=en_US" \
  -F 'meta={"category":["documentation"],"type":["manual"]}'

# Batch upload
curl -X POST http://localhost:11023/v1/upload \
  -F "files[]=@doc1.pdf" \
  -F "files[]=@doc2.html" \
  -F "files[]=@doc3.txt" \
  -F "collection=docs" \
  -F "lang=en_US"

# With custom size limit (50MB)
curl -X POST http://localhost:11023/v1/upload \
  -F "file=@large-manual.pdf" \
  -F "collection=docs" \
  -F "lang=en_US" \
  -F "maxSize=52428800"

MCP Tool: upload_file — accepts base64-encoded file content with filename for format detection, and text_only. ingest_documents takes format and content_base64 per document and text_only in its options.


POST /v1/get #

Retrieve a specific document by collection, key, and language.

Request Body:

{
  "collection": "blog",
  "key": "homepage",
  "lang": "en_GB",
  "env": {
    "year": "2024",
    "siteName": "My Blog"
  }
}

Response:

{
  "id": "blog|homepage|en_gb",
  "key": "homepage",
  "lang": "en_GB",
  "meta": {
    "category": ["blog"]
  },
  "contentMd": "# Welcome to My Blog in 2024",
  "addedAt": 1699296000,
  "updatedAt": 1699296000
}

Features:

  • Retrieves the latest version of a document
  • Supports templating via env parameter
  • Template variables in content are replaced: %%varName%% → value from env

Template Example:

If your content contains:

# Welcome to %%siteName%% in %%year%%

And you provide:

{
  "env": {
    "year": "2024",
    "siteName": "My Blog"
  }
}

The response will contain:

# Welcome to My Blog in 2024

cURL Example:

curl -X POST http://localhost:11023/v1/get \
  -H 'Content-Type: application/json' \
  -d '{
    "collection": "blog",
    "key": "homepage",
    "lang": "en_GB",
    "env": {"year": "2024"}
  }'

POST /v1/search #

Search for documents in a collection with optional metadata filtering and sorting.

Request Body:

{
  "collection": "blog",
  "filterMeta": {
    "category": ["blog", "tutorial"],
    "author": ["John Doe"]
  },
  "sort": "updatedAt",
  "asc": false,
  "limit": 10,
  "offset": 0
}

Parameters:

  • collection (required): Collection name
  • filterMeta (optional): Metadata filters (AND between keys, OR between values)
  • sort (optional): Sort field - addedAt, updatedAt, or key
  • asc (optional): Sort order - true for ascending, false for descending
  • limit (optional): Maximum number of results (default: 50), never more than MDDB_SEARCH_MAX_LIMIT (default 1000). A larger limit is lowered to the cap and the response carries the headers X-Limit-Capped: true and X-Limit: <the limit used> — the body is a bare array, with no object to hold the fields every other search returns
  • offset (optional): Number of results to skip (default: 0)

Response:

[
  {
    "id": "blog|post1|en_gb",
    "key": "post1",
    "lang": "en_GB",
    "meta": {
      "category": ["blog"],
      "author": ["John Doe"]
    },
    "contentMd": "# Post 1",
    "addedAt": 1699296000,
    "updatedAt": 1699296100,
    "revision": "53f8149d734342a9"
  },
  {
    "id": "blog|post2|en_gb",
    "key": "post2",
    "lang": "en_GB",
    "meta": {
      "category": ["tutorial"],
      "author": ["John Doe"]
    },
    "contentMd": "# Post 2",
    "addedAt": 1699295000,
    "updatedAt": 1699296200,
    "revision": "9a0c6e1f2b3d4c5e"
  }
]

Each result carries revision (v2.19.6), the same value POST /v1/get returns for that document, so a list can be edited with conditional writes without reading each document first. gRPC Search, MCP search_documents and GraphQL search carry it too. Full-text, vector and hybrid hits do not.

Filtering Logic:

  • Multiple values for the same key are combined with OR
  • Multiple keys are combined with AND
  • Example: {"category": ["blog", "tutorial"], "author": ["John"]} means:
    • (category = "blog" OR category = "tutorial") AND (author = "John")

cURL Example:

curl -X POST http://localhost:11023/v1/search \
  -H 'Content-Type: application/json' \
  -d '{
    "collection": "blog",
    "filterMeta": {"category": ["blog"]},
    "sort": "addedAt",
    "asc": true,
    "limit": 10
  }'

POST /v1/vector-search #

Perform semantic (vector) search using natural language queries. Documents are automatically embedded when added (if an embedding provider is configured). The search finds documents by meaning, not just exact metadata matches.

Request Body:

{
  "collection": "docs",
  "query": "how to authenticate users",
  "topK": 5,
  "threshold": 0.3,
  "filterMeta": {
    "category": ["tutorial"]
  },
  "includeContent": true
}

Parameters:

  • collection (required): Collection name
  • query (required*): Natural language search query (will be embedded server-side)
  • queryVector (optional*): Pre-computed embedding vector (use instead of query)
  • topK (optional): Maximum results to return (default: 5)
  • threshold (optional): Minimum similarity score 0.0-1.0 (default: 0.0)
  • filterMeta (optional): Metadata pre-filter (same logic as /v1/search)
  • includeContent (optional): Include contentMd in results (default: false)
  • algorithm (optional): flat (default), auto, hnsw, ivf, pq, opq, sq, sq4, bq. With auto the query planner chooses per query; the collection profile's retrieval.vectorAlgorithm applies when the request names none (SEARCH)
  • explain (optional): Add plan to the response — the index that answered, prefilter, strategy (v2.19.8: prefilter, graph+filter, ivf or scan+filter for a filtered search), candidates, iterativeScan and the reasons
  • includeImages (optional): Attach each hit's image documents as images (alt text, caption, page, url); with a provider that embeds images also return imageHits, the images whose picture matches the query. Also on /v1/fts, /v1/hybrid-search and /v1/cross-search (SEARCH)
  • queryImage (optional*): Search by an image instead of text — base64, a data URI or an http(s) URL (SSRF-guarded). Needs a provider that embeds images, else 400; the results are image documents, algorithm: "image"
  • latencyTargetMs (optional): Latency goal for auto, 0–60000; 10 or less favours a quantized index on 10,000+ vectors
  • positive, negative (optional): Relevance feedback — results that were right or wrong, each a document key or ID (string) or a vector (array of numbers); at most 50 per side (SEARCH)
  • feedbackMode (optional): query (default: Rocchio on the query vector) or rescore (re-rank the candidates by similarity to the examples)
  • feedbackWeight (optional): Rescore weight, 0–10 (default 0.5)
  • rocchio (optional): {alpha, beta, gamma} for query mode (default 1, 0.75, 0.25)
  • queryDecomposition (optional): off (default) or auto — a query of several clauses ("set up a replica and take a backup") is also searched clause by clause, at most 4, and each document keeps its best score; with explain, plan.decomposition gives the parts (SEARCH)

* Either query or queryVector is required.

Response:

{
  "results": [
    {
      "document": {
        "id": "docs|auth-guide|en_us",
        "key": "auth-guide",
        "lang": "en_US",
        "meta": {"category": ["tutorial"]},
        "contentMd": "# Authentication Guide\n...",
        "addedAt": 1709136000,
        "updatedAt": 1709136000
      },
      "score": 0.89,
      "rank": 1
    },
    {
      "document": {
        "id": "docs|login-flow|en_us",
        "key": "login-flow",
        "lang": "en_US",
        "meta": {"category": ["tutorial"]},
        "contentMd": "# Login Flow\n...",
        "addedAt": 1709135000,
        "updatedAt": 1709135000
      },
      "score": 0.74,
      "rank": 2
    }
  ],
  "total": 2,
  "model": "text-embedding-3-small",
  "dimensions": 1536
}

Response Fields:

  • results: Array of matched documents with similarity scores
    • document: Full document object
    • score: Cosine similarity score (0.0-1.0, higher = more similar)
    • rank: Position in results (1-based)
  • total: Number of results returned
  • model: Embedding model used
  • dimensions: Vector dimensionality
  • algorithm: The index that answered
  • plan (with explain): {algorithm, prefilter, strategy, candidates, iterativeScan, reasons}

How It Works:

  1. When a document is added via /v1/add, its content is automatically embedded in the background
  2. The query text is embedded using the same model
  3. Cosine similarity is computed between the query vector and all document vectors
  4. Results are ranked by similarity score
  5. If filterMeta is provided, only documents matching the metadata filter are searched (hybrid search)

cURL Example:

curl -X POST http://localhost:11023/v1/vector-search \
  -H 'Content-Type: application/json' \
  -d '{
    "collection": "docs",
    "query": "how to authenticate users",
    "topK": 5,
    "includeContent": true
  }'

POST /v1/vector-reindex #

Re-embed all documents in a collection. Useful after changing the embedding provider/model, or for initial indexing of existing documents.

Knowing when it is needed. MDDB records the model and the embedding variant each collection's vectors were produced with. The variant covers what can change while the model name stays the same, such as a provider beginning to send a task prefix or an input_type. At startup MDDB compares the record against what the configured provider produces now and logs any collection that differs:

embedding provenance changed  detail="1 collection(s) were embedded differently
than nomic-embed-text produces now and should be reindexed for search quality: docs"

Nothing is rewritten automatically. The vectors still work; they are simply no longer in the same space as a query embedded today, which shows up as quietly worse ranking rather than as an error. Reindexing is your call.

Request Body:

{
  "collection": "docs",
  "force": false
}

Parameters:

  • collection (required): Collection name
  • force (optional): If true, re-embed all documents regardless of content changes. If false, skip documents whose content hasn't changed (default: false)
  • async (optional): If true, start the reindex as a background job and answer at once (see below)

Long reindexes. Re-embedding tens of thousands of documents takes as long as the provider needs, often over an hour on a CPU. The synchronous call keeps working: its write deadline is lifted, as for add-batch and backups, so the result is delivered however long it takes, as long as the client waits. With "async": true the call answers 202 with a job instead, and Location points at it:

curl -X POST "$MDDB/v1/vector-reindex" -d '{"collection":"docs","force":true,"async":true}'
# {"jobId":"reindex_3f2a...","collection":"docs","status":"running",...}
curl "$MDDB/v1/vector-reindex/jobs/reindex_3f2a..."
# {"status":"running","done":12000,"percent":41.3,"etaSeconds":2280,"result":{"total":29040,"embedded":11800,...}}
curl "$MDDB/v1/vector-reindex/jobs"   # recent jobs, newest first

status ends as completed or failed (with error), and result then holds the final counts and errors. A second reindex of a collection while one runs answers 409 with the running job. Jobs are kept in memory, the last 50; a restart forgets them, but the vectors written stay.

Response:

{
  "embedded": 42,
  "skipped": 8,
  "failed": 0,
  "errors": []
}

cURL Example:

curl -X POST http://localhost:11023/v1/vector-reindex \
  -H 'Content-Type: application/json' \
  -d '{"collection": "docs", "force": false}'

GET /v1/vector-stats #

Get embedding/vector search statistics.

Response:

{
  "enabled": true,
  "provider": "text-embedding-3-small",
  "model": "text-embedding-3-small",
  "dimensions": 1536,
  "index_ready": true,
  "collections": {
    "docs": {
      "total_documents": 50,
      "embedded_documents": 48
    },
    "blog": {
      "total_documents": 120,
      "embedded_documents": 120
    }
  },
  "queue": {
    "size": 1000,
    "depth": 2,
    "dropped": 0,
    "wait": "5s"
  }
}

queue says why embedded_documents might be below total_documents, which the two counts alone cannot:

Field Meaning
size Queue capacity (MDDB_EMBEDDING_QUEUE_SIZE)
depth Jobs waiting right now — above zero means embedding is still running
dropped Documents stored without a vector since startup, because the queue was full and the write gave up waiting. Repair with POST /v1/vector-reindex
wait How long a write waits for room before dropping (MDDB_EMBEDDING_QUEUE_WAIT)

While the index loads at startup, indexProgress says how far it is: collectionsDone/collectionsTotal, vectorsDone/vectorsTotal, percent, etaSeconds (-1 until it can be estimated), the collection being loaded (current) and readyCollections, the ones that already answer. /health carries the same block as vectorIndex.progress. A vector search on a collection that is not loaded yet answers 503 with Retry-After, the collection and the progress; other collections are searched normally.

A collection answers on flat, HNSW and BQ before IVF, PQ, OPQ, SQ and SQ4 have trained on it; they train in the background afterwards (GO-047). While they do, indexTraining lists current, the collection being trained, pending, every collection not trained yet in training order, and indexes, the ones that refuse those collections. Such a refusal is a 503 with Retry-After and "training": true. See SEARCH.

Since v2.19.8 the top-level indexPersistence gives the checkpoint settings in force (enabled, formatVersion, checkpointIntervalSeconds, checkpointChanges), and each collection has indexPersistence — where its indexes came from at the last load (source: disk, rebuilt or partial; indexes, per index; reason; loadMs; caughtUp, vectors stored after the checkpoint) and its last checkpoint write (checkpoint: at, bytes, durationMs, indexes, error) — and hnswTombstones, the removed or overwritten nodes POST /v1/vector-compact would clear. See SEARCH.

"indexPersistence": {
  "source": "disk",
  "indexes": {"hnsw": "disk", "ivf": "disk", "opq": "disk", "pq": "disk", "sq": "disk", "sq4": "disk"},
  "loadMs": 1840,
  "caughtUp": 0,
  "checkpoint": {"at": "2026-11-16T08:00:00Z", "bytes": 57784097, "durationMs": 947,
                 "indexes": ["hnsw", "ivf", "opq", "pq", "sq", "sq4"]}
}

cURL Example:

curl http://localhost:11023/v1/vector-stats

POST /v1/vector-compact #

Rebuild a collection's HNSW graph without its tombstones (v2.19.8). A removed or overwritten document stays in the graph as a node searches skip until half of the graph is such nodes; this rebuilds it now. The new graph is built beside the one in use: searches and writes go on, and what was written meanwhile is applied when it takes over.

Permission: with auth on, write on collection.

Request body: {"collection": "docs"}

Response 200:

{"collection": "docs", "vectors": 199870, "tombstonesBefore": 130, "tombstonesAfter": 0, "elapsedMs": 61234}

tombstonesAfter is above zero only when documents were removed or overwritten while the graph was rebuilt. 404 when the collection has no HNSW graph, 400 without collection, 405 for any method but POST.

curl -X POST http://localhost:11023/v1/vector-compact -d '{"collection":"docs"}'

POST /v1/vector-projection #

Project a collection's embeddings onto two dimensions with PCA, computed on the server, to show cluster structure and outliers (the panel's vector map). The sample is deterministic: the index keys are sorted and an evenly spaced subset is taken, so the same collection gives the same picture.

Permission: with auth on, read on collection.

Request body:

Field Type Meaning
collection string Required
sample int Points to project; default 1000, at most 2000
query string Optional: embedded with the server's provider and projected as one more point
queryVector float[] Optional: a vector to project instead of query; ignored unless its length matches the collection's
curl -X POST http://localhost:11023/v1/vector-projection \
  -H "Content-Type: application/json" \
  -d '{"collection": "docs", "sample": 500, "query": "how to reset a password"}'

Response:

{
  "points": [
    {"id": "a1b2c3#0", "key": "guide/reset", "docId": "a1b2c3", "chunkIndex": 0, "x": 0.41, "y": -0.12}
  ],
  "query": {"id": "query", "key": "", "docId": "", "chunkIndex": 0, "x": 0.38, "y": -0.09},
  "total": 5210,
  "sampled": 500,
  "dimensions": 1536
}

id is the vector's index key: a document ID, or docID#N for chunk N. total counts the collection's vectors, sampled the points returned. Vectors whose length differs from the first one are skipped. A collection without vectors answers {"points": [], ...}; a missing collection is a 400.


Vector Search Configuration #

Embedding Providers

Provider MDDB_EMBEDDING_PROVIDER Default Model Default Dimensions API Key Required
OpenAI openai text-embedding-3-small 1536 Yes
Voyage AI (Anthropic) voyage voyage-3 1024 Yes
Ollama (local) ollama nomic-embed-text 768 No
Lexical (no model; matches spelling, not meaning — details) lexical lexical-ngram-v1 512 (256–2048) No
Disabled none or empty - - -

Provider-Specific Configuration

OpenAI:

MDDB_EMBEDDING_PROVIDER=openai
MDDB_EMBEDDING_API_KEY=sk-...
MDDB_EMBEDDING_API_URL=https://api.openai.com/v1    # default
MDDB_EMBEDDING_MODEL=text-embedding-3-small          # default
MDDB_EMBEDDING_DIMENSIONS=1536                        # default

Voyage AI (Anthropic):

MDDB_EMBEDDING_PROVIDER=voyage
MDDB_EMBEDDING_API_KEY=pa-...
MDDB_EMBEDDING_API_URL=https://api.voyageai.com/v1   # default
MDDB_EMBEDDING_MODEL=voyage-3                         # default
MDDB_EMBEDDING_DIMENSIONS=1024                        # default

Ollama (local, no API key needed):

MDDB_EMBEDDING_PROVIDER=ollama
MDDB_EMBEDDING_API_URL=http://localhost:11434          # default
MDDB_EMBEDDING_MODEL=nomic-embed-text                  # default
MDDB_EMBEDDING_DIMENSIONS=768                          # default

Performance Benchmarks (Apple M2)

Documents Dimensions Search Latency Throughput
1,000 768 ~0.9 ms ~1,064 qps
1,000 1,536 ~1.8 ms ~544 qps
5,000 768 ~4.8 ms ~210 qps
10,000 768 ~9.7 ms ~104 qps
10,000 1,536 ~19 ms ~52 qps
50,000 768 ~50 ms ~20 qps
50,000 1,536 ~96 ms ~10 qps

Metadata pre-filtering significantly reduces search time (e.g., filtering to 10% of 10K docs: ~1.1 ms vs ~9.7 ms).


POST /v1/fts #

Perform full-text search across document content. Supports multiple search modes: simple, boolean, phrase, wildcard, proximity, and range filtering. Uses TF-IDF, BM25, BM25F, or PMISparse scoring with optional stemming, synonyms, and typo tolerance.

Result limit. limit (default 50) is never above MDDB_SEARCH_MAX_LIMIT (default 1000) or the collection's retrieval.maxTopK. A request above the cap gets the cap, and the response adds "limit": <the limit used>, "limitCapped": true; under the cap neither field appears. facetMaxValues is bounded by the same cap (0 means the cap), maxHighlights by 20 and fragmentSize by 1000. The same holds for vector, hybrid, cross-collection, autocomplete, code symbol and geo search — see SEARCH.

Request Body:

{
  "collection": "blog",
  "query": "markdown database tutorial",
  "limit": 10,
  "algorithm": "bm25f",
  "fuzzy": 1,
  "mode": "auto",
  "disableStem": false,
  "disableSynonyms": false,
  "fieldWeights": {
    "content": 1.0,
    "meta.title": 3.0,
    "meta.tags": 2.0
  },
  "rangeMeta": [
    {"field": "addedAt", "gte": "2024-01-01", "lte": "2024-12-31"}
  ]
}

Parameters:

  • collection (required): Collection name
  • query (required): Search query text
  • limit (optional): Maximum results (default: 50)
  • algorithm (optional): "tfidf" (default), "bm25", "bm25f", or "pmisparse" — used for simple mode
  • mode (optional): Search mode — "auto" (default), "simple", "boolean", "phrase", "wildcard", "proximity", "expression" (full query DSL with nested parens and precedence)
  • distance (optional): Proximity distance in words (default: 5) — only used with mode=proximity
  • fuzzy (optional): Typo tolerance — 0 (off, default), 1 (1 edit), 2 (2 edits) — used for simple mode
  • lang (optional): Language code for query tokenization (e.g., "pl", "de", "fr"). Uses language-specific stemmer and stop words. Falls back to server default if omitted (default: "en", configurable via MDDB_FTS_DEFAULT_LANG)
  • disableStem (optional): Disable stemming for this query (default: false)
  • disableSynonyms (optional): Disable synonym expansion for this query (default: false)
  • fieldWeights (optional, BM25F only): Map of field name to weight. Defaults: content=1.0, meta.title=3.0, meta.tags=2.0, meta.category=2.0, meta.description=1.5
  • bm25K1, bm25B (optional, bm25 and bm25f only): BM25 parameters for this query, k1 0–3 and b 0–1. Default: the collection profile's retrieval.bm25K1/bm25B, then 1.2 / 0.75. See SEARCH.
  • filterMeta (optional): Metadata pre-filter — {"key": ["value1", "value2"]}
  • rangeMeta (optional): Array of range filters on metadata or timestamps
  • boost (optional): Per-query score multipliers keyed by "metaKey:metaValue". Positive values boost (5.0 → 5×), negative values demote (-2.0 → ½×). Multiple matching entries combine multiplicatively; floor is 0.001. No reindex required.
  • highlight (optional): When true, each result gains a highlights[] array with snippet fragments around matched terms. Works uniformly across every mode.
  • highlightTag (optional): Wrap tag for matched terms — defaults to "<mark>" which produces <mark>term</mark>. Common alternatives: "<strong>", "**" (for markdown), "[h]". The close tag is derived automatically from the open tag.
  • maxHighlights (optional): Max fragments returned per result (default 3).
  • fragmentSize (optional): Approximate chars per fragment (default 150). Fragments snap to word boundaries so the value is a target, not a hard cap.
  • facetBy (optional): Array of metadata keys. When non-empty the response gains a facets map keyed by the same names with per-value counts (ordered by count desc, value asc) aggregated over the matched documents. Counts reflect the post-filter, post-boost, post-curation result set.
  • facetMaxValues (optional): Cap per-key bucket count. 0 / omitted = unlimited.

Search Modes:

  • simple: Standard full-text search with TF-IDF/BM25/BM25F/PMISparse scoring
  • boolean: Boolean operators — rust AND performance, rust OR golang, NOT java, +required -excluded
  • phrase: Exact phrase matching — "machine learning algorithms" (consecutive terms)
  • wildcard: Pattern matching — prog* (any suffix), te?t (single char)
  • proximity: Terms within N words — "rust systems" with distance: 5
  • auto: Auto-detects mode from query syntax (default)

Range Filter Object:

  • field (required): Metadata key name, or "addedAt" / "updatedAt" for timestamps
  • gte (optional): Greater than or equal (supports unix timestamps, ISO dates, numeric strings)
  • lte (optional): Less than or equal
  • gt (optional): Greater than (strict)
  • lt (optional): Less than (strict)

Response:

{
  "results": [
    {
      "document": {
        "id": "blog|post1|en_gb",
        "key": "post1",
        "lang": "en_GB",
        "meta": {"category": ["tutorial"]},
        "contentMd": "# Markdown Database Tutorial..."
      },
      "score": 2.3456,
      "matchedTerms": ["markdown", "databas", "tutori"]
    }
  ],
  "total": 1,
  "algorithm": "bm25",
  "mode": "simple",
  "lang": "en",
  "stemmingActive": true,
  "synonymsActive": true
}

cURL Examples:

# Simple search
curl -X POST http://localhost:11023/v1/fts \
  -H 'Content-Type: application/json' \
  -d '{"collection":"blog","query":"markdown database","algorithm":"bm25","limit":10}'

# Boolean search
curl -X POST http://localhost:11023/v1/fts \
  -H 'Content-Type: application/json' \
  -d '{"collection":"blog","query":"rust AND performance NOT java","mode":"boolean"}'

# Phrase search
curl -X POST http://localhost:11023/v1/fts \
  -H 'Content-Type: application/json' \
  -d '{"collection":"blog","query":"\"machine learning\"","mode":"phrase"}'

# Wildcard search
curl -X POST http://localhost:11023/v1/fts \
  -H 'Content-Type: application/json' \
  -d '{"collection":"blog","query":"prog*","mode":"wildcard"}'

# Proximity search (terms within 5 words)
curl -X POST http://localhost:11023/v1/fts \
  -H 'Content-Type: application/json' \
  -d '{"collection":"blog","query":"rust systems","mode":"proximity","distance":5}'

# Range filter (price between 10 and 100)
curl -X POST http://localhost:11023/v1/fts \
  -H 'Content-Type: application/json' \
  -d '{"collection":"shop","query":"widget","rangeMeta":[{"field":"price","gte":"10","lte":"100"}]}'

# Multi-language search (Polish)
curl -X POST http://localhost:11023/v1/fts \
  -H 'Content-Type: application/json' \
  -d '{"collection":"articles","query":"programowanie wydajne","lang":"pl","algorithm":"bm25"}'

# Per-query boost: 5× featured, ½× archived
curl -X POST http://localhost:11023/v1/fts \
  -H 'Content-Type: application/json' \
  -d '{"collection":"blog","query":"tutorial","boost":{"tag:featured":5.0,"status:archived":-2.0}}'

# Highlighting with fragments
curl -X POST http://localhost:11023/v1/fts \
  -H 'Content-Type: application/json' \
  -d '{"collection":"blog","query":"markdown database","highlight":true,"maxHighlights":2}'

When highlight: true, each result gains a highlights array:

{
  "results": [
    {
      "document": { "id": "blog|post1|en", "key": "post1", ... },
      "score": 2.34,
      "matchedTerms": ["markdown", "database"],
      "highlights": [
        {
          "fragment": "…using <mark>Markdown</mark> as a lightweight <mark>database</mark> format…",
          "matchedTerms": ["markdown", "database"],
          "startOffset": 312,
          "endOffset": 461
        }
      ]
    }
  ]
}

Missing collection, and a collection the caller may not read.

Case Answer
The collection does not exist, auth off or the caller may read that name (admin, *, or a permission on the name) 200 with "results": [], "total": 0 — the same as a query that matches nothing. There is no 404.
Auth on, the caller has no read on the collection — existing or not 403 {"error":"forbidden"}
Auth on, no credentials 401
collection or query missing 400

Permission is checked before the search, so 403 says nothing about whether the collection exists. /v1/vector-search, /v1/hybrid-search, /v1/cross-search (the source and every target) and /v1/symbol answer 403 the same way.

total is the number of results in this response (len(results), or len(passages) with "format": "passages"), after limit, the server's cap and the context budget. It is not the number of documents that match. That number is matched, returned only with "facetScope": "all". When the cap lowered limit, the response says so with limit and limitCapped; when contextTokenBudget dropped results, with contextTruncated.


POST /v1/fts-reindex #

Reindex all documents in a collection using their stored lang field for language-aware FTS processing. A collection with fts: {enabled: false} has its postings removed instead. Every document is rebuilt from scratch, while a write re-indexes only what it changed (see incremental indexing): run it after changing stop words, stemming or fts.excludeMetaKeys.

Request Body:

{ "collection": "articles" }

cURL Example:

curl -X POST http://localhost:11023/v1/fts-reindex \
  -H 'Content-Type: application/json' -d '{"collection":"articles"}'

Response:

{
  "status": "ok",
  "reindexed": 150,
  "skipped": 2
}

status is ok, partial when some documents failed to index (they count in skipped), or removed for a collection with full-text indexing off. A reindex of a large collection takes minutes; the call lifts the HTTP write deadline for its own response, as add-batch does, so the answer arrives however long it takes, as long as the client waits.


GET /v1/fts-languages #

Returns all supported languages for multi-language FTS.

cURL Example:

curl http://localhost:11023/v1/fts-languages

Response:

{
  "languages": [
    {"code": "ar", "name": "Arabic"},
    {"code": "da", "name": "Danish"},
    {"code": "de", "name": "German"},
    {"code": "en", "name": "English"}
  ],
  "defaultLang": "en"
}

GET /v1/autocomplete #

Return up to topN terms starting with the given prefix, ranked by document frequency. Scans the existing FTS inverted index — no additional indexing is required.

Query Parameters:

  • collection (required): Collection name
  • q (required): Prefix query — lowercased and stripped of non-alphanumerics
  • field (optional): Limit to one indexed field (e.g. title, content, meta.tags); empty means global
  • topN (optional, default 10): Maximum suggestions, never above MDDB_SEARCH_MAX_LIMIT or the collection's retrieval.maxTopK; a capped request's response adds "limit" and "limitCapped": true

cURL Examples:

# Global autocomplete across all indexed content
curl "http://localhost:11023/v1/autocomplete?collection=blog&q=mar&topN=5"

# Title-only autocomplete for type-ahead UI
curl "http://localhost:11023/v1/autocomplete?collection=blog&q=mar&field=meta.title"

Response:

{
  "items": [
    {"term": "market", "field": "", "docCount": 42},
    {"term": "marker", "field": "", "docCount": 17},
    {"term": "marathon", "field": "", "docCount": 3}
  ],
  "total": 3,
  "query": "mar",
  "field": ""
}

Notes:

  • A single call scans at most 10000 index entries so pathological prefixes like a stay fast.
  • Prefix is capped at 32 characters; longer prefixes are truncated silently.
  • Empty q returns an empty result list rather than an error — safer for client-side type-ahead handlers.

POST /v1/synonyms #

Add or update synonyms for a term in a collection.

Request Body:

{
  "collection": "docs",
  "term": "big",
  "synonyms": ["large", "huge", "enormous"]
}

Response:

{
  "status": "ok"
}

cURL Example:

curl -X POST http://localhost:11023/v1/synonyms \
  -H 'Content-Type: application/json' \
  -d '{"collection":"docs","term":"big","synonyms":["large","huge","enormous"]}'

GET /v1/synonyms #

List all synonyms for a collection.

Query Parameters:

  • collection (required): Collection name

Response:

{
  "collection": "docs",
  "synonyms": {
    "big": ["large", "huge", "enormous"],
    "fast": ["quick", "rapid", "swift"]
  }
}

cURL Example:

curl "http://localhost:11023/v1/synonyms?collection=docs"

DELETE /v1/synonyms #

Delete all synonyms for a term in a collection.

Request Body:

{
  "collection": "docs",
  "term": "big"
}

Response:

{
  "status": "ok"
}

cURL Example:

curl -X DELETE http://localhost:11023/v1/synonyms \
  -H 'Content-Type: application/json' \
  -d '{"collection":"docs","term":"big"}'

POST /v1/export #

Export documents from a collection in NDJSON or ZIP format.

Request Body:

{
  "collection": "blog",
  "filterMeta": {
    "category": ["blog"]
  },
  "format": "ndjson"
}

Parameters:

  • collection (required): Collection name
  • filterMeta (optional): Metadata filters (same as search)
  • format (required): Export format - ndjson or zip
  • keys (optional, 2.19.7+): export only these documents, each {"key": "...", "lang": "..."} — in the order listed, each once; a key that names no document is skipped. Combined with filterMeta, only the listed documents that also match are exported. Empty or absent exports the whole collection (or what filterMeta selects), as before. An entry without key or lang is refused with 400 (keys[<index>]: key and lang are required).

Response (NDJSON):

{"id":"blog|post1|en_gb","key":"post1","lang":"en_GB","meta":{"category":["blog"]},"contentMd":"# Post 1","addedAt":1699296000,"updatedAt":1699296100}
{"id":"blog|post2|en_gb","key":"post2","lang":"en_GB","meta":{"category":["blog"]},"contentMd":"# Post 2","addedAt":1699295000,"updatedAt":1699296200}

Response (ZIP): Binary ZIP file containing markdown files named as {key}.{lang}.md

Both answers name the file (2.19.0+): Content-Disposition: attachment; filename="<collection>.ndjson" (or .zip), the collection reduced to letters, digits, - and _ (anything else becomes -; export when none was given). CORS exposes the header (Access-Control-Expose-Headers: X-Total-Count, Content-Disposition), so a browser on another origin can read the name.

cURL Examples:

NDJSON export:

curl -X POST http://localhost:11023/v1/export \
  -H 'Content-Type: application/json' \
  -d '{
    "collection": "blog",
    "filterMeta": {"category": ["blog"]},
    "format": "ndjson"
  }' > export.ndjson

ZIP export:

curl -X POST http://localhost:11023/v1/export \
  -H 'Content-Type: application/json' \
  -d '{
    "collection": "blog",
    "format": "zip"
  }' > export.zip

Selected documents as a ZIP:

curl -X POST http://localhost:11023/v1/export \
  -H 'Content-Type: application/json' \
  -d '{
    "collection": "blog",
    "format": "zip",
    "keys": [{"key": "post1", "lang": "en_GB"}, {"key": "post2", "lang": "en_GB"}]
  }' > selection.zip

GET /v1/backup #

Create a backup of the database file.

Query Parameters:

  • to (optional): Backup file name (default: backup-{timestamp}.db)

Response:

{
  "backup": "backup-1699296000.db"
}

cURL Example:

curl "http://localhost:11023/v1/backup?to=backup-$(date +%s).db"

Notes:

  • Copies the database through a read transaction, so the copy is one consistent state even while writes continue
  • The copy passes bbolt's full integrity check before it is kept. A failure returns 500 and means the live database is damaged — see BACKUP. MDDB_BACKUP_VERIFY=false skips the check
  • Backup is created in the same directory as the database
  • Does not interrupt server operations

POST /v1/restore #

Restore the database from a backup file.

Request Body:

{
  "from": "backup-1699296000.db"
}

Response:

{
  "restored": "backup-1699296000.db"
}

cURL Example:

curl -X POST http://localhost:11023/v1/restore \
  -H 'Content-Type: application/json' \
  -d '{"from": "backup-1699296000.db"}'

⚠️ Warning:

  • This operation replaces the current database
  • The server briefly closes and reopens the database connection
  • All current data will be replaced with the backup

Safety: the backup must pass bbolt's full integrity check, run in a separate process, before the live file is touched — the current database is kept as a snapshot until the swap succeeds, and any failure rolls back — the server never ends up with a closed or destroyed database. A failed restore returns 500 with the previous data still being served. The gRPC Restore RPC follows the same contract and, like this endpoint, resets the binlog so replication followers re-snapshot.


GET /v1/backups #

List the backup files in the server's backup directory (MDDB_BACKUP_DIR), newest first (v2.19.11). Admin on *.

Query Parameters:

  • limit (optional): rows per page, default 100, at most 1000
  • offset (optional): rows to skip, default 0

Response:

{
  "backups": [
    {
      "name": "mddb-20261122T030000Z.db",
      "path": "/data/backups/mddb-20261122T030000Z.db",
      "bytes": 52428800,
      "modifiedAt": "2026-11-22T03:00:04Z",
      "state": "checksummed",
      "collectionFiles": 0
    }
  ],
  "total": 1,
  "limit": 100,
  "offset": 0,
  "note": "Backups in folders inside the backup directory, and backups a scheduled rule stores in object storage, are not listed."
}

Notes:

  • Lists regular .db files in the backup directory itself, never a folder inside it, a symlink, a checksum or temporary file, or the live database. Backups a scheduled rule stores in object storage are not listed.
  • state is checksummed when a <name>.sha256 file lies beside the backup (written by a scheduled run after the integrity check), else unknown. The list never re-checks a file; a restore checks it before installing it.
  • collectionFiles counts the files in <name>.d/ (per-collection layout).
  • See BACKUP.

GET /v1/backups/{name}/download #

Download one backup file listed by GET /v1/backups (v2.19.11). Admin on *.

Response: the file, application/octet-stream, with Content-Length and Content-Disposition: attachment; filename=<name>. Range requests are answered with 206. HEAD answers the headers only.

cURL Example:

curl -OJ "http://localhost:11023/v1/backups/nightly.db/download"

Notes:

  • {name} is a single file name: a path separator, .., an absolute path or a NUL is refused, and the file is opened through the backup directory, so a symlink cannot lead out of it.
  • Every name that is not a listed backup answers 404 {"error":"backup not found"}.
  • In the per-collection layout the download is the main file only.
  • Each download, served or refused, is written to the audit log as backup.download with the user.

POST /v1/truncate #

Truncate revision history and optionally clear cache.

Request Body:

{
  "collection": "blog",
  "keepRevs": 3,
  "dropCache": true
}

Parameters:

  • collection (required): Collection name
  • keepRevs (required): Number of recent revisions to keep per document (0 = delete all history)
  • dropCache (optional): Whether to drop cache (placeholder for future use)

Response:

{
  "status": "truncated"
}

cURL Example:

curl -X POST http://localhost:11023/v1/truncate \
  -H 'Content-Type: application/json' \
  -d '{
    "collection": "blog",
    "keepRevs": 3,
    "dropCache": true
  }'

Use Cases:

  • Reduce database size by removing old revisions
  • Keep only recent history for auditing
  • Clean up after bulk imports

GET /v1/storage #

Where the bytes of the database file are: bytes per top-level bucket, key and value bytes per collection split by bucket and category (content, metadata, fullText, vectors, other), and the free space a compaction would give back.

curl "$MDDB/v1/storage"                     # every collection: reads the whole file
curl "$MDDB/v1/storage?collection=src"      # one collection: reads only its keys
{
  "fileBytes": 2690252800, "pageSize": 4096, "freePages": 812, "freeBytes": 3325952,
  "buckets": {"ftsp": {"inUseBytes": 1003141120, "keys": 9120334}},
  "collections": {
    "src": {"totalBytes": 2410000000,
            "byCategory": {"content": 98000000, "metadata": 41000000, "fullText": 2190000000, "vectors": 81000000},
            "byBucket": {"docs": 98000000, "ftsp": 1003141120}}
  },
  "elapsedMs": 41210
}

In the per-collection layout (STORAGE-LAYOUT) each collection also reports fileBytes, the size of its own file, and the totals cover every file.

The full breakdown reads every key; on a large file that is minutes. It reads in short transactions, so writes are not held up behind it, and a bucket's inUseBytes is the bytes of its keys and values. allocBytes, the pages bbolt allocated to a bucket, is no longer reported: measuring it took one read transaction over the whole bucket. buckets is present only in the full breakdown. Turn full-text indexing off for a collection that does not need it with "fts": {"enabled": false} in its collection config, then POST /v1/fts-reindex to remove its postings.

GET /v1/indexing-status #

Is what was just written searchable yet? Queued embedding and metadata work for one collection, or for the whole server without collection. A write returns once its full text and metadata are indexed; the embedding follows from a background worker, so a semantic search sees the document once pendingEmbeddings reaches 0.

curl "http://localhost:11023/v1/indexing-status?collection=notes"

A collection holding image documents also reports images: documents, embedded (with an image vector), the multimodal model, or a note saying why images are not embedded (RAG-010).

trainingCollections lists the collections whose IVF, PQ, OPQ, SQ and SQ4 indexes are still training after a start or a restore (GO-047). Flat and HNSW already answer for them. The field is absent when no collection is training.

{
  "collection": "notes",
  "pendingEmbeddings": 3,
  "failedEmbeddings": 0,
  "completedEmbeddings": 120,
  "pendingMetadata": 0,
  "progress": 0.975,
  "oldestPendingAt": "2026-10-29T09:12:03Z",
  "provider": "text-embedding-3-small",
  "indexed": false
}

To wait inside a search instead of polling, /v1/vector-search, /v1/hybrid-search and /v1/cross-search take waitForIndex (ms, max 30000) and waitForKeys; the response then carries indexing: {waitedMs, timedOut}. /v1/vector-search also takes readLevel: "indexedPlusPending", which adds still-queued documents that match by text, marked pendingEmbedding. The SSE event collection.indexed fires when a collection's queue drains, and /v1/stats includes the server-wide figures under indexing.

Collection aliases: /v1/aliases #

An alias is a stable name for a collection. Clients use the alias, and moving it to another collection is one atomic step. That is how a collection rebuilt with a new embedding model replaces the old one without any client changing a name.

curl -X PUT http://localhost:11023/v1/aliases/docs -d '{"collection":"docs-v2"}'
curl http://localhost:11023/v1/aliases
curl -X DELETE http://localhost:11023/v1/aliases/docs
  • Where an alias works. REST, gRPC, MCP and GraphQL all accept it wherever they take a collection: in the collection, collections, sourceCollection and targetCollections fields, in a ?collection= query parameter, and in the upload form.
  • One name per request. The alias is resolved once, when the request arrives, so one request runs entirely against one collection. A search running during a move sees the old collection or the new one, never both.
  • Permissions. An alias carries its collection's permissions, because they are checked on the collection it points at. Creating or moving an alias needs write permission on the new target and on the old one. Listing shows only aliases whose collection the caller may read.
  • Rules. An alias cannot take the name of an existing collection, and cannot point at another alias. Deleting an alias leaves its collection. An operation that takes a collection, delete included, acts on the collection the alias points at.
  • Storage and replication. Aliases are kept in the main database, so backups carry them and the binlog replicates them.

mddb-cli reindex-swap <alias> --into <new> does the whole switch. It copies the documents into the new collection, waits until it is indexed, then moves the alias. The old collection is kept, so you can roll back.

Features: /v1/features #

Features (v2.19.0, GO-049) are the server's optional modules, each switched on or off by an administrator. A switched-off module disappears from every surface; its data stays, and switching it back on restores it without a migration. Documents, collections, full-text and vector search, auth and backups are core and cannot be switched off.

Module Default What it covers
chat on /v1/chat/* (scenarios, skills, conversations), the chat RPCs and chat_* tools; mddb-chat refuses join while it is off
chatExternalMcp off chat assistants calling external MCP servers (MCP-005); requires chat
geo on /v1/geo-*, the Geo* RPCs, the geo toolset
temporal on /v1/temporal/*, TemporalQuery, TemporalHot
spell on /v1/spell-suggest, /v1/spell-cleanup, /v1/spell-dictionary, SpellSuggest, SpellCleanup
curation on /v1/curation, the curation rule RPCs and tools
automation on /v1/automation*, /v1/automation-logs, the automation RPCs and toolset
memory on /v1/memory/*, the memory toolset
codeIntel on /v1/code-graph, /v1/symbol, /v1/code-languages, CodeSymbol, the code toolset, GraphQL codeGraph and codeSymbol
eval on /v1/eval, /v1/eval-queries, the eval RPCs, run_eval, add_eval_query
corpus on /v1/corpus*, the corpus pack RPCs and tools
classify on /v1/classify, Classify, classify_document
duplicates on /v1/find-duplicates, FindDuplicates, find_duplicates
images on /v1/image, an image document's bytes
webhooks on /v1/webhooks, /v1/webhooks/delete, RegisterWebhook, ListWebhooks, DeleteWebhook, the webhooks toolset, GraphQL webhooks, registerWebhook, deleteWebhook
schemas on /v1/schema/*, /v1/validate, the schema RPCs and ValidateDocument, the schema toolset, GraphQL schema, schemas, setSchema, deleteSchema, validateDocument
aliases on /v1/aliases, /v1/aliases/{name} (alias management)
crossSearch on /v1/cross-search, CrossSearch, cross_search
searchTuning on /v1/search-advisor, /v1/vector-projection (the panel's Vector Space), SearchAdvisor, search_advisor
ftsTuning on /v1/synonyms, /v1/stopwords, the synonym and stop word RPCs and tools
webSearch off /v1/web-search (v2.19.10, #449)
rerankApi off /v1/rerank (v2.19.10, #450)
extractApi off /v1/extract/process (v2.19.10, #451)
vectorStores off /v1/vector_stores, /v1/vector_stores/{id}/search (v2.19.10, #446)
esCompat off, on with MDDB_ES_COMPAT=true /es, /es/… (the Elasticsearch-compatible subset; module since v2.19.10)
qdrantCompat off, on with MDDB_QDRANT_COMPAT=true /qdrant, /qdrant/… (v2.19.10, #447)
modelTraining off /v1/training/profiles, /v1/training/datasets, /v1/training/datasets/{id}, /v1/training/jobs, /v1/training/jobs/{id} (v2.19.11; Model training)

A server that never touched a switch behaves as before 2.19.0.

What "disabled" means. A REST route of the module answers 404 {"error":"feature disabled","feature":"geo"} (after authentication); an RPC answers FAILED_PRECONDITION feature disabled: geo; its MCP tools are left out of tools/list and a call is refused, also through a custom tool whose action is one of them; a GraphQL field of it fails with the same text. A module whose requirement is off is off too (chat off stops chatExternalMcp), and keeps its own switch for when the requirement returns. Background work a module already runs (automation crons and triggers, temporal event recording, webhook delivery) is not stopped by the switch.

Management off, stored data still applies. The six modules added later in 2.19.0 switch a management surface, never access to data: with webhooks off, registered webhooks are still delivered; with schemas off, a stored schema is still checked on every write (a write that breaks it is still 400), only its management and the stand-alone /v1/validate go; with aliases off, existing aliases still resolve on every surface (REST, gRPC, MCP, GraphQL, /es), they just cannot be listed, created or deleted; with ftsTuning off, stored synonyms and stop words still shape full-text queries. To stop a schema, a webhook or an alias from applying, delete it while its module is on.

Precedence. MDDB_FEATURES_FORCE_OFF=geo,chat (config) beats the switch, which beats the default. A forced module is listed with lockedBy and cannot be switched (409).

GET /v1/features

Any authenticated caller.

curl http://localhost:11023/v1/features
{
  "features": [
    {"name": "chat", "description": "Chat assistants: ...", "enabled": true, "configured": true,
     "default": true, "requires": []},
    {"name": "chatExternalMcp", "description": "...", "enabled": false, "configured": true,
     "default": false, "requires": ["chat"], "blockedBy": ["chat"],
     "updatedAt": "2026-11-11T10:00:00Z", "updatedBy": "admin"},
    {"name": "geo", "description": "...", "enabled": false, "configured": true,
     "default": true, "requires": [], "lockedBy": "MDDB_FEATURES_FORCE_OFF"}
  ],
  "version": 3
}

enabled is whether the module works now; configured is its switch (what an administrator set, or default); blockedBy lists required modules that are off; version grows on every switch, so a consumer polls one number.

PUT /v1/features/{name}

A global administrator, on a writable server.

curl -X PUT http://localhost:11023/v1/features/geo -d '{"enabled": false}'

200 {"feature": {...}, "version": 4}. 400 without a boolean enabled, 403 for a non-administrator, 404 {"error":"unknown feature","feature":"x"}, 409 {"error":"feature locked","feature":"geo","lockedBy":"MDDB_FEATURES_FORCE_OFF"}.

  • Storage and replication. Switches are kept in the main database with their version counter, so backups carry them and the binlog replicates them.
  • Other surfaces. gRPC ListFeatures, SetFeature (GRPC) and the MCP tools feature_list, feature_set (MCP) call the same code. The panel's Features page (PANEL) switches them.

Chat scenarios: /v1/chat/scenarios #

A chat scenario is how one assistant behaves (v2.19.0, #403): its prompt, guardrails, the collections it may search, its style, LLM parameters and limits. Scenarios are stored in MDDB, edited in mddb-panel ("Chat" in the sidebar) and read by mddb-chat, so changing a word of a prompt no longer means editing a TOML file and restarting a service.

Method Path Answer
GET /v1/chat/scenarios {"scenarios":[…],"version":N} — the scenarios the caller may read
GET /v1/chat/scenarios/version {"version":N} — the cheap poll
GET /v1/chat/scenarios/{name} the scenario
PUT /v1/chat/scenarios/{name} the stored scenario; 201 when created, 200 when replaced
DELETE /v1/chat/scenarios/{name} {"deleted":true,"version":N}
GET /v1/chat/scenarios/{name}/prompt {"name","prompt","version","bytes","approxTokens","warning","missingSkills"} — the composed system prompt and its size
GET /v1/chat/scenarios/{name}/access {"scenario","authEnabled","collections","users"} — who can read the scenario (2.19.10, admin on "*")
curl -X PUT http://localhost:11023/v1/chat/scenarios/support -d '{
  "description": "Support desk",
  "enabled": true,
  "operatorPrompt": "You are Ada, the support assistant of Example Ltd. Answer in the user\u0027s language.",
  "guardrails": "No legal or medical advice. Never quote prices.",
  "offTopic": {"mode": "redirect", "redirectTemplate": "I can only help with Example products."},
  "allowedCollections": ["docs", "runbooks"],
  "skills": ["triage"],
  "style": {"emoji": "off", "verbosity": "short", "markdown": true,
            "citationTemplate": "https://example.org/blob/main/"},
  "llm": {"model": "gpt-5-mini", "temperature": 0.2, "maxTokens": 800,
          "extraBody": {"reasoning_effort": "low"}},
  "maxTurns": 12,
  "tokenBudgetPerSession": 50000,
  "rateLimit": {"messagesPerMinute": 20}
}'
curl http://localhost:11023/v1/chat/scenarios/support/prompt
curl http://localhost:11023/v1/chat/scenarios/version

Who can read a scenario (2.19.10, #441). A scenario is offered only to an account that can read every collection in its allowedCollections. GET /v1/chat/scenarios/{name}/access lists every user, by name, with what they can read of those collections (aliases resolved):

{
  "scenario": "support",
  "authEnabled": true,
  "collections": ["docs", "runbooks"],
  "users": [
    {"username": "admin", "admin": true, "full": true,
     "grants": [{"collection": "docs", "via": "admin"}, {"collection": "runbooks", "via": "admin"}]},
    {"username": "bot", "admin": false, "full": false,
     "grants": [{"collection": "docs", "via": "group:readers"}]}
  ]
}

full is true when the user can read every collection, which is always the case for a scenario with none. via names the rule that matched, in the order the server checks them: admin (admin on "*"), user (the user's own grant on the collection), user:* (their grant on "*"), group:<name>, group:<name>:*. When several groups match, the first group by name is reported. A tenant user reads only inside the tenant's namespace, and a disabled user is marked "disabled": true. When authentication is off, authEnabled is false and users is empty. The route needs admin on "*". A caller without it gets 403 whether the scenario exists or not; an admin asking for an unknown scenario gets 404. It returns no password or key hashes.

Field Values Default
name 1–128 characters, no |, / or spaces, not version; taken from the path —
description, operatorPrompt, guardrails text, at most 16384 bytes each empty
enabled boolean false
offTopic.mode refuse, redirect, brief refuse
offTopic.redirectTemplate the reply in redirect mode a built-in sentence
allowedCollections existing collections or aliases, each once none
skills up to 64 skill names, composed in this order none
mcpServers up to 16 external MCP servers: {name, url, enabled, secretRef, allowedTools, timeoutMs, resultMaxChars} none
style.emoji off, sparingly, free off
style.verbosity short, normal, long normal
style.markdown boolean false
style.citationTemplate how a source is cited, e.g. a link template with `` none
llm.model, llm.maxTokens, llm.extraBody model name, token cap, an object sent to the model API as is unset
llm.loopGuard overrides mddb-chat's repetition-loop guard (2.19.2, #413): enabled (boolean), ngram (0–4096), window (0–65536, not shorter than ngram), ratio (0–1), minOutput (0–1000000), unit (chars or words); 0 or empty keeps mddb-chat's [llm.loop_guard] value (chat) unset
llm.temperature 0 to 2; 0 is kept as 0, leaving it out means unset unset
maxTurns, tokenBudgetPerSession, rateLimit.messagesPerMinute 0 or more; 0 means no limit from the scenario 0
logging.enabled boolean: record every turn, anonymous sessions included, for the conversation log (#406) false
logging.retentionDays 0–3650: how long an anonymous session's log is kept; 0 is MDDB_CHAT_RETENTION_DAYS (30) 0
logging.redact boolean: redact e-mails, tokens and card-like numbers before storage (chat) true
createdAt, updatedAt set by the server —
  • Create or replace. PUT stores the whole body: a field left out is reset to its default. Read the scenario first to change one field.
  • Precedence. As with retrieval profiles: an explicit per-request value wins over the scenario, and the scenario wins over MDDB's default.
  • Version counter. One number for the whole store. It grows by one on every create, replace and delete, is stored with the scenarios and keeps growing across restarts. A consumer polls /v1/chat/scenarios/version and reloads the list when the number changes.
  • Composed prompt. /prompt joins, in this order: the operator prompt, the guardrails, the off-topic clause, the scenario's skills in its order (since 2.19.0, under a line saying the guardrails and the scope rule above take precedence), the style clause, then the responsePrompt of each allowed collection that has one (collection config). A skill name with no stored skill is skipped and listed in missingSkills. bytes is the prompt's length, approxTokens is bytes / 4 (a rule of thumb, not a tokenizer) and warning is set past 75% of MDDB_CHAT_PROMPT_MAX_BYTES (default 131072). A PUT whose composed prompt is over that limit is 400. A scenario without skills composes exactly as before. Since 2.19.0 /prompt also returns mcpServers: each external server's active state and, when it is off, the reason; with an active server the prompt ends with a clause framing external tool results as untrusted data.
  • Permissions. Writing needs a global administrator. Reading a scenario needs read permission on every collection it allows; the list leaves out the scenarios the caller may not read, so a tenant sees only scenarios over its own collections. /version needs any valid credential.
  • Errors. 400 for an invalid field or a collection that does not exist, 403 without the permission or on a read-only server, 404 for an unknown name.
  • Storage and replication. Scenarios are kept in the main database, so backups carry them and the binlog replicates them.
  • Other surfaces. gRPC ListChatScenarios, GetChatScenario, PutChatScenario, DeleteChatScenario, GetChatScenarioPrompt (GRPC) and the MCP tools chat_scenario_list, chat_scenario_get, chat_scenario_put, chat_scenario_delete (MCP) call the same code.

Chat skills: /v1/chat/skills #

A chat skill (v2.19.0, #404) is a reusable block of Markdown instructions in the SKILL.md format — front matter with name and description, then the instructions — that scenarios attach by name. A skill is operator-trusted text: it becomes part of a system prompt, so every endpoint, reads included, needs a global administrator.

Method Path Answer
GET /v1/chat/skills {"skills":[…],"version":N} — every skill without content or history; version is the scenarios' counter
GET /v1/chat/skills/{name} the skill with content and history (earlier versions, without contents)
GET /v1/chat/skills/{name}?version=N a kept earlier version, with its content
PUT /v1/chat/skills/{name} the stored skill; 201 when created, 200 for a new version or no change
DELETE /v1/chat/skills/{name} {"deleted":true,"version":N}; 409 with usedBy while a scenario attaches it
GET /v1/chat/skills/{name}/used-by {"name","scenarios":[…]}
POST /v1/chat/skills/import a preview of {"url"} or {"content"}; stores nothing
POST /v1/chat/skills/{name}/update fetch the source again: a preview, stored with {"confirm":true}
# 1. Preview: the server fetches the file and returns the whole text.
curl -X POST http://localhost:11023/v1/chat/skills/import \
  -d '{"url":"https://github.com/blader/humanizer/blob/main/SKILL.md"}'
# {"name":"humanizer","description":"…","content":"…","raw":"---\nname: …",
#  "source":{"url":"…","commit":"3f2c…","fetchedAt":"2026-11-11T10:00:00Z"},
#  "bytes":5123,"sha256":"…","exists":false}

# 2. Save what was read, with its source.
curl -X PUT http://localhost:11023/v1/chat/skills/humanizer \
  -d '{"description":"…","content":"…","source":{"url":"…","commit":"3f2c…","fetchedAt":"2026-11-11T10:00:00Z"}}'

# 3. Later: see what changed upstream, then confirm the text that was shown.
curl -X POST http://localhost:11023/v1/chat/skills/humanizer/update
curl -X POST http://localhost:11023/v1/chat/skills/humanizer/update -d '{"confirm":true,"sha256":"…"}'
Field Values
name 1–128 characters, no |, / or spaces, not version or import; taken from the path
description text, at most 16384 bytes; taken from the front matter when the content is a whole SKILL.md and none is given
content the instructions, 1 to MDDB_CHAT_SKILL_MAX_BYTES (default 32768) bytes of UTF-8; a whole SKILL.md is split into front matter and body
source {url, commit, fetchedAt} for an imported skill: an https URL, the Git commit when the URL is a GitHub one, the fetch time
version set by the server: 1, then one more on every change
history the last 10 earlier versions, newest first: version, description, bytes, source, updatedAt
bytes, usedBy, createdAt, updatedAt set by the server
  • Versions. Each PUT that changes the description, the content or the source stores a new version and keeps the previous one (the last 10), so the panel can show a diff. A PUT that changes nothing stores nothing. Every change bumps the scenarios' version counter (/v1/chat/scenarios/version), so mddb-chat reloads on the same poll.
  • Import. import fetches over https only, through the server's SSRF guard (private and loopback addresses are refused, a redirect may not leave https), capped at the skill limit plus 8 KiB of front matter, 15 s. A GitHub URL (github.com/{owner}/{repo}/blob|raw/{ref}/{path} or raw.githubusercontent.com/…) is pinned: the branch or tag is resolved to a commit through the GitHub API and the file is read at that commit. When the API cannot tell (a rate limit, a private repository), the file is read as named and commit is empty. The answer carries the full text (raw) so an operator reads it before saving; saving is a separate PUT.
  • Update. Only an explicit POST …/update fetches again. Without confirm it is a preview: {skill, preview, changed, saved, version}. With confirm: true a changed text is stored as a new version; pass the preview's sha256 and a source that changed since the preview is refused with 409. A skill without a source cannot be updated (400).
  • Delete. Refused with 409 and {"error","usedBy":[…]} while a scenario attaches the skill.
  • Errors. 400 for an invalid field or fetch, 403 without admin or on a read-only server (for writes), 404 for an unknown name or version.
  • Storage and replication. Skills are kept in the main database next to the scenarios, so backups carry them and the binlog replicates them.
  • Other surfaces. gRPC ListChatSkills, GetChatSkill, PutChatSkill, DeleteChatSkill, ImportChatSkill, UpdateChatSkill, GetChatSkillUsedBy (GRPC) and the MCP tools chat_skill_list, chat_skill_get, chat_skill_put, chat_skill_delete (MCP) call the same code.

External MCP servers: /v1/chat/mcp #

(v2.19.0, MCP-005) A scenario may name external MCP servers whose read-only tools the assistant calls next to its collections: live data (an order's status, a service's health) or knowledge someone else keeps behind their own MCP server. Static knowledge still belongs in a collection, which is faster and ranks and cites by key. The security model is in chat.

Method Path Answer
GET /v1/chat/mcp-secrets {"secrets":[{name, header, set, updatedAt, usedBy}],"encryptionReady":true} — never a value; encryptionReady is false while no MDDB_ENCRYPTION_KEY is loaded (admin)
PUT /v1/chat/mcp-secrets/{name} {"value":"…","header":"X-Api-Key"}; 201 when new, 200 when replaced; the answer has no value; 409 {"error":"…set MDDB_ENCRYPTION_KEY and restart mddbd","requires":"MDDB_ENCRYPTION_KEY"} without an at-rest key (admin)
DELETE /v1/chat/mcp-secrets/{name} {"deleted":true,"version":N}; 409 with usedBy while a scenario names it (admin)
POST /v1/chat/mcp/inspect {"url","secretRef"} → {url, serverName, serverVersion, protocolVersion, tools:[{name, title, description, annotations, allowable, reason}]} (admin)
POST /v1/chat/mcp/call {"scenario","server","tool","arguments","sub"} → {scenario, server, tool, content, isError, truncated, durationMs} (read on the scenario; a forwardIdentity server also needs write on the chat collection)
# A credential: a bearer token, or a header value when header is given.
curl -X PUT http://localhost:11023/v1/chat/mcp-secrets/wiki -d '{"value":"…"}'
# What the server offers (the chatExternalMcp feature must be on).
curl -X POST http://localhost:11023/v1/chat/mcp/inspect \
  -d '{"url":"https://wiki.example.com/mcp","secretRef":"wiki"}'
# Allow its read-only tools in a scenario.
curl -X PUT http://localhost:11023/v1/chat/scenarios/support -d '{"enabled":true,
  "mcpServers":[{"name":"wiki","url":"https://wiki.example.com/mcp","enabled":true,
                 "secretRef":"wiki","allowedTools":["search"]}]}'
mcpServers[] field Values Default
name 1–128 characters, no |, / or spaces, unique in the scenario —
url https only, no user or password in it (MCP Streamable HTTP) —
enabled boolean false
secretRef the name of a stored secret none
allowedTools up to 64 tool names; each must be read-only on the server none
timeoutMs 100 to 60000 8000
resultMaxChars 100 to 100000; a longer result is cut and marked truncated 4000
forwardIdentity (v2.19.2, #414) {"secretRef","header","ttlSeconds"}: send the signed-in user's identity, see The MCP identity token off
forwardIdentity.secretRef a stored secret of at least 32 bytes, never the server's own secretRef —
forwardIdentity.header the header the token is sent in; not Authorization or a header the client sets X-MDDB-Chat-Identity
forwardIdentity.ttlSeconds 10 to 300 120
  • Switches. A tool reaches the model only when every level is on: the chat feature, the scenario's enabled, the chatExternalMcp feature (off by default), the server's enabled, and the tool in allowedTools. /v1/chat/scenarios/{name}/prompt returns each server's state with the first switch that is off as reason.
  • Checked on save. With chatExternalMcp on, a PUT of a scenario connects to each server (initialize, tools/list) and refuses with 400, naming the tool, any allowed tool that is not offered, lacks readOnlyHint: true, or has destructiveHint: true. A server that cannot be reached refuses the save unless it is saved with enabled: false. A secretRef naming no secret is 400. With the feature off nothing is contacted and the servers are stored inactive.
  • Inspect answers 404 {"error":"feature disabled","feature":"chatExternalMcp"} while the feature is off, 404 for an unknown secretRef, 409 for a secretRef stored unsealed, 502 when the server cannot be reached or answers with an error.
  • Call. mddb-chat calls tools through mddbd, which holds the credential and checks every switch again, and checks again that the tool is still read-only in the server's own tools/list. A switch that is off or a tool not allowed is 403; an unknown scenario or server 404. A timeout, a refused connection or the tool's own error is 200 with isError: true and a short content, so the chat turn goes on.
  • Identity (v2.19.2, #414). A server with forwardIdentity answers about the signed-in user's own data. A call to it must carry sub — mddb-chat sends the verified join token's — or it is refused (403, gRPC FAILED_PRECONDITION) before anything is sent; the caller also needs write on the chat collection, as storing a user's conversation does, so a reader of the scenario cannot name another user. Every request of the call (initialize, tools/list, tools/call) carries the server's credential and a fresh identity token. Checking a scenario on save and inspect carry no identity: the host should answer tools/list to the credential alone. A server without forwardIdentity gets no new header, and a sub sent for it is ignored. mddbd logs sub, scenario, server and tool of each forwarded call, never the token, the key or the arguments. The prompt's server state has forwardIdentity: true; mddb-chat offers such a server's tools only to a signed-in session.
  • Transport. https only, through the server's SSRF guard (private and loopback addresses are refused unless MDDB_OUTBOUND_ALLOW_PRIVATE=true; a redirect may not leave https), the session's Mcp-Session-Id sent back, JSON or event-stream answers up to 4 MiB.
  • Secrets are write-only: no API returns a value. They are stored next to the scenarios (backups carry them, the binlog replicates them), and only ever sealed with the at-rest key: without MDDB_ENCRYPTION_KEY a PUT is 409 with requires: "MDDB_ENCRYPTION_KEY" and stores nothing (set the key and restart mddbd), and the listing's encryptionReady is false. A stored value that is not sealed is refused when used (inspect 409, a call isError: true) and listed with set: false; set it again. A secret's value never appears in a log or an error; one quoted back by a server is replaced with [redacted], as is an identity token. A secret named as a credential or as an identity key is in usedBy.
  • Other surfaces. gRPC ListChatMcpSecrets, PutChatMcpSecret, DeleteChatMcpSecret, InspectChatMcpServer, CallChatMcpTool (GRPC) and the MCP tools chat_mcp_secret_list, chat_mcp_secret_put, chat_mcp_secret_delete (MCP) call the same code.

GET /v1/gain #

What retrieval saved its callers over a window of days, for the whole server. It reports searches by type, algorithm and hybrid fusion, and tokens returned. It also reports tokens avoided, meaning whole documents minus the passages or chunks returned instead. Read-only. The definitions are in TELEMETRY.

curl "http://localhost:11023/v1/gain?window=30d"
{
  "windowDays": 30, "from": "2026-09-30", "to": "2026-10-29",
  "totals": {
    "searches": {"vector": 7410, "hybrid": 5822, "fts": 5160},
    "algorithms": {"hnsw": 9120, "bm25": 5160, "flat": 2140},
    "fusion": {"rrf": 2560, "alpha": 3262},
    "tokensReturned": 21700000, "tokensAvoided": 160700000,
    "fragmentHits": 68102, "documentHits": 14922
  },
  "totalSearches": 18392,
  "tokensWithoutRetrieval": 182400000,
  "savedPercent": 88.1
}

window accepts 7d, 30 and so on, up to 365d, and defaults to 30d. daily=true adds a per-day breakdown under daily.

POST /v1/eval #

Measure retrieval on the collection's own questions. An evaluation set is a list of queries, each with the keys of the documents that should answer it and optional grades (0–3) for nDCG. The endpoint runs the set under up to 8 search configurations and returns, per configuration, recall@k, nDCG@k, MRR, p50/p99 latency in milliseconds and the estimated tokens returned. It only reads, so a read-only server runs it.

curl -X POST http://localhost:11023/v1/eval -d '{
  "collection": "docs",
  "k": 10,
  "configs": [
    {"searchType": "fts", "algorithm": "bm25"},
    {"searchType": "hybrid", "strategy": "rrf"},
    {"searchType": "vector"}
  ]
}'
{
  "collection": "docs", "k": 10, "queries": 20,
  "results": [
    {"config": "fts/bm25", "recallAtK": 0.825, "ndcgAtK": 0.739, "mrr": 0.723,
     "p50Ms": 0.9, "p99Ms": 1.9, "tokens": 1580031},
    {"config": "hybrid", "recallAtK": 0.875, "ndcgAtK": 0.783, "mrr": 0.765,
     "p50Ms": 10.7, "p99Ms": 17.3, "tokens": 1790501}
  ]
}
Field Meaning
configs[] searchType (fts, vector, hybrid), algorithm (FTS), vectorAlgorithm, alpha, strategy, retrievalMode, name. Default: fts/bm25, hybrid, vector.
queries Inline queries for this run instead of the stored set — how a set kept in a repository is evaluated. Max 200.
k Cut-off, default 10, max 100.
details Adds perQuery with every query's scores and returned keys.

A configuration that fails (no embedding provider, unknown algorithm) carries error and does not stop the others.

GET / POST / DELETE /v1/eval-queries #

The stored evaluation set of a collection. It lives in the collection config (evalSet) but is changed only here: PUT /v1/collection-config keeps the stored set.

# add (an existing id is replaced)
curl -X POST http://localhost:11023/v1/eval-queries -d '{
  "collection": "docs", "id": "backup",
  "query": "how do I back up and restore the database",
  "expectedKeys": ["BACKUP.md"], "grades": {"BACKUP.md": 3}
}'
# list
curl "http://localhost:11023/v1/eval-queries?collection=docs"
# remove
curl -X DELETE "http://localhost:11023/v1/eval-queries?collection=docs&id=backup"

When a collection has a set, GET /v1/search-advisor runs it and recommends the configuration that scored best, with the run under measured.

GET /v1/stats #

Get server and database statistics.

Request: No body required (GET request)

Response:

{
  "databasePath": "mddb.db",
  "databaseSize": 16384,
  "mode": "wr",
  "collections": [
    {
      "name": "blog",
      "documentCount": 42,
      "revisionCount": 156,
      "metaIndexCount": 84
    }
  ],
  "totalDocuments": 42,
  "totalRevisions": 156,
  "totalMetaIndices": 84,
  "uptime": ""
}

Response Fields:

  • databasePath: Path to the database file
  • databaseSize: Database file size in bytes
  • mode: Access mode (read, write, wr)
  • collections: Array of collection statistics
    • name: Collection name
    • documentCount: Number of documents in collection
    • revisionCount: Number of revisions in collection
    • metaIndexCount: Number of metadata indices in collection
  • totalDocuments: Total documents across all collections
  • totalRevisions: Total revisions across all collections
  • totalMetaIndices: Total metadata indices across all collections
  • statsComputedAt, statsAgeSeconds: when the counts were computed
  • statsPending: true when the first count after a start is still running

How fresh the counts are. Counting walks every document, revision and metadata-index key, which on a database of millions of documents takes minutes; the call used to do that every time and never returned. The counts now come from a snapshot shared with gRPC, MCP and /metrics:

  • nothing written since the snapshot: it is exact and returned at once;
  • written since, on a database whose count takes under a second: counted again before answering, so the numbers are current, as before;
  • written since, on a database whose count is slow: the snapshot is returned at once with its age, and a new count runs in the background at most every MDDB_STATS_TTL seconds (300).

The first call after a start waits up to MDDB_STATS_WAIT seconds (2) and answers statsPending: true if the count is not done. GET /v1/vector-stats takes its document, embedding and chunk counts from the same snapshot, and GET /v1/storage keeps its breakdowns under the same rules; both report statsComputedAt and statsAgeSeconds. databaseSize is always current. For one collection's document count without waiting, use POST /v1/aggregate {"collection": "..."} and read totalDocs.

cURL Example:

curl http://localhost:11023/v1/stats

CLI Example:

mddb-cli stats

Use Cases:

  • Monitor database growth
  • Check collection sizes before operations
  • Verify indexing status
  • Performance monitoring and capacity planning

POST /v1/schema/set #

Set or update the validation schema for a collection. schema is the schema document as a JSON string, not a nested object: an object is a 400. schema/get and schema/list return it the same way. Schema validation is opt-in per collection. See the Schema Validation Guide for full details on supported rules.

Request Body:

{
  "collection": "blog",
  "schema": "{\"required\":[\"category\",\"author\"],\"properties\":{\"category\":{\"type\":\"string\",\"enum\":[\"blog\",\"tutorial\",\"news\"]},\"author\":{\"type\":\"string\"},\"tags\":{\"type\":\"string\",\"minItems\":1,\"maxItems\":5}}}"
}

Response:

{
  "status": "ok",
  "collection": "blog"
}

cURL Example:

curl -X POST http://localhost:11023/v1/schema/set \
  -H 'Content-Type: application/json' \
  -d '{
    "collection": "blog",
    "schema": "{\"required\":[\"category\"],\"properties\":{\"category\":{\"type\":\"string\",\"enum\":[\"blog\",\"tutorial\"]}}}"
  }'

POST /v1/schema/get #

Retrieve the current validation schema for a collection.

Request Body:

{
  "collection": "blog"
}

Response (schema exists):

{
  "collection": "blog",
  "schema": "{\"required\":[\"category\",\"author\"],\"properties\":{\"category\":{\"type\":\"string\",\"enum\":[\"blog\",\"tutorial\",\"news\"]},\"author\":{\"type\":\"string\"},\"tags\":{\"type\":\"string\",\"minItems\":1,\"maxItems\":5}}}",
  "enabled": true
}

Response (no schema):

{
  "collection": "blog",
  "schema": "",
  "enabled": false
}

cURL Example:

curl -X POST http://localhost:11023/v1/schema/get \
  -H 'Content-Type: application/json' \
  -d '{"collection": "blog"}'

POST /v1/schema/delete #

Delete the validation schema for a collection, disabling validation. Existing documents are not affected.

Request Body:

{
  "collection": "blog"
}

Response:

{
  "status": "ok",
  "collection": "blog"
}

cURL Example:

curl -X POST http://localhost:11023/v1/schema/delete \
  -H 'Content-Type: application/json' \
  -d '{"collection": "blog"}'

POST /v1/schema/list #

List all collections that have a validation schema defined.

Request Body: Empty or {}.

Response:

{
  "schemas": [
    {
      "collection": "blog",
      "schema": "{\"required\":[\"category\",\"author\"],\"properties\":{\"category\":{\"type\":\"string\",\"enum\":[\"blog\",\"tutorial\",\"news\"]},\"author\":{\"type\":\"string\"}}}"
    },
    {
      "collection": "products",
      "schema": "{\"required\":[\"price\",\"sku\"],\"properties\":{\"price\":{\"type\":\"number\"},\"sku\":{\"type\":\"string\",\"pattern\":\"^SKU-[0-9]+$\"}}}"
    }
  ]
}

cURL Example:

curl -X POST http://localhost:11023/v1/schema/list \
  -H 'Content-Type: application/json' \
  -d '{}'

POST /v1/validate #

Validate a document's metadata against the collection schema without persisting anything. Useful for dry-run checks.

Request Body:

{
  "collection": "blog",
  "meta": {
    "category": ["blog"],
    "author": ["Jane Doe"],
    "tags": ["golang", "tutorial"]
  }
}

Response (valid):

{
  "valid": true,
  "errors": [],
  "warnings": []
}

Response (invalid):

{
  "valid": false,
  "errors": [
    "schema validation failed: field \"tags\" has 6 values, maximum 5 allowed",
    "field \"status\" value \"pending\" not in allowed values [draft published archived]"
  ],
  "warnings": []
}

cURL Example:

curl -X POST http://localhost:11023/v1/validate \
  -H 'Content-Type: application/json' \
  -d '{
    "collection": "blog",
    "meta": {
      "category": ["blog"],
      "author": ["Jane Doe"]
    }
  }'

POST /v1/auth/login #

Authenticate with username and password to receive a JWT token. The token must be included in the Authorization header for subsequent authenticated requests.

Request Body:

{
  "username": "admin",
  "password": "secret"
}

Response:

{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "expiresAt": 1709481200
}

cURL Example:

curl -X POST http://localhost:11023/v1/auth/login \
  -H 'Content-Type: application/json' \
  -d '{"username":"admin","password":"secret"}'

Error Responses:

  • 401 Unauthorized - Invalid credentials
  • 400 Bad Request - Invalid request format

POST /v1/auth/api-key #

Create a new API key for programmatic access. Requires JWT authentication via Authorization header.

Authentication: JWT token required

Request Body:

{
  "description": "CI/CD pipeline",
  "expiresAt": 0
}

Parameters:

  • description (string, optional): Human-readable label for the API key
  • expiresAt (int64, optional): Unix timestamp when key expires (0 = never expires)

Response:

{
  "key": "mddb_live_abc123def456...",
  "description": "CI/CD pipeline",
  "createdAt": 1709394600,
  "expiresAt": 0
}

cURL Example:

# First, login to get JWT token
TOKEN=$(curl -s -X POST http://localhost:11023/v1/auth/login \
  -H 'Content-Type: application/json' \
  -d '{"username":"admin","password":"secret"}' | jq -r .token)

# Create API key
curl -X POST http://localhost:11023/v1/auth/api-key \
  -H "Authorization: Bearer $TOKEN" \
  -H 'Content-Type: application/json' \
  -d '{"description":"Production deployment","expiresAt":0}'

Important Notes:

  • The full API key is only shown once in the response
  • Save the key securely - it cannot be retrieved again
  • API keys are hashed with SHA256 before storage
  • Use the key in subsequent requests via the X-API-Key header

Error Responses:

  • 401 Unauthorized - Missing or invalid JWT token
  • 400 Bad Request - Invalid request format
  • 500 Internal Server Error - Failed to create API key

GET /v1/auth/api-keys #

List all API keys for the authenticated user. Returns metadata about each key (not the actual key values).

Authentication: JWT token required

Response:

{
  "keys": [
    {
      "keyHash": "abc123def456...",
      "description": "Production deployment",
      "createdAt": 1709394600,
      "expiresAt": 0
    },
    {
      "keyHash": "xyz789ghi012...",
      "description": "Development testing",
      "createdAt": 1709395200,
      "expiresAt": 1740931200
    }
  ]
}

Response Fields:

  • keyHash (string): SHA256 hash of the API key (use this to delete the key)
  • description (string): Key description
  • createdAt (int64): Unix timestamp of creation
  • expiresAt (int64): Unix timestamp of expiry (0 = never expires)

cURL Example:

curl -H "Authorization: Bearer $TOKEN" \
  http://localhost:11023/v1/auth/api-keys

Error Responses:

  • 401 Unauthorized - Missing or invalid JWT token
  • 500 Internal Server Error - Failed to retrieve API keys

DELETE /v1/auth/api-keys/:keyHash #

Delete an API key by its hash. Users can only delete their own API keys.

Authentication: JWT token required

URL Parameters:

  • keyHash (string, required): The SHA256 hash of the API key (from GET /v1/auth/api-keys)

Response:

{
  "status": "deleted"
}

cURL Example:

# Get list of keys to find the keyHash
curl -H "Authorization: Bearer $TOKEN" \
  http://localhost:11023/v1/auth/api-keys

# Delete specific key
curl -X DELETE -H "Authorization: Bearer $TOKEN" \
  http://localhost:11023/v1/auth/api-keys/abc123def456...

Error Responses:

  • 401 Unauthorized - Missing or invalid JWT token
  • 403 Forbidden - Attempting to delete another user's API key
  • 404 Not Found - API key not found
  • 400 Bad Request - Missing keyHash parameter

Using API Keys #

Once you have an API key, use it to authenticate requests instead of JWT tokens:

With HTTP Header:

curl -H "X-API-Key: mddb_live_abc123def456..." \
  http://localhost:11023/v1/search \
  -H 'Content-Type: application/json' \
  -d '{"collection":"blog","filterMeta":{"status":["published"]}}'

With CLI:

mddb-cli --api-key mddb_live_abc123def456... search blog -f "status=published"

API Key vs JWT Token:

  • JWT Tokens: Short-lived (default 24h), obtained via login, ideal for interactive sessions
  • API Keys: Long-lived or permanent, ideal for automation, CI/CD, and third-party integrations

POST /v1/classify #

Zero-shot document classification using embedding similarity. Ranks candidate labels by their semantic similarity to a document or text.

Request Body:

Field Type Required Description
collection string No* Collection name (for doc reference)
key string No* Document key (for doc reference)
lang string No Language code (default: "en")
text string No* Raw text to classify
labels string[] Yes Candidate labels (max 100)
topK int No Return top K labels (0 = all)
multi bool No Return all labels above threshold
threshold float No Minimum similarity score (default: 0.0)

*Provide either text OR collection+key (with optional lang).

Example Request:

curl -X POST http://localhost:11023/v1/classify \
  -d '{
    "text": "Go is a statically typed, compiled language designed at Google",
    "labels": ["programming", "cooking", "sports", "music"]
  }'

Example Response:

{
  "results": [
    {"label": "programming", "score": 0.87},
    {"label": "music", "score": 0.21},
    {"label": "sports", "score": 0.18},
    {"label": "cooking", "score": 0.12}
  ],
  "model": "text-embedding-3-small",
  "dimensions": 1536
}

Notes:

  • Requires an embedding provider to be configured
  • For document references, reuses existing embedding from vector store if available
  • Labels are embedded in a single batch API call for efficiency

PATCH /v1/update #

Partially update a document's metadata and/or content independently without re-sending the entire document.

Request Body:

Field Type Required Description
collection string Yes Collection name
key string Yes Document key
lang string Yes Language code
meta object No New metadata (replaces all). Use {} to clear
contentMd string No New content (replaces existing)
ttl int No New TTL in seconds (0 = remove)
expectedRevision string No Update only if the document is still at this revision; otherwise 409 Conflict

Conditional writes. GET /v1/get, POST /v1/add and this endpoint return the document's revision. Send it back as expectedRevision and the write succeeds only if nobody wrote in between; otherwise the response is 409 Conflict with currentRevision, and nothing is changed. Two agents editing one file cannot silently lose an edit. Without expectedRevision writes are unconditional, as before. POST /v1/add takes expectedRevision too (an expectation on a document that does not exist is a conflict). gRPC UpdateDocument takes expected_revision and answers ABORTED; MCP update_document and add_document take expected_revision; GraphQL updateDocument takes expectedRevision.

Since v2.19.6 POST /v1/search results carry revision as well, and two more conditions use the same 409 body:

  • Create only if absent (#423). POST /v1/add with "ifAbsent": true writes only when the document does not exist. Otherwise the answer is 409 with the existing document's currentRevision and an empty expectedRevision. The check runs in the write's own transaction, so two clients creating one key at once cannot both succeed. gRPC Add takes if_absent (ABORTED), MCP add_document takes if_absent, and GraphQL addDocument takes ifAbsent. It cannot be combined with expectedRevision (400). The Elasticsearch-compatible _create uses the same check.
  • Delete only at a revision (#424). POST /v1/delete with expectedRevision deletes only while the document is at that revision; a missing document is a conflict with an empty currentRevision. gRPC DeleteDocument takes expected_revision (ABORTED), MCP delete_document takes expected_revision, and GraphQL deleteDocument takes expectedRevision.
curl -X PATCH http://localhost:11023/v1/update -d '{"collection":"notes","key":"plan.md","lang":"en",
  "contentMd":"# Plan v2","expectedRevision":"53f8149d734342a9"}'
# 409 {"error":"revision conflict","expectedRevision":"53f8149d734342a9","currentRevision":"9a0c..."}

An update also re-extracts code symbols from new content, and REST, gRPC, MCP and GraphQL updates share one implementation — the MCP one used to skip the metadata index, revision history and full-text reindex.

After every write. Every write path ends in the same after-write step: POST /v1/add, this endpoint, POST /v1/add-batch, ingest, the scheduled sync, gRPC Add, UpdateDocument, AddBatch and UpdateBatch, MCP and GraphQL. It queues the embedding, updates TTL, geo and temporal tracking, re-indexes full text (only what changed), fires the doc.added / doc.updated webhook and SSE event and the automation triggers, and drops cached searches. Before, gRPC UpdateBatch re-indexed full text only, and PATCH /v1/update (and gRPC, MCP and GraphQL updates) sent no SSE event.

Setting contentMd to "" empties the document's content. Its content postings and its vectors are removed, so full-text, vector and hybrid search no longer find it by text it no longer has. Its meta.<key> fields stay searchable unless fts.excludeMetaKeys excludes them. Before, an empty content was never indexed, and the old postings and vectors stayed. Batch updates (gRPC UpdateBatch, MCP) read an empty content_md as "leave it": empty a document with this endpoint, POST /v1/add or a batch add.

Example:

# Update only metadata
curl -X PATCH http://localhost:11023/v1/update \
  -d '{"collection":"blog","key":"p1","lang":"en","meta":{"tag":["go","updated"]}}'

# Update only content
curl -X PATCH http://localhost:11023/v1/update \
  -d '{"collection":"blog","key":"p1","lang":"en","contentMd":"# Updated content"}'

GET /v1/doc-meta #

Get document metadata without content. Lightweight read.

Query Parameters:

Parameter Required Description
collection Yes Collection name
key Yes Document key
lang No Language code (default: "en")

Example:

curl "http://localhost:11023/v1/doc-meta?collection=blog&key=p1&lang=en"

POST /v1/delete #

Delete a document from a collection.

Request Body:

{
  "collection": "blog",
  "key": "homepage",
  "lang": "en",
  "expectedRevision": "53f8149d734342a9"
}

expectedRevision (optional, v2.19.6) deletes the document only while it is still at that revision. Otherwise the answer is 409 Conflict, {"error":"revision conflict","expectedRevision":"…","currentRevision":"…"}, and nothing is deleted. A missing document is a conflict with an empty currentRevision. Without it, a delete is unconditional and a missing document is 404, as before.

Response:

{
  "status": "deleted",
  "collection": "blog",
  "key": "homepage",
  "lang": "en"
}

POST /v1/delete-batch #

Delete multiple documents in a single request.

Request Body:

{
  "collection": "blog",
  "documents": [
    { "key": "post-1", "lang": "en" },
    { "key": "post-2", "lang": "en" }
  ]
}

Response:

{
  "deleted": 2,
  "notFound": 0,
  "not_found": 0,
  "failed": 0,
  "errors": null
}

not_found is deprecated since 2.19.0: it is notFound under its old snake_case spelling, kept so existing callers keep working, and will be removed in a later minor release. Read notFound. The MCP tools delete_batch and update_batch answer the same pair; gRPC's DeleteBatchResponse.not_found is notFound in its JSON mapping already.


POST /v1/documents:deleteWhere, /v1/documents:updateWhere, /v1/documents:setTTLWhere #

Act on every document a metadata filter matches. The alternative is listing keys and sending them back in batches, with a race between the list and the write. All three take POST and the same body.

Permission: with auth on, write on collection; a dryRun needs only read. The SEC-019 gate checks read and the handler raises it to write for a real run.

# first, what would go
curl -X POST "http://localhost:11023/v1/documents:deleteWhere" -d '{
  "collection": "repo", "filter": {"gitCommit": {"not": ["9f2c1e0"]}}, "dryRun": true
}'
# {"matched": 42, "affected": 42, "sample": ["src/old.go", "..."], "dryRun": true}

# merge metadata into every match
curl -X POST "http://localhost:11023/v1/documents:updateWhere" -d '{
  "collection": "repo", "filter": {"branch": {"in": ["main"]}}, "meta": {"status": ["archived"]}
}'

# expire every match in one hour
curl -X POST "http://localhost:11023/v1/documents:setTTLWhere" -d '{
  "collection": "repo", "filter": {"status": {"in": ["archived"]}}, "ttl": 3600
}'
Field Meaning
collection Required
filter, filterMeta The documents to act on. At least one is required: there is no "every document" by filter
limit Documents affected by this call, default 1000, max 10000
cursor nextCursor of the previous call, to continue without repeats
dryRun Report matched, affected and a sample of keys, and change nothing. A read-only server answers it
meta :updateWhere: merged into each document. Its keys replace the document's values for those keys. Content is not changed
ttl :setTTLWhere: seconds from now; 0 removes the expiry

Each document goes through the normal single-document write: revisions, full-text and vector indexes, webhooks and the binlog. There is no shortcut around it. A document that fails, for example on its schema, is listed in errors and the rest continue. The MCP tools are delete_where (destructive), update_where and set_ttl_where. The gRPC calls are DeleteWhere, UpdateWhere and SetTTLWhere.

POST /v1/delete-collection #

Delete all documents in a collection.

Request Body:

{
  "collection": "blog"
}

Response:

{
  "status": "ok",
  "collection": "blog"
}

POST /v1/hybrid-search #

Hybrid search combining full-text (sparse) and vector (dense) results using alpha blending or reciprocal rank fusion (RRF).

Request Body:

{
  "collection": "blog",
  "query": "how to deploy",
  "topK": 10,
  "algorithm": "bm25",
  "vectorAlgorithm": "flat",
  "alpha": 0.5,
  "strategy": "alpha",
  "rrfK": 60,
  "fuzzy": 0,
  "threshold": 0.0,
  "distanceMetric": "cosine",
  "filterMeta": { "category": ["tutorial"] },
  "includeContent": false,
  "disableStem": false,
  "disableSynonyms": false
}
Field Type Default Description
collection string Required. Collection name
query string Required. Search query
topK integer 10 Max results
algorithm string "bm25" FTS algorithm: bm25, bm25f
vectorAlgorithm string "flat" Vector algorithm: flat, auto (the query planner chooses), hnsw, ivf, pq, opq, sq, sq4, bq; the profile's retrieval.vectorAlgorithm applies when unset
explain boolean false Add plan — the vector half's index and why — to the response
latencyTargetMs integer 0 Latency goal for auto, 0–60000
positive, negative array Relevance feedback for the vector half only: document keys/IDs or vectors (SEARCH)
feedbackMode, feedbackWeight, rocchio query, 0.5, 1/0.75/0.25 How the examples are applied
queryDecomposition string "off" auto splits a multi-clause query for the vector half only (SEARCH)
alpha number 0.5 Weight blending (0=FTS only, 1=vector only)
strategy string "alpha" Fusion strategy: alpha or rrf
rrfK integer 60 RRF parameter k
fuzzy integer 0 Typo tolerance: 0, 1, or 2
threshold number 0.0 Min vector similarity 0–1
distanceMetric string "cosine" cosine, dot_product, euclidean
filterMeta object Metadata key-value filter
filter object Operator filter: prefix, contains, gt/gte/lt/lte, not, exists per key (SEARCH)
groupBy object {key, perGroup} — at most perGroup results per metadata value or document (SEARCH)
includeContent boolean false Include full content
disableStem boolean false Disable stemming
disableSynonyms boolean false Disable synonym expansion
boost object Per-query score multiplier keyed by "metaKey:metaValue"
bm25K1, bm25B number profile, then 1.2 / 0.75 BM25 parameters of the full-text half (SEARCH)
geo object Spatial pre-filter: {lat, lng, radiusMeters}
sort string "combined" Result ordering: combined (default, by fused score) or distance (by distanceMeters ascending — requires geo)
facetBy array Metadata keys to aggregate into facets map on the response
facetMaxValues integer 0 Cap per-key bucket count; 0 = unlimited

Response:

{
  "results": [
    {
      "document": { "id": "...", "key": "...", "lang": "...", "meta": {} },
      "combinedScore": 0.85,
      "ftsScore": 0.7,
      "vectorScore": 0.95,
      "matchedTerms": ["deploy"],
      "rank": 1
    }
  ],
  "total": 1,
  "strategy": "alpha",
  "alpha": 0.5,
  "ftsAlgorithm": "bm25",
  "vectorAlgorithm": "flat",
  "distanceMetric": "cosine",
  "searchStats": { "durationMs": 12 }
}

OpenAI-compatible vector stores: /v1/vector_stores #

Two read-only routes in the shape of the OpenAI Vector Stores API (#446). They are the two calls Open WebUI's OpenAI-compatible External Knowledge Source provider makes. A vector store is a collection. Creating, changing and deleting stores or files through this API is not served: documents are written with /v1/add and the other MDDB endpoints. Setup steps are in LLM_CONNECTIONS. Both belong to the vectorStores module, off by default: until it is switched on (System → Features, PUT /v1/features/vectorStores) they answer 404 {"error":"feature disabled","feature":"vectorStores"}.

Authentication works as on the rest of /v1: Authorization: Bearer mddb_live_… (or X-API-Key) or a JWT. Errors use the OpenAI error object, {"error":{"message","type","param","code"}}, with MDDB's status codes. The 401 for a request without credentials comes from the auth middleware, in MDDB's own shape.

GET /v1/vector_stores?limit=20&after=<id> lists the collections the caller may read. Read permission, the tenant namespace and an MCP API key's scope apply per collection, so a user with read on two collections lists those two. Collections that hold documents and collections that only have a configuration are both listed, sorted by name. Aliases are not listed, but the search accepts them as ids. limit is 1–100 (default 20). has_more and last_id page the list, as Open WebUI does.

curl -H "Authorization: Bearer $MDDB_API_KEY" "http://localhost:11023/v1/vector_stores?limit=100"
{
  "object": "list",
  "data": [
    {
      "id": "acme/docs",
      "object": "vector_store",
      "name": "acme/docs",
      "created_at": 0,
      "status": "completed",
      "file_counts": { "in_progress": 0, "completed": 2, "failed": 0, "cancelled": 0, "total": 2 },
      "metadata": { "description": "Operations handbook" }
    }
  ],
  "first_id": "acme/docs",
  "last_id": "acme/docs",
  "has_more": false
}

metadata.description is the collection's configured description. file_counts counts documents. created_at is 0, because MDDB does not record when a collection was created. The answer is 503 (stats_pending) while the server's first statistics walk is still running.

POST /v1/vector_stores/{id}/search searches one collection. {id} is a collection name or an alias. A name containing / (a tenant namespace) is sent escaped, acme%2Fdocs, as Open WebUI sends it. An unescaped / works too.

Field Type Meaning
query string or array of strings Required. Several strings are searched as one query.
max_num_results integer 1 or more. Default 10; values above 50 are lowered to 50.
ranking_options.score_threshold number Drops results scoring below it.
filters, rewrite_query, ranking_options.ranker Accepted and ignored. Use /v1/hybrid-search for metadata filters.

The search runs MDDB's own engines. A collection with embeddings, on a server with an embedding provider, goes through hybrid search (/v1/hybrid-search with its defaults and the collection's profile). Any other collection goes through full-text search (/v1/fts). Each result is a passage: the lines around the document's best match, cut as the passages format cuts them. score is in 0–1. Hybrid scores are already in that range. A full-text score is divided by the top score, so the best hit scores 1.

The caller needs read permission on the collection. Without it the answer is 403 whether or not the collection exists. An unknown collection the caller may read is 404 (vector_store_not_found).

curl -X POST "http://localhost:11023/v1/vector_stores/acme%2Fdocs/search" \
  -H "Authorization: Bearer $MDDB_API_KEY" -H "Content-Type: application/json" \
  -d '{"query":"how does failover work","max_num_results":5}'
{
  "object": "vector_store.search_results.page",
  "search_query": ["how does failover work"],
  "data": [
    {
      "file_id": "acme/docs|replication|en",
      "filename": "replication",
      "score": 1,
      "attributes": {
        "collection": "acme/docs",
        "lang": "en",
        "url": "https://docs.example.org/replication"
      },
      "content": [{ "type": "text", "text": "# Replication\n\nA follower replica copies every write…" }]
    }
  ],
  "has_more": false,
  "next_page": null
}

file_id is the document's id and filename its key. attributes holds the document's metadata (several values of one key are joined with , ) plus collection and lang. url is the metadata's first url value, when there is one. Open WebUI shows filename as the source title and links attributes.url.

Open WebUI first calls GET {endpoint}/vector_store/list, a route of another proxy's API. MDDB does not serve it, and Open WebUI falls back to /v1/vector_stores on the 404.


POST /v1/cross-search #

Vector search across multiple collections using a text query, pre-computed vector, or another document's embedding.

Request Body:

{
  "query": "machine learning basics",
  "targetCollections": ["articles", "tutorials"],
  "topK": 10,
  "threshold": 0.5,
  "algorithm": "flat",
  "distanceMetric": "cosine",
  "includeContent": false
}

Alternative source modes (use one):

  • query (string) — text to embed
  • sourceCollection + sourceDocID — use an existing document's embedding
  • queryVector (array of numbers) — pre-computed vector
Field Type Default Description
targetCollections string[] all Collections to search
topK integer 10 Max results
threshold number 0.0 Min similarity
algorithm string "flat" Vector algorithm; auto plans each target collection and reports "algorithm": "auto"
explain boolean false Add plan to the response; with auto, one plan per target under plan.collections
latencyTargetMs integer 0 Latency goal for auto, 0–60000
positive, negative array Relevance feedback: keys resolve in sourceCollection, then each target; or vectors
feedbackMode, feedbackWeight, rocchio query, 0.5, 1/0.75/0.25 How the examples are applied
distanceMetric string "cosine" Distance metric
filterMeta object Metadata filter
filter object Operator filter applied in every target collection
groupBy object {key, perGroup}; key: "collection" keeps the best per collection
includeContent boolean false Include content

Response:

{
  "results": [
    {
      "collection": "tutorials",
      "document": { "key": "ml-intro", "lang": "en", "meta": {} },
      "score": 0.92,
      "rank": 1
    }
  ],
  "total": 1,
  "targetCollections": ["articles", "tutorials"],
  "algorithm": "flat",
  "distanceMetric": "cosine",
  "searchStats": { "durationMs": 8, "collectionsSearched": 2 }
}

Open WebUI engines: /v1/web-search, /v1/rerank, /v1/extract/process #

Three endpoints in the request and response shapes Open WebUI sends to an external web search engine, reranker and document loader (v2.19.10). Each is a feature module that starts off; switch it on at PUT /v1/features/{name} or on the panel's Features page. Switched off, a route answers 404 {"error":"feature disabled","feature":"<module>"}. Any credential the API accepts works as Authorization: Bearer, an mddb_live_… API key included. The settings on the Open WebUI side are in OPENWEBUI.

Method Path Module Permission Answers
POST /v1/web-search webSearch read, checked per collection in the handler [{"link","title","snippet"}]
POST /v1/rerank rerankApi authenticated (no collection) {"model","results":[{"index","relevance_score"}]}
PUT /v1/extract/process extractApi authenticated (no collection) {"page_content","metadata"} or a list of them

POST /v1/web-search takes {"query": "…", "count": 3} and runs the cross-collection full-text search (?searchType=hybrid for hybrid) over every collection the caller may read, a tenant user's own only, without the server's memory and chat stores. ?collections=docs,kb (or repeated) picks the collections, each of which must be readable (403 otherwise); MDDB_WEBSEARCH_COLLECTIONS narrows the default server-wide. link is the document's url, source_url or link metadata when it is http(s), else /v1/doc-meta?collection=…&key=…&lang=… on the address the request reached; title is meta.title, else the key; snippet is the passage around the query's words (up to 4096 characters).

curl -s -X POST 'http://localhost:11023/v1/web-search?collections=docs' \
  -H 'Authorization: Bearer mddb_live_…' -H 'Content-Type: application/json' \
  -d '{"query":"pump reset","count":3}'

POST /v1/rerank takes {"model", "query", "documents": […], "top_n"} and scores the documents with the server's reranking model (a stored configuration of kind rerank, else MDDB_RERANK_*). model is accepted and does not choose a model: the server runs one, and the answer names it. Every document gets a result, best first; one the model did not score gets a score below all the others. Each document is read up to 2048 characters; more than 200 documents or 2 MiB of text is 400. No model configured is 503; a failing model is 502 with timeout, invalidResponse or error.

PUT /v1/extract/process takes the file's bytes as the body, its type in Content-Type and its URL-quoted name in X-Filename, and converts it with the converters of /v1/upload without storing anything. The answer's page_content is the Markdown; metadata has source, converter, mime, conversionConfidence (a number) and conversionWarnings, every other value a string. A mailbox or an email with attachments answers a list, the file first. Limits are the upload's: 10 MB, ?maxSize= up to 100 MB, under MDDB_MAX_BODY_BYTES; over is 413. An unsupported format is 415, a file that fails to convert 422.

curl -s -X PUT http://localhost:11023/v1/extract/process \
  -H 'Authorization: Bearer mddb_live_…' -H 'Content-Type: application/pdf' \
  -H 'X-Filename: Report%20Q1.pdf' --data-binary @report.pdf

POST /v1/find-duplicates #

Detect exact, similar and near-duplicate documents in a collection using content hashing, vector embeddings and text overlap (MinHash).

Request Body:

{
  "collection": "blog",
  "mode": "both",
  "threshold": 0.9,
  "maxDocs": 5000,
  "distanceMetric": "cosine",
  "includeContent": false
}
Field Type Default Description
collection string Required. Collection name
mode string "both" exact, similar, minhash, or both (both = exact + similar; it leaves out minhash, which reads every document body)
threshold number 0.9 Similarity threshold 0–1 (embedding similarity, or text overlap in minhash mode)
maxDocs integer 5000 Max documents to process
distanceMetric string "cosine" Distance metric
includeContent boolean false Include document content

Response:

{
  "collection": "blog",
  "mode": "both",
  "threshold": 0.9,
  "distanceMetric": "cosine",
  "totalDocuments": 150,
  "totalEmbedded": 148,
  "exactGroups": [
    {
      "groupId": 1,
      "type": "exact",
      "documents": [
        { "docId": "blog|p1|en", "key": "p1", "lang": "en", "contentHash": "abc123" },
        { "docId": "blog|p2|en", "key": "p2", "lang": "en", "contentHash": "abc123" }
      ]
    }
  ],
  "similarGroups": [],
  "exactDuplicates": 2,
  "similarPairs": 0
}

Every document in a group carries key and lang (2.19.0+), so a caller does not have to parse them out of docId.

minhash mode compares the words themselves (word shingles, MinHash signatures) and needs no embedding provider: it finds a page that was forked and lightly edited, which exact misses and similar cannot tell apart from two independent pages on one subject. Its groups come back in minhashGroups (type: "minhash"), with the number of pairs in minhashPairs; totalDocuments is the number of documents scanned:

{
  "collection": "runbooks",
  "mode": "minhash",
  "threshold": 0.7,
  "distanceMetric": "cosine",
  "totalDocuments": 3,
  "totalEmbedded": 0,
  "minhashGroups": [
    {
      "groupId": 1,
      "type": "minhash",
      "documents": [
        { "docId": "runbooks|restart-production|en", "key": "restart-production", "lang": "en", "score": 0.82 },
        { "docId": "runbooks|restart-staging|en", "key": "restart-staging", "lang": "en", "score": 0.82 }
      ]
    }
  ],
  "minhashPairs": 1,
  "exactDuplicates": 0,
  "similarPairs": 0
}

POST /v1/aggregate #

Compute metadata facets and date histograms for a collection. Supports optional metadata pre-filtering.

Request Body:

Field Type Required Description
collection string Yes Collection name
filterMeta object No Metadata pre-filter (same as /v1/search)
facets array No Facet aggregation requests
facets[].field string Yes Metadata key to aggregate (e.g. "category")
facets[].orderBy string No "count" (default, descending) or "value" (alphabetical)
histograms array No Date histogram requests
histograms[].field string Yes "addedAt" or "updatedAt"
histograms[].interval string No "day", "week", "month" (default), "year"
maxFacetSize int No Max values per facet (default: 50)

Example:

curl -X POST http://localhost:11023/v1/aggregate \
  -H 'Content-Type: application/json' \
  -d '{
    "collection": "blog",
    "facets": [
      {"field": "category"},
      {"field": "author", "orderBy": "value"}
    ],
    "histograms": [
      {"field": "addedAt", "interval": "month"}
    ]
  }'

Example with metadata pre-filter:

curl -X POST http://localhost:11023/v1/aggregate \
  -H 'Content-Type: application/json' \
  -d '{
    "collection": "blog",
    "filterMeta": {"status": ["published"]},
    "facets": [{"field": "tags"}]
  }'

Response:

{
  "collection": "blog",
  "totalDocs": 42,
  "facets": {
    "category": [
      {"value": "tutorial", "count": 15},
      {"value": "news", "count": 12},
      {"value": "release", "count": 8}
    ],
    "author": [
      {"value": "Alice", "count": 20},
      {"value": "Bob", "count": 22}
    ]
  },
  "histograms": {
    "addedAt": [
      {"key": "2026-01", "from": 1767225600, "to": 1769904000, "count": 10},
      {"key": "2026-02", "from": 1769904000, "to": 1772323200, "count": 18},
      {"key": "2026-03", "from": 1772323200, "to": 1775001600, "count": 14}
    ]
  },
  "durationMs": 3
}

GET /v1/collection-config #

Get configuration for a specific collection.

Query Parameters:

Parameter Required Description
collection Yes Collection name

Example:

curl "http://localhost:11023/v1/collection-config?collection=blog"

Response:

{
  "collection": "blog",
  "config": {
    "type": "default",
    "description": "Blog posts",
    "icon": "",
    "color": "",
    "customMeta": {}
  },
  "configured": true
}

Also supports PUT to set config and DELETE to remove config for a collection.

Repository (v2.19.11)

repository: {"url": "https://github.com/acme/shop-api", "forge": "", "tokenSecretRef": "forge-token"} is the forge repository the collection is read from: a git or issues sync without its own url reads it, and its token (a stored secret's name, never a value). A PUT that does not name repository keeps the stored one; "repository": {} removes it. 400 for a URL a sync could not read or a secret that does not exist. See AUTOMATIONS.

Quota usage

A collection with a quota also gets usage: what it uses of each limit, next to config.quota.

{
  "collection": "tenant-a",
  "config": { "type": "default", "quota": { "maxDocuments": 5000, "embeddingCallsPerDay": 200 } },
  "configured": true,
  "usage": { "documents": 1234, "bytes": 5242880, "vectors": 3810, "embeddingCalls": 17, "embeddingTokens": 9120 }
}
Field Compare with Meaning
documents maxDocuments Documents the collection holds
bytes maxBytes Stored size of its documents (after compression and encryption)
vectors maxVectors Chunk vectors in the largest of the server's indexes
embeddingCalls embeddingCallsPerDay Embedding provider calls today (UTC)
embeddingTokens embeddingTokensPerDay Estimated tokens (characters / 4) embedded today (UTC)

These are the counts the write gate and the embedding budget check, so a value at or above its limit is the reason a write is refused (507) or an embedding waits. Embedding use is counted only while the collection has an embedding budget, and from zero after a restart. A collection without a quota gets no usage: it is not scanned on a config read. gRPC returns the same numbers in GetCollectionConfigResponse.usage; /metrics keeps the mddb_collection_fullness and mddb_embedding_budget_used gauges.

Credentials are masked on read

A collection config can hold two credentials: storageConfig.secretKey and wordpress.apiKey. Reads — REST, gRPC and MCP alike — return them empty and set a presence flag instead:

{
  "storageConfig": { "bucket": "docs", "accessKey": "AKIA", "secretKeySet": true },
  "wordpress":     { "url": "https://blog.example.com", "apiKeySet": true }
}

Reading a collection's configuration requires read permission on that collection. That is permission to read its documents — not to collect the credentials for the bucket underneath them, which reach every other collection sharing it.

On write, an empty credential keeps the stored one, so the read-modify-write loop a UI performs does not erase it. Send a new value to replace it; remove the whole storageConfig or wordpress block to clear it. secretKeySet and apiKeySet are output-only and ignored on write.

gRPC carries the same fields as REST

CollectionConfigProto used to carry 8 of the 18 fields CollectionConfig holds, so a gRPC client saw a partially configured collection and could not tell that from a collection that really was partially configured. It now carries all of them: storage_backend, storage_config, quantization, disk_only_vectors, encrypted, track_access, track_hot, spell_correct, spell_lang and wordpress.

The booleans in SetCollectionConfigRequest are declared optional, which is load-bearing rather than stylistic: a plain proto3 bool cannot tell "the client did not mention encryption" from "the client wants encryption off". Since the handler merges into the stored config, an unset bool arriving as false would switch encryption off on a collection whose owner only wanted a new icon — after which the next document is written as plaintext. Presence keeps that from happening. Omitted means "leave it alone" for those fields and for storage_backend, storage_config, quantization, spell_lang, wordpress and code. The original fields — type, description, icon, color, custom_meta, max_revisions and response_prompt — are set as sent, as REST PUT does, because proto3 cannot tell an omitted string or 0 from an empty one: send their current values when changing something else.

PUT /v1/collection-config

Set or update collection configuration including storage backend.

Request Body:

Field Type Required Description
collection string Yes Collection name
type string No Collection type (default, website, images, audio, documents). images means something: writes extract images by default and an image file is an image document (SEARCH); the others are labels
description string No Collection description
icon string No Emoji icon
color string No Hex color code
customMeta object No Custom key-value metadata
storageBackend string No Where this collection's document bodies are stored: boltdb (default), memory, s3 — see below
storageConfig object No Backend-specific settings (required for s3)
maxRevisions integer No Revision retention cap. 0 (default) = unlimited; N > 0 keeps only the newest N revisions per document. Older entries are trimmed inside the same transaction as every write.
retrieval object No Per-collection retrieval defaults — see below
responsePrompt string No How to format answers from this collection — see below (max 4 KiB)
trackAccess boolean No Record per-read access events for temporal analytics
trackHot boolean No Maintain a hot-documents leaderboard
spellCorrect boolean No Auto-correct FTS queries using the spell checker
spellLang string No Override language for spell correction
quota object No {maxDocuments, maxBytes, maxVectors, embeddingCallsPerDay, embeddingTokensPerDay}; 0 = no limit. Omitted keeps the stored quota, {} removes it. Changing it needs a global admin when auth is on (403 otherwise) — see below
Quotas

Writes that would take a collection past maxDocuments, maxBytes or maxVectors — on any endpoint: add, update, add-batch, ingest, upload (one file; a multi-file upload lists the refusal per file), import-url — answer 507 Insufficient Storage, and nothing is written (a batch is refused whole). The same 507 comes from the server-wide MDDB_DISK_RESERVE_BYTES and MDDB_VECTOR_RAM_LIMIT_BYTES (config):

{
  "error": "quota exceeded: documents of collection \"acme/notes\" is 10000, limit 10000 (507)",
  "code": "QUOTA_EXCEEDED",
  "status": 507,
  "collection": "acme/notes",
  "resource": "documents",
  "limit": 10000,
  "used": 10000
}

resource is one of documents, bytes, vectors, diskReserve, vectorRam, embeddingCalls, embeddingTokens. A spent embedding budget never refuses a document — its embedding waits, pending — but POST /v1/vector-reindex answers 429 Too Many Requests with Retry-After (seconds to midnight UTC) and retryAfterSeconds in the body. gRPC answers RESOURCE_EXHAUSTED for both; MCP returns the object as the tool error's structuredContent; GraphQL puts it in the error's extensions. See MULTI_TENANCY.

Storage backends

A collection can keep its document bodies somewhere other than the server's own database file:

Backend Holds documents in Use for
boltdb (default) The server's database file Everything, unless you have a reason not to
memory Process memory, lost on restart Scratch collections, tests, caches you can rebuild
s3 Any S3-compatible object store Large corpora whose bodies should not live on the node's disk
curl -X PUT "$MDDB/v1/collection-config" -H 'Content-Type: application/json' -d '{
  "collection": "archive",
  "storageBackend": "s3",
  "storageConfig": {
    "endpoint": "s3.example.com",
    "bucket": "mddb-archive",
    "region": "eu-central-1",
    "accessKey": "...", "secretKey": "..."
  }
}'

What moves and what does not. The backend holds document bodies. The metadata index, revisions, the full-text and vector indexes, and the replication binlog stay in the server's database in every configuration. That is not a limitation to be lifted later: those are written inside a single transaction alongside each other, and a remote object store cannot join it. Splitting them would trade a correctness guarantee for a storage location.

The key index — which document a key and language name — is among what stays, so on every backend a key is found by any spelling of its ASCII letter case (README.md as readme.md), as on boltdb; the S3 bucket holds no key index to migrate (STORAGE-LAYOUT).

So an s3 collection still needs its local database, and that database still needs to survive — it holds everything needed to find a document, just not the document.

Ordering, and what a crash leaves behind. A body is written to the backend before the transaction that indexes it commits. The two cannot be atomic, so the failure is chosen deliberately: a crash in between leaves an object nothing references — wasted space, harmless to readers — rather than an index entry pointing at a document that is not there, which is what people experience as data loss.

A backend that cannot be reached refuses writes. Configuring an unreachable S3 endpoint is rejected at configuration time, and a backend that fails later causes writes to that collection to error rather than falling back to local disk. Silently writing elsewhere is how an operator loses data they believed was in object storage.

Retrieval defaults

Retrieval settings used to be constants scattered across MDDB's internals — FTS returned 50 results, vector 5, hybrid 10, memory recall 10 — so a caller had to know those numbers to get consistent behaviour, and a collection of prose could not be tuned differently from a collection of source.

They now live next to the data. Precedence is fixed everywhere: an explicit request parameter wins, then this profile, then MDDB's default for that endpoint. A collection without a profile behaves exactly as before.

curl -X PUT "$MDDB/v1/collection-config" -H 'Content-Type: application/json' -d '{
  "collection": "handbook",
  "retrieval": {
    "defaultSearchType": "hybrid",
    "topK": 40,
    "retrievalMode": "chunk",
    "contextTokenBudget": 8000
  }
}'
Field Type Description
defaultSearchType string fts | vector | hybrid. Read by clients (mddb-chat, MCP agents) to pick an endpoint; the server does not reroute a request because of it.
topK integer Results per search, 1–1000
retrievalMode string parent (whole document) | chunk (matching passage) | window (passage with neighbours)
hybridStrategy string alpha | rrf
hybridAlpha number 0 = keyword only, 1 = semantic only. Requires hybridAlphaSet: true, because 0.0 is a real weight and cannot double as "unset".
oversample number 1.0–10.0. Candidates fetched per requested result before deduplication or merging — see SEARCH for measured effect
contextTokenBudget integer Cap on total returned context, in tokens
maxTopK integer Most results one search of this collection returns, whatever the request asks. Lowers MDDB_SEARCH_MAX_LIMIT for this collection, never raises it; topK must not exceed it. 0 = unset. A capped response carries "limitCapped": true and the limit used — see SEARCH
groupBy object Default result grouping, e.g. {"key": "path", "perGroup": 1} for one passage per file; a request's own groupBy wins
summaryMode string off (default) | blend | expand: what the documents' client-written summaries (metadata key summary) do on vector and hybrid search — see SEARCH
summaryWeight number 0–10. BM25F weight of meta.summary while summaryMode is not off; unset = 2.0

The context budget drops results, it does not truncate them. Half a document still costs tokens and no longer says anything reliable, so the budget trims the tail of an already-ranked list and the response sets contextTruncated: true. The first result is always kept, even when it alone exceeds the budget — returning nothing would read as "no matches" rather than as a budget too small for the corpus. Token counts are approximated as bytes÷4; a real tokeniser would tie the budget to one model family, and this is a guard rail, not accounting.

Applies to /v1/fts, /v1/vector-search, /v1/hybrid-search, /v1/search and /v1/memory/recall, over REST, gRPC and MCP alike. Cross-collection search is deliberately excluded: it has no single collection whose profile could own topK, and picking one of N arbitrarily would be worse than a fixed default.

Answer formatting

A collection of runbooks wants numbered steps; a collection of API docs wants code blocks and key references. That instruction used to live in the client — a per-scenario system prompt in mddb-chat, and nothing at all for MCP agents — so every consumer had to know, separately, what every collection expected.

responsePrompt puts it with the data:

curl -X PUT "$MDDB/v1/collection-config" -H 'Content-Type: application/json' -d '{
  "collection": "runbooks",
  "responsePrompt": "Answer as numbered steps. Quote the exact command for each step and name the file it belongs in. If the runbook does not cover the question, say so instead of improvising."
}'

It is picked up in two places, without a second round trip:

  • mddb-chat appends it to the scenario's system prompt. Order is deliberate: the scenario is the operator's policy — who the assistant is, what it may say — and the collection prompt is about the shape of its data. Policy comes first, so a collection cannot talk its way past it by opening with "ignore your previous instructions".
  • MCP returns it as responsePrompt on search_documents, vector_search and hybrid_search results, and folds it into the rag-pipeline prompt. An agent gets the instruction in the same call that fetched what to say.

and are expanded through the same template mechanism the automation rules use. The value is plain text for a model, capped at 4 KiB — it is prepended to prompts automatically, so an unbounded one would quietly eat the context the answer needs — and the panel renders it as text, never as markup.

A collection without a responsePrompt behaves exactly as before.

storageConfig fields (for S3):

Field Type Required Description
endpoint string Yes S3 endpoint (e.g. s3.amazonaws.com, minio:9000)
bucket string Yes S3 bucket name
region string No AWS region (e.g. us-east-1)
accessKey string No Access key
secretKey string No Secret key
prefix string No Key prefix within bucket (e.g. mddb/)
useTLS bool No Use HTTPS (default: false)

Example — In-Memory backend:

curl -X PUT http://localhost:11023/v1/collection-config \
  -H 'Content-Type: application/json' \
  -d '{
    "collection": "scratch",
    "type": "default",
    "storageBackend": "memory"
  }'

Example — S3 backend:

curl -X PUT http://localhost:11023/v1/collection-config \
  -H 'Content-Type: application/json' \
  -d '{
    "collection": "archive",
    "type": "documents",
    "storageBackend": "s3",
    "storageConfig": {
      "endpoint": "s3.amazonaws.com",
      "bucket": "my-mddb-archive",
      "region": "us-east-1",
      "accessKey": "AKIAIOSFODNN7EXAMPLE",
      "secretKey": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
      "prefix": "mddb/",
      "useTLS": true
    }
  }'

Response:

{
  "status": "ok",
  "collection": "archive"
}

Note: The memory backend is ephemeral — all data is lost on server restart. The s3 backend requires endpoint and bucket in storageConfig. The default boltdb backend uses the embedded database.


GET /v1/collection-configs #

List all collection configurations.

Example:

curl http://localhost:11023/v1/collection-configs

Response:

{
  "configs": [
    {
      "collection": "blog",
      "config": { "type": "default", "description": "Blog posts" }
    }
  ],
  "total": 1
}

Corpus packs: /v1/corpus #

A corpus pack is one collection, or several (v2.19.11) — documents, full-text index, vectors, geo points — shipped as a .mddbpack file and installed read-only on any server. Building, installing and removing need the admin permission. The full guide: CORPUS-PACKS.

Method Path Body Answer
GET /v1/corpus — {"packs":[{"collection","readOnly","corpus":{…}}],"total"}
POST /v1/corpus/build {"collection","license","version","description","sources":[{"repo","commit","license"}]}, or "name" and "collections":["a",{"name":"b","license","sources"}] instead of "collection" the pack, application/zstd
POST /v1/corpus/install multipart/form-data, field pack {"name","version","license","docCount","vectorsDisabled","warnings","collections"}
POST /v1/corpus/inspect multipart/form-data, field pack (the pack or its first megabytes) {"manifest":{…},"conflicts":[…]}; nothing is installed
POST /v1/corpus/remove {"name"} {"status":"removed","name","deleted"}
curl -X POST http://localhost:11023/v1/corpus/build \
  -d '{"collection":"k8s-docs","license":"CC-BY-4.0","version":"1.31"}' -o k8s-docs-1.31.mddbpack
curl -X POST http://localhost:11023/v1/corpus/install -F pack=@k8s-docs-1.31.mddbpack

build answers 400 without a licence, for an encrypted collection or one whose documents live in S3 or memory, for both collection and collections, and for several collections without a name; 404 for a collection without documents. install answers 400 for anything that is not a valid pack — a checksum that does not match, a newer storage format, keys of another collection — and 409 when a pack of that name is installed or a collection of the pack already holds data. inspect answers the same 400s and lists the 409 reasons in conflicts.

An installed pack's config carries readOnly: true and corpus. Every write to it is refused: 403 with {"code":"READ_ONLY","collection":"…"} over REST, PERMISSION_DENIED over gRPC, READ_ONLY in MCP structured content and GraphQL extensions.


Chat conversations: /v1/chat/conversations #

Persistent per-user chat conversations (v2.19.0, #405). A host application that has already signed its user in keeps that user's conversations in MDDB, so a reconnect, a new pod or a restart of mddb-chat resumes them with their history. This is the host API: the caller is the host's backend (or mddb-chat on its behalf), never a browser.

Every conversation belongs to one sub — the opaque user id of the host's signed join token (below). Every request names it, in the query string of a GET or DELETE and in the body of a POST. A conversation whose sub differs answers 404, exactly as a missing id does: a host cannot cross users by mistake, and cannot learn that another user's conversation exists.

Method Path Body / query Answer
POST /v1/chat/conversations {"sub","scenario","displayName"?,"retentionDays"?} the conversation, messages: []
GET /v1/chat/conversations ?sub=&scenario=&limit=&cursor= {"conversations":[summary…],"nextCursor"?}, newest first
GET /v1/chat/conversations/{id} ?sub=&limit= the conversation with its messages, oldest first; limit keeps the last N
POST /v1/chat/conversations/{id}/messages {"sub","messages":[…]} the conversation holding only the messages added, with their ids
POST /v1/chat/conversations/{id}/end {"sub"} the conversation, ended: true, no messages
DELETE /v1/chat/conversations/{id} ?sub= {"deleted":true,"id"}
DELETE /v1/chat/conversations ?sub= {"deleted":<count>,"sub"} — everything of a user (GDPR erasure)
GET /v1/chat/conversations/export ?sub= {"sub","exportedAt","total","conversations":[…]} — everything of a user, with messages (GDPR export)

A conversation:

{
  "id": "5f3c9a0e1b2d4c6f8a7b9c0d1e2f3a4b",
  "scenario": "support",
  "sub": "user-42",
  "displayName": "Ada",
  "title": "How do I rotate the key?",
  "createdAt": 1794000000,
  "updatedAt": 1794000042,
  "lastMessageAt": 1794000042,
  "ended": false,
  "retentionDays": 30,
  "expiresAt": 1796592042,
  "messageCount": 2,
  "messages": [
    {"id": "9b1d…", "role": "user", "content": "How do I rotate the key?", "createdAt": 1794000040},
    {"id": "c41e…", "role": "assistant", "content": "Call POST /v1/encryption/rotate.",
     "toolCalls": [{"name": "search", "collection": "docs", "durationMs": 42}],
     "model": "gpt-5", "provider": "openai", "tokens": {"prompt": 812, "completion": 64},
     "createdAt": 1794000042}
  ]
}

A summary (in a listing) is the same object without messages. Times are Unix seconds.

Field Rule
sub, scenario Required. At most 256 bytes, no control characters. sub is opaque to MDDB
displayName Optional, same limits
title Set by the server: the start of the first user message, one line, at most 80 characters, cut between characters
messages[].role user, assistant or tool — a system message is refused, the prompt belongs to the scenario
messages[].content Required unless toolCalls is set; at most 256 000 bytes
messages[].id Set by the server unless the caller sends one matching [A-Za-z0-9_-]{1,64} (2.19.0, #406; below)
messages[].createdAt Optional; now when omitted (send it to import an older history)
one append 1 to 100 messages; a conversation holds at most 5000 — start a new one after that
limit on a listing default 50, at most 200; walk with cursor=<nextCursor>
limit on a read the last N messages — mddb-chat passes its max_history_length; messageCount stays the whole conversation's
# Start (or "new conversation": the old one stays)
curl -X POST http://localhost:11023/v1/chat/conversations \
  -H "Authorization: Bearer $HOST_TOKEN" \
  -d '{"sub":"user-42","scenario":"support","displayName":"Ada","retentionDays":30}'

# After each turn
curl -X POST http://localhost:11023/v1/chat/conversations/$ID/messages \
  -H "Authorization: Bearer $HOST_TOKEN" \
  -d '{"sub":"user-42","messages":[{"role":"user","content":"How do I rotate the key?"},
       {"role":"assistant","content":"Call POST /v1/encryption/rotate.","model":"gpt-5","provider":"openai",
        "tokens":{"prompt":812,"completion":64},"toolCalls":[{"name":"search","collection":"docs","durationMs":42}]}]}'

# Resume after a reconnect: the newest conversation, the last 20 messages
curl "http://localhost:11023/v1/chat/conversations?sub=user-42&scenario=support&limit=1" -H "Authorization: Bearer $HOST_TOKEN"
curl "http://localhost:11023/v1/chat/conversations/$ID?sub=user-42&limit=20" -H "Authorization: Bearer $HOST_TOKEN"

# "Delete my conversations" / GDPR
curl "http://localhost:11023/v1/chat/conversations/export?sub=user-42" -H "Authorization: Bearer $HOST_TOKEN"
curl -X DELETE "http://localhost:11023/v1/chat/conversations?sub=user-42" -H "Authorization: Bearer $HOST_TOKEN"

Status codes. 400 a missing sub or a request the store refuses (the reason is in error); 401/403 no credentials / no permission, or a read-only server or collection on a write; 404 no such conversation for this sub; 409 an append to an ended conversation; 405 any other method.

Permission. There is no separate scope to grant: the conversations live in one system collection, chat_conversations, and the host API needs read on it for the three GETs and write for everything else. Give the host's user (or API key) read and write on that collection and nothing more, and the key is a chat host that reaches no other data — least privilege with the permissions MDDB already has. A global administrator passes as everywhere. A tenant user's conversations live in <tenant>/chat_conversations (MULTI_TENANCY), so two tenants never share a store even for the same sub.

curl -X POST http://localhost:11023/v1/auth/permissions -H "Authorization: Bearer $ADMIN_TOKEN" \
  -d '{"username":"chat-host","collection":"chat_conversations","read":true,"write":true}'

Retention. retentionDays is the scenario's retention, given when the conversation is created (0 or omitted: MDDB_CHAT_RETENTION_DAYS, default 30; at most 3650). Every write — an append, an end — moves expiresAt to that many days from now, and the conversation is removed after it by the same TTL reaper that removes any expired document; an expired conversation is "not found" from the moment it expires.

Storage. One document per conversation, written through the same path as every document: encryption at rest, replication, backups and quotas apply unchanged. A conversation is not embedded, not full-text indexed and not sent to webhooks. It is separate from the agent memory store on purpose: memory sessions are read by any caller that names a sessionId and every message there is embedded for recall, while a conversation is only ever reachable with its sub.

Also over gRPC (CreateChatConversation … ExportChatConversations, GRPC) and, read-only, as the MCP tools chat_conversation_list and chat_conversation_get (MCP).

Answer feedback and the turn log fields (2.19.0, #406)

Method Path Body Answer
POST /v1/chat/conversations/{id}/feedback {"sub","messageId","rating","comment"?} {"conversationId","messageId","feedback":{"rating","comment"?,"at"}}

A rating is up or down, on one assistant message, and is stored with that message as feedback. comment is optional: trimmed, at most 2000 characters, line breaks and tabs allowed, no other control characters. Rating the same message again replaces the earlier rating. An ended conversation can still be rated (a visitor often rates after closing the chat). 400 for a missing messageId, a rating that is not up/down or a bad comment; 404 for a message the conversation does not hold, a user message, or another sub's conversation. Permission is write on the chat collection, as for an append. Over gRPC: RateChatMessage.

New, additive message fields — everything above keeps working unchanged:

Field Rule
messages[].id Kept when the caller sends one matching [A-Za-z0-9_-]{1,64} (so a rating can name the answer by the id the client saw — mddb-chat sends the done frame's message_id); otherwise set by the server
messages[].outcome Marks a logged turn (assistant messages only): answered, noResults, refused or error. An answered reply that is the scenario's redirect text (offTopic.mode: redirect) is stored as refused. A message with an outcome may have empty content (a failed turn)
messages[].latencyMs How long the turn took, 0 or more
messages[].loopStopped true on an answer mddb-chat's loop guard cut short (2.19.2, #413); assistant messages only
messages[].toolCalls[].query, .resultKeys, .topScore What a tool searched for (at most 4096 bytes), the keys it found, best first (at most 50), and the best score
messages[].toolCalls[].server The external MCP server of the tool (MCP-005); absent for a built-in tool. name is the tool's own name
messages[].feedback {"rating","comment"?,"at"} — set only by the feedback call; a feedback sent in an append is dropped
redact on an append true redacts these messages before they are stored, and makes the conversation redact: true: every later message and feedback comment of it is redacted too (chat)
curl -X POST http://localhost:11023/v1/chat/conversations/$ID/feedback \
  -H "Authorization: Bearer $HOST_TOKEN" \
  -d '{"sub":"user-42","messageId":"3f9a…","rating":"down","comment":"The port is wrong."}'

The join token (host → mddb-chat)

MDDB itself never sees this token. It is documented here because it is where sub comes from: the host signs it, mddb-chat verifies it and then calls the API above with the sub it carries — never with a user id sent by the browser.

token   = "v1." + payloadB64 + "." + signatureB64
payload = {"sub":"<opaque user id>","name":"<display name>","scenario":"<scenario>","exp":<unix seconds>}
payloadB64   = base64url(UTF-8 JSON of payload), no padding
signatureB64 = base64url(HMAC-SHA256(secret, "v1." + payloadB64)), no padding
Claim Required Meaning
sub yes The user's id at the host: opaque, stable, 1–256 bytes, no control characters. It becomes the conversation's sub
name no Display name, stored as displayName
scenario yes The scenario the user may join; a join for another scenario is refused
exp yes Expiry, Unix seconds. Keep it short (a few minutes): the token only opens the socket

Verification, in this order: the token has three dot-separated parts and the first is v1; the signature equals HMAC-SHA256 over the ASCII bytes of "v1." + payloadB64, compared in constant time; only then the payload is decoded; exp is in the future (and not more than 24 hours away); sub and scenario are present. The secret is shared between the host and mddb-chat only, at least 32 random bytes. Unknown claims are ignored, so the payload can grow without a new version.

Test vector — secret test-secret-0123456789abcdef0123456789abcdef, payload {"sub":"user-42","name":"Ada","scenario":"support","exp":1900000000}:

v1.eyJzdWIiOiJ1c2VyLTQyIiwibmFtZSI6IkFkYSIsInNjZW5hcmlvIjoic3VwcG9ydCIsImV4cCI6MTkwMDAwMDAwMH0.GlF4jwoVSiQHfdz2PJCcQimFfTfy-kCn-wWGkDd69xI
// Host side (Node.js)
import { createHmac } from "node:crypto";
const b64 = (b) => Buffer.from(b).toString("base64url");
function joinToken(secret, sub, scenario, name, ttlSeconds = 300) {
  const body = "v1." + b64(JSON.stringify({ sub, name, scenario, exp: Math.floor(Date.now() / 1000) + ttlSeconds }));
  return body + "." + createHmac("sha256", secret).update(body).digest("base64url");
}

The MCP identity token (mddbd → MCP server)

(v2.19.2, #414) What an external MCP server with forwardIdentity receives on every request of a chat user's call, in X-MDDB-Chat-Identity (or the configured header), next to its own credential. The shape is the join token's, so a host can reuse its verifier, with an audience a join token never carries:

token   = "v1." + payloadB64 + "." + signatureB64
payload = {"aud":"mcp","sub":"<sub>","scenario":"<scenario>","server":"<server name>","iat":<unix>,"exp":<unix>}
payloadB64   = base64url(UTF-8 JSON of payload), no padding
signatureB64 = base64url(HMAC-SHA256(identityKey, "v1." + payloadB64)), no padding
Claim Meaning
aud Always "mcp". Require it: a join token has no aud, so it can never pass as an identity token
sub The user's id at the host, exactly as in the join token that opened the session
scenario, server Where the call came from: log it, or restrict a key to one server
iat, exp Issue and expiry time, Unix seconds; exp - iat is ttlSeconds (default 120, at most 300)

Verification, in this order: three dot-separated parts and the first is v1; the signature equals HMAC-SHA256 over the ASCII bytes of "v1." + payloadB64 with the identity key, compared in constant time; only then the payload is decoded; aud == "mcp"; exp is in the future and at most 300 seconds away; sub is present. Check the server's static credential as well: the token says on behalf of whom, the credential says that this is the chat service.

  • The key never travels. mddbd sends the HMAC, not the key, which is a sealed MCP secret of its own (at least 32 bytes, write-only), never the server's credential and never the join-token secret. A leaked request shows one user's identity until exp, not the means to mint one.
  • Identity from the session only. sub comes from the verified join token; the model and the tool arguments cannot name another user. An anonymous session is never offered the server's tools.
  • Nothing is granted by the token. The host decides what an identified chat caller may do (read-only tools, say). There is no jti yet: the short lifetime, the required credential and TLS are the controls against replay.

Test vector — identity key 0123456789abcdef0123456789abcdef, payload {"aud":"mcp","sub":"user-42","scenario":"support","server":"account","iat":1767225600,"exp":1767225720}:

v1.eyJhdWQiOiJtY3AiLCJzdWIiOiJ1c2VyLTQyIiwic2NlbmFyaW8iOiJzdXBwb3J0Iiwic2VydmVyIjoiYWNjb3VudCIsImlhdCI6MTc2NzIyNTYwMCwiZXhwIjoxNzY3MjI1NzIwfQ.hlY9TBl5ZxNybqBHuIRuWJI5jDKgH6N0GDHDj6fGaog
# Host side (Python): verify an identity token.
import base64, hashlib, hmac, json, time

def b64d(s):
    return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))

def verify_identity(token, key, now=None):
    now = int(time.time()) if now is None else now
    parts = token.split(".")
    if len(parts) != 3 or parts[0] != "v1":
        raise ValueError("not a v1 token")
    mac = hmac.new(key, (parts[0] + "." + parts[1]).encode(), hashlib.sha256).digest()
    if not hmac.compare_digest(mac, b64d(parts[2])):
        raise ValueError("bad signature")
    claims = json.loads(b64d(parts[1]))
    if claims.get("aud") != "mcp":
        raise ValueError("not an identity token")
    if not now < claims["exp"] <= now + 300:
        raise ValueError("expired or too far ahead")
    if not claims.get("sub"):
        raise ValueError("no sub")
    return claims

Chat conversation log: /v1/chat/log #

The review API of the conversation log (v2.19.0, #406): what visitors asked and how the assistant did, across users. Global admin only: it shows every user's turns. It reads the logged turns — assistant messages with an outcome — of the caller's chat collection (for a global admin, the global chat_conversations); a scenario logs only when its logging.enabled is on.

Method Path Query Answer
GET /v1/chat/log scenario, from, to, rating, outcome, cursor, limit {"turns":[…],"nextCursor"?}, newest first
GET /v1/chat/log/export format=csv|json (default json) and the same filters, no paging a file download (Content-Disposition: attachment)
GET /v1/chat/gaps scenario, from, to, minCount, threshold, limit {"gaps":[…],"threshold"}, most frequent first
Parameter Values
from, to Unix seconds, an RFC 3339 time or a date YYYY-MM-DD; both inclusive; a date as to is that whole day (UTC)
rating up, down, none (unrated) or any (rated)
outcome answered, noResults, refused, error
limit log: default 50, at most 200, walk with cursor=<nextCursor>; gaps: default 100, at most 1000
minCount gaps: only questions asked at least this often (default 1)
threshold gaps: a turn whose best search score is below this is a gap; default MDDB_CHAT_GAP_SCORE, else 0.3

A turn:

{
  "conversationId": "5f3c…", "messageId": "3f9a…", "scenario": "support",
  "sub": "user-42", "displayName": "Ada", "anonymous": false, "at": 1794000042,
  "question": "How do I rotate the key?",
  "answer": "Call POST /v1/encryption/rotate.", "answerExcerpt": "Call POST /v1/encryption/rotate.",
  "outcome": "answered", "rating": "down", "comment": "Wrong endpoint.",
  "model": "gpt-5", "provider": "openai", "latencyMs": 1830, "tokens": {"prompt": 812, "completion": 64},
  "toolCalls": [{"name": "search_docs", "collection": "docs", "durationMs": 42,
                 "query": "rotate encryption key", "resultKeys": ["encryption", "keys"], "topScore": 0.81}]
}

question is the user message before the answer; answerExcerpt is the answer on one line, at most 280 characters. An anonymous session's turn has anonymous: true and no sub or displayName — its session id is never shown as an identity. A turn mddb-chat's loop guard cut short carries "loopStopped": true (2.19.2, #413). Identities (sub, displayName) appear only because the API is for global administrators.

Export. Every turn the filters select, at most 100 000, written and flushed row by row. JSON is one array of turns. CSV is RFC 4180 (fields with commas, quotes or line breaks are quoted, quotes doubled) under the header time, conversationId, messageId, scenario, sub, displayName, anonymous, question, answer, outcome, rating, comment, model, provider, latencyMs, promptTokens, completionTokens, tools, topScore, loopStopped — time in RFC 3339 UTC, tools as name(query) → key key; … (server/name for an external MCP tool), topScore the best of the turn. A cell that starts with =, +, -, @ or a tab gets a leading apostrophe, so a spreadsheet does not run visitor text as a formula (CSV injection).

Docs gaps. The questions the documentation did not answer: a logged turn whose outcome is noResults, whose searches (tool calls with a query) found nothing, or whose best score is below threshold. Errors and refusals do not count, nor does a turn that searched nothing. Questions are grouped by their normalised text — lowercase, punctuation and symbols stripped, whitespace collapsed:

{"gaps": [{"question": "how do i back up", "example": "How do I back up?", "count": 7,
           "noResults": 5, "lastAskedAt": 1794000042, "scenarios": ["support"]}],
 "threshold": 0.3}

example is the latest question as asked; noResults how many of count found nothing at all. Ordered by count, then the latest asked.

curl "http://localhost:11023/v1/chat/log?scenario=support&rating=down&from=2026-11-01" -H "Authorization: Bearer $ADMIN_TOKEN"
curl -OJ "http://localhost:11023/v1/chat/log/export?format=csv&outcome=noResults" -H "Authorization: Bearer $ADMIN_TOKEN"
curl "http://localhost:11023/v1/chat/gaps?minCount=2" -H "Authorization: Bearer $ADMIN_TOKEN"

400 for an unreadable time, rating, outcome, format, cursor or threshold, or a negative number; 401/403 for anyone but a global administrator. Also over gRPC (ListChatLog, ListChatGaps, GRPC) and as the read-only MCP tools chat_log_list and chat_gaps (MCP).

GET /v1/embedding-configs #

List all configured embedding models.

Example:

curl http://localhost:11023/v1/embedding-configs

Response:

{
  "configs": [
    {
      "id": "cfg_abc123",
      "name": "OpenAI Ada",
      "provider": "openai",
      "model": "text-embedding-3-small",
      "dimensions": 1536,
      "apiKey": "sk-...",
      "apiUrl": "",
      "isDefault": true,
      "createdAt": 1709100000
    }
  ]
}

Also supports POST to create a new embedding config.


GET/PUT/DELETE /v1/embedding-configs/:id #

Manage a specific embedding configuration.

  • GET returns the config object
  • PUT updates the config (fields: name, provider, model, dimensions, apiKey, apiUrl, isDefault)
  • DELETE removes the config (returns 204 No Content)

Example:

curl http://localhost:11023/v1/embedding-configs/cfg_abc123

POST /v1/embedding-configs/set-default #

Set a specific embedding configuration as default.

Request Body:

{
  "id": "cfg_abc123"
}

Response:

{
  "message": "default config updated"
}

GET/POST/DELETE /v1/stopwords #

Manage FTS stop words for a collection.

GET — List stop words:

curl "http://localhost:11023/v1/stopwords?collection=blog"

Response:

{
  "collection": "blog",
  "entries": [
    { "word": "the", "isDefault": true },
    { "word": "myword", "isDefault": false }
  ],
  "total": 2,
  "defaults": 1,
  "custom": 1
}

POST — Add stop words:

{
  "collection": "blog",
  "words": ["myword", "another"]
}

DELETE — Remove stop words:

{
  "collection": "blog",
  "words": ["myword"]
}

GET/POST /v1/webhooks #

List or register webhooks.

GET — List all webhooks:

curl http://localhost:11023/v1/webhooks

POST — Register a webhook:

{
  "url": "https://example.com/hook",
  "events": ["doc.added", "doc.updated", "doc.deleted"],
  "collection": "blog"
}

Response (webhook object):

{
  "id": "wh_abc123",
  "url": "https://example.com/hook",
  "events": ["doc.added", "doc.updated", "doc.deleted"],
  "collection": "blog",
  "createdAt": 1709100000
}

GET /v1/audit #

List audit-log events. Admin-only. Returns 404 when MDDB_AUDIT_ENABLED is not set.

Query parameters:

Name Type Description
from RFC3339 timestamp Lower bound (inclusive). Converted to nanoseconds internally.
to RFC3339 timestamp Upper bound (inclusive).
fromNanos int64 Nanosecond-precision lower bound (takes precedence over from).
toNanos int64 Nanosecond-precision upper bound.
actor string Filter by authenticated username.
action string e.g. auth.login, auth.jwt, auth.apikey, auth.missing, write./v1/add.
result string ok or fail.
limit int Max events returned (default 100).

Example:

curl -H "Authorization: Bearer $ADMIN_JWT" \
  "http://localhost:11023/v1/audit?actor=alice&result=fail&limit=50"

Response:

{
  "events": [
    {
      "ts": 1740000000000000000,
      "actor": "alice",
      "action": "auth.login",
      "resource": "/v1/auth/login",
      "result": "fail",
      "ip": "203.0.113.5",
      "userAgent": "curl/8.4.0"
    }
  ],
  "count": 1,
  "dropped": 0
}

Events are returned newest-first. dropped reports the running total of events that could not fit in the in-memory ring buffer (operational-health signal — a non-zero value means the audit subsystem was under pressure).


GET /v1/admin/diagnose #

A tar.gz describing the instance without its data, to attach to an issue. mddb-cli diagnose saves it; mddb-cli diagnose --inspect prints its manifest without writing anything.

Authentication: admin JWT or API key required (as /v1/audit). Read-only: it works on a read-only instance and on a replication follower.

Query parameters:

Parameter Default Effect
profiles false Add runtime.json (goroutine count, heap and GC counters); stacks and heap profiles come from /debug/pprof
integrity false Add integrity.json: bbolt's consistency check of every database file (slow on a large database; the request budget becomes 30 minutes)
keepNames false Keep collection names instead of c_ + 8 hex digits of their SHA-256

Response: 200, Content-Type: application/gzip, Content-Disposition: attachment; filename="mddb-diagnose-<UTC time>.tar.gz". The first file is MANIFEST.json:

{
  "format": 1,
  "version": "2.19.13",
  "createdAt": "2026-10-30T15:31:04Z",
  "options": { "profiles": false, "integrity": false, "keepNames": false },
  "files": [
    { "name": "build.json", "size": 237, "sha256": "e1db…", "redaction": "none: build and runtime facts only" },
    { "name": "query-shape.json", "size": 2336, "sha256": "b83b…", "redaction": "counters only; collections hashed (c_ + 8 hex of SHA-256)" }
  ],
  "omitted": [ { "name": "runtime.json", "reason": "opt-in: profiles" } ],
  "neverIncluded": [ "document content, metadata values, document IDs and keys", "…" ]
}

The files, their sources and their redaction are listed in TELEMETRY.md, "Diagnose bundle".

curl -H "Authorization: Bearer $TOKEN" -o bundle.tar.gz \
  "http://localhost:11023/v1/admin/diagnose?profiles=true"
tar -xOzf bundle.tar.gz MANIFEST.json

GET /v1/audit/exporters #

Per-sink delivery counters for the audit log export subsystem. Returns a snapshot of every configured exporter (webhook + syslog) with delivered / failed / dropped counts and the last error.

Authentication: admin JWT or API key required.

Response:

{
  "exporters": [
    {
      "name": "webhook",
      "target": "https://splunk.example/services/collector/raw",
      "queued": 1250,
      "delivered": 1248,
      "failed": 2,
      "dropped": 0,
      "lastError": "attempt 1: HTTP 503",
      "bufferSize": 1024
    },
    {
      "name": "syslog",
      "target": "tcp://logs.example:6514",
      "queued": 1250,
      "delivered": 1250,
      "failed": 0,
      "dropped": 0,
      "lastError": "",
      "bufferSize": 1024
    }
  ],
  "count": 2
}

Exporters are configured via MDDB_AUDIT_EXPORT_WEBHOOK_URL, MDDB_AUDIT_EXPORT_SYSLOG_ADDR, etc. — see config.


GET /v1/encryption/status #

At-rest encryption posture: primary keyID, configured previous keyIDs, and per-collection counts of how each document is sealed.

Authentication: admin JWT or API key required.

Response:

{
  "enabled": true,
  "primaryKeyID": 2,
  "previousKeyIDs": [1],
  "collections": [
    {
      "collection": "secrets",
      "encrypted": true,
      "total": 1500,
      "withPrimary": 800,
      "withLegacy": 700,
      "plaintext": 0,
      "unknownKey": 0
    }
  ]
}

withLegacy counts entries sealed under a previous key (V1 ciphertexts or V2 with a non-primary keyID). Run POST /v1/encryption/rotate to converge them on the current primary.


POST /v1/encryption/rotate #

Start a re-encryption job that walks every encrypted entry under non-primary keys and re-seals it with the current MDDB_ENCRYPTION_KEY. Plaintext entries and entries already sealed under the primary are skipped.

Authentication: admin JWT or API key required. Refused in read-only mode.

Body (optional):

{ "collection": "secrets" }

Empty collection (or omit the body) scopes the job to every collection.

Response (job is started in the background; poll for progress):

{
  "id": "rot-a1b2c3d4e5f6a7b8",
  "status": "queued",
  "primaryKeyID": 2,
  "startedAt": 1714560000000000000,
  "scanned": 0,
  "reencrypted": 0,
  "skipped": 0,
  "errors": 0
}

Calling rotate while a job is already running returns the running job's ID instead of queueing a second one — the operation is single-flight.


GET /v1/encryption/jobs[/:id] #

Without an ID — list every rotation job ever queued in this process (newest first):

{ "jobs": [ { "id": "rot-...", "status": "completed", ... } ] }

With an ID (GET /v1/encryption/jobs/:id) — single job snapshot:

{
  "id": "rot-a1b2c3d4e5f6a7b8",
  "status": "completed",
  "primaryKeyID": 2,
  "startedAt": 1714560000000000000,
  "finishedAt": 1714560015000000000,
  "scanned": 1500,
  "reencrypted": 700,
  "skipped": 800,
  "errors": 0
}

status is one of queued, running, completed, failed. A failed job carries lastError with the most recent failure message.


GET /v1/compliance-status #

Report the live state of the production-hardening guard, for operator-facing liveness / readiness probes and for external monitoring that must detect a drifted configuration before production traffic hits a non-compliant server. With auth on, it needs an authenticated caller (any valid token or API key), so give the probe a read-only API key.

Query parameters: none.

Response:

{
  "production": true,
  "compliant": true,
  "missing": [],
  "missingCount": 0
}

When the server was started with MDDB_PRODUCTION=true but a guardrail is not satisfied the server would have refused to boot, so compliant=true is implied. When MDDB_PRODUCTION is unset the server runs with the existing defaults and this endpoint reports what is and is not wired up:

{
  "production": false,
  "compliant": false,
  "missing": [
    { "envVar": "MDDB_AUTH_ENABLED",     "want": "true",              "reason": "A.5.15 / CC6.1 — access control" },
    { "envVar": "MDDB_TLS_ENABLED",      "want": "true",              "reason": "A.8.24 / CC6.7 — encryption in transit" },
    { "envVar": "MDDB_CORS_ORIGINS",     "want": "explicit allowlist",   "reason": "A.8.23 / CC6.6 — web-origin segmentation" },
    { "envVar": "MDDB_AUDIT_ENABLED",    "want": "true",              "reason": "A.8.15 / CC7.2 — audit trail" },
    { "envVar": "MDDB_RATE_LIMIT_ENABLED","want": "true",             "reason": "A.5.30 / CC6.6 — resource-exhaustion protection" }
  ],
  "missingCount": 5
}

Wire a liveness probe to alert when compliant=false so configuration drift is caught immediately.


POST /v1/webhooks/delete #

Delete a webhook by ID.

Request Body:

{
  "id": "wh_abc123"
}

Response:

{
  "status": "deleted",
  "id": "wh_abc123"
}

POST /v1/revisions #

List document revision history.

Request Body:

{
  "collection": "blog",
  "key": "homepage",
  "lang": "en"
}

Response:

{
  "collection": "blog",
  "key": "homepage",
  "lang": "en",
  "revisions": [
    {
      "timestamp": 1709200000,
      "updatedAt": 1709200000,
      "contentMd": "# Old content",
      "meta": { "author": ["Jane"] }
    }
  ],
  "total": 1
}

timestamp identifies the revision; restore takes it. It is the write's unix second. When a document already has a revision in that second, the new one takes the next free second. Several writes within a second therefore keep every version, dated a second or so apart in order. updatedAt keeps the actual write time.


POST /v1/revisions/restore #

Restore a document to a previous revision.

Request Body:

{
  "collection": "blog",
  "key": "homepage",
  "lang": "en",
  "timestamp": 1709200000
}

Response: Restored document object.


GET/POST /v1/automation #

List or create automation rules (triggers, crons, webhooks).

GET — List rules:

curl http://localhost:11023/v1/automation

Response:

{
  "rules": [
    {
      "id": "auto_abc",
      "name": "Alert on new docs",
      "type": "trigger",
      "searchType": "fts",
      "query": "urgent",
      "threshold": 0.8,
      "webhookUrl": "https://example.com/alert"
    }
  ],
  "total": 1
}

POST — Create a rule:

{
  "name": "Daily report",
  "type": "cron",
  "schedule": "0 9 * * *",
  "searchType": "vector",
  "query": "status report",
  "webhookUrl": "https://example.com/report"
}

Response: Created rule object (201 Created).


GET/PUT/DELETE /v1/automation/:id #

Manage a specific automation rule.

  • GET returns the rule object
  • PUT updates the rule
  • DELETE removes the rule

GET takes type (webhook, trigger, cron) and, since 2.19.0, collection: only the rules acting on that collection — the syncs writing to it and the triggers watching it. Every sync and backup in a listing carries lastResult (at, status, durationMs, error, and a sync's added, updated, unchanged, deleted, failed), the newest automation log entry of the rule. See AUTOMATIONS.

POST /v1/automation/:id/run (2.19.0) — Run a cron rule's sync or backup now, through the code its schedule fires (logged, announced on the jobs SSE stream, firing its webhook). 202:

{"ruleId": "3f9c2a1b7d4e5f60", "action": "sync", "status": "started",
 "jobId": "sync-3f9c2a1b7d4e5f60-20261030T120000Z", "startedAt": 1793361600}

409 while the previous run of the rule is still going (the skip is logged), 404 for no such rule, 400 for a rule with no sync or backup, 503 without a cron scheduler (MDDB_CRONS off). Global administrator.

A git sync's lastResult (2.19.5) also has ref, commit, commitUrl (the commit's page on the forge) and upToDate (the commit was the last run's: nothing downloaded or written). The git source's fields — url, ref (a branch, a tag or latest-release), include, exclude, forge, tokenSecretRef, hookSecretRef, adopt — are described in AUTOMATIONS. A rule naming a stored secret that does not exist is refused with 400.

POST /v1/automation/:id/hook (2.19.5) — A forge's push or release webhook runs a git sync now. No mddb credentials: the request is verified against the rule's hookSecretRef secret — X-Hub-Signature-256: sha256=<hex HMAC-SHA256 of the body> (GitHub; Gitea and Forgejo send it too), X-Gitea-Signature / X-Forgejo-Signature: <hex>, or X-Gitlab-Token: <secret>. 202 with the run (as /run), 200 {"status":"pong"} for GitHub's X-GitHub-Event: ping, 401 for a missing or wrong signature, 404 for an id without a hook, 409 while the previous run is going, 413 for a body over 25 MB, 503 when the secret cannot be opened or no cron scheduler runs. For an issues sync (2.19.11) an event about an issue, a comment or a pull request refreshes that one document and answers 200 with what it did (AUTOMATIONS).

POST /v1/sync/refresh (2.19.11) — {"collection": "...", "number": 123}: refresh item 123 of each issues sync writing to the collection now, or, without number, start an incremental run of each sync rule writing to it. Permission: write on the collection (an MCP key limited to it may call it; MCP tool sync_refresh). At most once every 30 s per rule: 200 with runs (each done, started, throttled, running or error, with lastRunAt), 429 with Retry-After when every rule was refreshed too recently, 404 when no sync rule writes to the collection. See AUTOMATIONS.

GET/PUT /v1/forge-tokens (2.19.11) — the default forge tokens, {"defaults": {"github.com": "github-token"}}: host → the stored secret a git or issues sync on that host reads with when neither its rule nor its collection's repository names one. A PUT replaces the map. Global admin. See AUTOMATIONS.

POST /v1/automation/:id/test — Test a trigger rule:

{
  "trigger": { "id": "auto_abc", "name": "...", "searchType": "fts", "query": "urgent" },
  "matches": [...],
  "total": 3
}

GET /v1/automation-logs #

Get automation execution logs with pagination.

Query Parameters:

Parameter Required Default Description
limit No 50 Max results per page
cursor No Pagination cursor
ruleId No Filter by rule ID
status No Filter by status

Example:

curl "http://localhost:11023/v1/automation-logs?limit=10&ruleId=auto_abc"

Response:

{
  "logs": [...],
  "total": 25,
  "nextCursor": "...",
  "hasMore": true
}

POST /v1/import-url #

Import a markdown document from a URL. Automatically extracts YAML frontmatter.

Request Body:

{
  "collection": "articles",
  "url": "https://example.com/post.md",
  "key": "imported-post",
  "lang": "en",
  "meta": { "source": ["web"] },
  "ttl": 86400
}
Field Type Description
collection string Required. Target collection
url string Required. URL to fetch
key string Document key (derived from URL path if empty)
lang string Required. Language code
meta object Metadata (merged with frontmatter)
ttl integer Time-to-live in seconds

Response: Saved document object. The call lifts the HTTP write deadline for its own response: a slow remote server no longer costs the client the answer.


POST /v1/import-wiki #

Import Wikipedia (MediaWiki) XML dumps. Supports .xml and .xml.bz2 compressed files. Streams the XML — does not load the entire file into memory. The call lifts the HTTP write deadline for its own response; an import that outlasted MDDB_HTTP_WRITE_TIMEOUT used to finish with the client seeing EOF.

Multipart Form Upload:

curl -X POST http://localhost:11023/v1/import-wiki \
  -F "file=@enwiki-20260101-pages-articles.xml.bz2" \
  -F "collection=wikipedia" \
  -F "lang=en" \
  -F "skipRedirects=true" \
  -F "skipFts=true"

Raw Stream (octet-stream):

curl -X POST "http://localhost:11023/v1/import-wiki?collection=wikipedia&lang=en&skipRedirects=true&skipFts=true" \
  -H "Content-Type: application/x-bzip2" \
  --data-binary @enwiki-20260101-pages-articles.xml.bz2
Field Type Description
collection string Required. Target collection
lang string Required. Language code (e.g. en, de, pl)
namespaces string Comma-separated namespace IDs to import (default: 0 = articles only)
skipRedirects bool Skip redirect pages (default: false)
skipFts bool Skip FTS indexing during import for speed (default: false). Run /v1/fts-reindex after.
maxPages int Maximum pages to import (default: unlimited)
batchSize int Pages per batch commit (default: 500)

Response:

{
  "imported": 1234567,
  "skipped": 456789,
  "failed": 0,
  "collection": "wikipedia",
  "durationMs": 3600000
}

Metadata stored per document: source=wikipedia, wiki_id, wiki_title, wiki_ns, wiki_rev_id, wiki_timestamp, wiki_contributor, wiki_redirect (if applicable).


POST /v1/set-ttl #

Set or remove document time-to-live.

Request Body:

{
  "collection": "blog",
  "key": "temp-post",
  "lang": "en",
  "ttl": 3600
}
Field Type Description
collection string Required. Collection name
key string Required. Document key
lang string Required. Language code
ttl integer Required. Seconds until expiry; 0 to remove TTL

Response: Updated document object with expiresAt field.


GET /v1/meta-keys #

List all unique metadata keys and their distinct values for a collection.

Query Parameters:

Parameter Required Description
collection Yes Collection name

Example:

curl "http://localhost:11023/v1/meta-keys?collection=blog"

Response:

{
  "meta": {
    "author": ["John", "Jane"],
    "category": ["blog", "tutorial"],
    "tags": ["golang", "database"]
  }
}

GET /v1/checksum #

Get a checksum of a collection's documents, to compare replicas or to see whether anything changed.

Every document contributes a 64-bit value derived from its whole key (collection, key, language) and its whole stored value (content, metadata, revision and timestamps as stored); the contributions are mixed and added, so the order documents are read in does not matter. Two nodes holding the same documents byte for byte report the same checksum; a document added, removed or changed on one of them changes it (except with a chance of about one in 2^64). It is not a cryptographic digest. The same figure is the checksum of each collection in /v1/stats.

Since 2.19.8 the checksum is 16 hex digits. Before, it was 8 digits from an XOR of CRC32 values over each key and the first 64 bytes of each value, which cancelled out: a follower missing 1,000 documents whose keys differed only in a counter reported the leader's checksum.

Query Parameters:

Parameter Required Description
collection Yes Collection name

Example:

curl "http://localhost:11023/v1/checksum?collection=blog"

Response:

{
  "collection": "blog",
  "checksum": "6f1d0c9a3be27c45",
  "documentCount": 42
}

GET /v1/system/info #

Returns system information including OS, memory, CPU, and network details.

Example:

curl http://localhost:11023/v1/system/info

Response:

{
  "hostname": "server-1",
  "os": "linux",
  "arch": "amd64",
  "numCPU": 4,
  "goVersion": "go1.27.4",
  "version": "2.19.13",
  "uptimeSeconds": 3600,
  "memoryTotal": 134217728,
  "memoryUsed": 67108864,
  "numGoroutines": 12,
  "cpuUsagePercent": 15.3
}

GET /v1/config #

Returns server configuration overview.

Values pass through the configuration allowlist the diagnose bundle uses : a URL is shown without credentials, query or fragment (https://user:key@host/v1 → https://host/v1); secrets are never part of this answer.

Example:

curl http://localhost:11023/v1/config

Response:

{
  "version": "2.19.13",
  "databasePath": "mddb.db",
  "mode": "wr",
  "protocols": {
    "http": { "enabled": true, "addr": ":11023" },
    "grpc": { "enabled": true, "addr": ":11024" },
    "mcp": { "enabled": true, "addr": ":11025" }
  },
  "authEnabled": false,
  "metricsEnabled": true,
  "vectorConfig": {
    "enabled": true,
    "provider": "openai",
    "model": "text-embedding-3-small",
    "dimensions": 1536
  },
  "automationsEnabled": true,
  "searchStatsEnabled": true,
  "esCompat": { "enabled": true, "prefix": "/es" },
  "searchMaxLimit": 1000,
  "telemetry": { "enabled": true, "endpoint": "https://collector.internal:4318" },
  "clientAddressing": { "trustedProxies": 2, "header": "X-Forwarded-For", "proxyProtocol": false }
}

Search surface, tracing and proxies:

Field Source Meaning
esCompat.enabled, esCompat.prefix MDDB_ES_COMPAT Whether the Elasticsearch-compatible subset is served, and under which path (always /es)
qdrantCompat.enabled, qdrantCompat.prefix MDDB_QDRANT_COMPAT (2.19.10) Whether the Qdrant-compatible point query is served, and under which path (always /qdrant)
searchMaxLimit MDDB_SEARCH_MAX_LIMIT The most results one search returns (default 1000); a collection's retrieval.maxTopK can only lower it
telemetry.enabled, telemetry.endpoint MDDB_OTEL_ENDPOINT Whether traces are exported, and the collector's scheme and host only — never a path, query or credentials. Omitted when tracing is off
clientAddressing.trustedProxies MDDB_TRUSTED_PROXIES How many proxy entries are trusted, never which: the addresses describe the operator's network
clientAddressing.header MDDB_CLIENT_IP_HEADER The header a trusted proxy carries the client address in (canonical form; default X-Forwarded-For)
clientAddressing.proxyProtocol MDDB_PROXY_PROTOCOL Whether the TCP listeners accept a PROXY protocol header

The diagnose bundle renders the same fields with its stricter rules: the collector endpoint becomes <set: https>.


GET /v1/endpoints #

Returns list of all available endpoints across HTTP, gRPC, and MCP protocols.

Example:

curl http://localhost:11023/v1/endpoints

Response:

{
  "http": [
    { "method": "POST", "path": "/v1/add", "description": "Add document", "requiresAuth": true }
  ],
  "grpc": [
    { "name": "AddDocument", "description": "Add a document" }
  ],
  "mcp": [
    { "name": "add_document", "description": "Add a document" }
  ]
}

GET /v1/mcp/config #

A starting MCP configuration file for this server, as YAML (Content-Type: text/yaml). The panel's LLM Connections page offers it as a download. It fills in the listen addresses from MDDB_ADDR and MDDB_GRPC_ADDR, and lists the custom_tools block commented out. Only GET is accepted; other methods get 405.

Permission: with auth on, any authenticated caller.

curl http://localhost:11023/v1/mcp/config -o mcp-config.yaml

Response (abridged):

mcp:
  # Set listenAddress to run MCP on a dedicated port.
  # Omit to embed MCP on the HTTP API port (:11023).
  # listenAddress: "0.0.0.0:9000"

mddb:
  grpcAddress: "localhost:11024"
  restBaseUrl: "http://localhost:11023"
  # grpc_only | rest_only | grpc_with_rest_fallback | rest_with_grpc_fallback
  transportMode: "grpc_with_rest_fallback"
  timeoutSeconds: 2
  maxRetries: 1

# custom_tools:
#   - name: "semantic_search"
#     ...

The custom tools format is in CUSTOM-TOOLS.


Endpoints documented on topic pages #

These routes are served by the same HTTP listener and pass the same access gate, but their full reference lives with the feature. The machine-readable contract for all of them is openapi.yaml. "Permission" is what the SEC-019 gate requires when MDDB_AUTH_ENABLED=true: read/write on the collection the request names (on * when it names none), "global admin" for admin on *, "authenticated" for any valid token or API key. See AUTHENTICATION for the rules.

Method Path Permission Reference
GET /v1/events authenticated; each event is filtered by read on its collection SSE
POST /v1/geo-search read GEOSEARCH
POST /v1/geo-within read GEOSEARCH
POST /v1/geo-polygon read GEOSEARCH
POST /v1/geo-reindex global admin GEOSEARCH
GET /v1/geo-stats read on * (reports every collection) GEOSEARCH
POST /v1/geo-encode authenticated (no collection) GEOSEARCH
POST /v1/geo-decode authenticated (no collection) GEOSEARCH
GET, POST, DELETE /v1/mcp/keys global admin MCP
POST /v1/mcp/keys/disable global admin MCP
GET /v1/replication/status authenticated REPLICATION
POST /v1/replication/promote global admin CLUSTER
POST /v1/replication/demote global admin CLUSTER
GET /v1/placement global admin CLUSTER (v2.19.8+; answered by the meta group's leader)
POST /v1/placement/move global admin CLUSTER (v2.19.8+; answered by the meta group's leader)
POST /v1/spell-suggest read SYMSPELL (needs MDDB_SPELL=true)
POST /v1/spell-cleanup read SYMSPELL (needs MDDB_SPELL=true)
GET, PUT, DELETE /v1/spell-dictionary read for GET, write otherwise SYMSPELL (needs MDDB_SPELL=true)
POST /v1/temporal/query read TEMPORAL-TRACK (needs MDDB_TEMPORAL=true)
POST /v1/temporal/hot read TEMPORAL-TRACK (needs MDDB_TEMPORAL=true)
POST /v1/temporal/histogram read TEMPORAL-TRACK (needs MDDB_TEMPORAL=true)
GET /v1/tenants global admin MULTI_TENANCY (v2.19.8+)
GET, PUT, DELETE /v1/tenants/{id} GET: global admin or the tenant's own admin; PUT, DELETE: global admin MULTI_TENANCY (v2.19.8+)
GET /v1/tenants/{id}/usage global admin or the tenant's own admin MULTI_TENANCY (v2.19.8+)

Without MDDB_SPELL or MDDB_TEMPORAL the spell and temporal routes answer 404 with a JSON body naming the module that is off (2.19.0+; before, the mux's plain-text 404 page not found):

{"error": "feature disabled", "feature": "temporal"}

Two more groups are off by default and registered only when switched on:

Method Path Permission Reference
GET, POST, PUT, DELETE /es, /es/ (the Elasticsearch-compatible subset) per index in the path, as the matching /v1 call ELASTICSEARCH-COMPAT (needs MDDB_ES_COMPAT=true)
GET, POST /qdrant, /qdrant/ (the Qdrant-compatible point query, 2.19.10+) read on the collection in the path QDRANT_COMPAT (needs MDDB_QDRANT_COMPAT=true)
GET /debug/pprof/, /debug/pprof/cmdline, /debug/pprof/profile, /debug/pprof/symbol, /debug/pprof/trace global admin Go's net/http/pprof; config (needs MDDB_PPROF_ENABLED=true)

GET /health #

Health check endpoint. Also available at /v1/health.

Response:

{
  "status": "healthy",
  "mode": "wr"
}

Returns 503 with "status": "unhealthy" if the database is not accessible.

The database check waits at most 2 s. While the database is busy — a write growing the file waits for long reads to end, and no read can begin meanwhile — the answer is 200 with "status": "busy" and databaseWaitSeconds; after MDDB_HEALTH_STALL_LIMIT seconds (300) it is 503 with "status": "stalled". See HEALTHCHECK.

Since v2.19.8 vectorIndexCheckpoints (fromDisk, rebuilt, partial) counts the collections whose vector indexes were read from their checkpoint at the last load, built from the stored vectors, or partly both; absent when checkpoints are off or nothing was loaded yet (SEARCH).


POST /v1/auth/register #

Register a new user. Requires admin privileges.

Request Body:

{
  "username": "newuser",
  "password": "secret123"
}

Response:

{
  "username": "newuser",
  "createdAt": 1709100000
}

GET /v1/auth/me #

Get current authenticated user information.

Response:

{
  "username": "admin",
  "admin": true,
  "createdAt": 1709000000
}

GET/POST/DELETE /v1/auth/permissions #

Get, set or remove user permissions on collections. Requires admin privileges.

GET — Query parameter username:

curl "http://localhost:11023/v1/auth/permissions?username=john"

POST — Set permission:

{
  "username": "john",
  "collection": "blog",
  "read": true,
  "write": true,
  "admin": false
}

Response (POST): { "status": "ok" }

DELETE (2.19.9+) — remove one grant; query parameters username and collection (* for the wildcard grant). The user's other grants stay, and tokens issued before the removal lose the grant on their next request:

curl -X DELETE "http://localhost:11023/v1/auth/permissions?username=john&collection=blog"

Response (DELETE): { "status": "ok" }; 400 without both parameters, 404 permission not found, 409 cannot remove your own global admin when an admin removes their own admin on * (AUTHENTICATION).


GET /v1/auth/users #

List all users. Requires admin privileges.

Response:

{
  "users": [
    {
      "username": "admin",
      "createdAt": 1709000000,
      "disabled": false,
      "admin": true,
      "groups": ["admins"]
    }
  ]
}

DELETE /v1/auth/users/:username #

Delete a user account. Requires admin privileges.

Example:

curl -X DELETE http://localhost:11023/v1/auth/users/john

Response: { "status": "deleted" }


GET/POST /v1/auth/groups #

List all groups (GET) or create a new group (POST). Requires admin privileges.

POST — Create group:

{
  "name": "editors",
  "description": "Content editors",
  "members": ["john", "jane"]
}

Response (POST): Created group object (201 Created).


GET/PUT/DELETE /v1/auth/groups/:name #

Manage a specific group. Requires admin privileges.

  • GET returns the group object
  • PUT updates description and members
  • DELETE removes the group

GET/POST/DELETE /v1/auth/group-permissions #

Get, set or remove permissions for a group on collections. Requires admin privileges.

GET — Query parameter group:

curl "http://localhost:11023/v1/auth/group-permissions?group=editors"

POST — Set group permission:

{
  "groupName": "editors",
  "collection": "blog",
  "read": true,
  "write": true,
  "admin": false
}

Response (POST): { "status": "permission set" }

DELETE (2.19.9+) — remove one grant; query parameters group and collection. The group and its other grants stay:

curl -X DELETE "http://localhost:11023/v1/auth/group-permissions?group=editors&collection=blog"

Response (DELETE): { "status": "ok" }; 400 without both parameters, 404 permission not found.


Data Models #

Document #

{
  "id": string,              // Auto-generated: "collection|key|lang"
  "key": string,             // Document key (e.g., "homepage")
  "lang": string,            // Language code (e.g., "en_GB")
  "meta": {                  // Metadata (multi-value)
    "key1": ["value1", "value2"],
    "key2": ["value3"]
  },
  "contentMd": string,       // Markdown content
  "addedAt": int64,          // Unix timestamp (first creation)
  "updatedAt": int64         // Unix timestamp (last update)
}

Metadata #

  • Metadata is stored as map[string][]string (key → array of values)
  • Each metadata key can have multiple values
  • Metadata is automatically indexed for fast searching
  • Common metadata keys: category, author, tags, status, etc.

Code Documents #

MDDB stores source the same way it stores prose: one document per file, with no new type, table or endpoint. What changes is how the text is tokenised, and that is decided by a convention on the ordinary flat meta map.

Meta key Value Effect
kind code Index with the source-aware tokeniser
language css, html, javascript, … The source language; inferred from the extension when absent
path css/style.css The original path, when the document key is a slug
{
  "collection": "theme",
  "key": "css/style.css",
  "lang": "en",
  "contentMd": ".hero-banner { background: url(hero.png); }",
  "meta": { "kind": ["code"], "language": ["css"] }
}

The convention is optional. A document whose key or path ends in a known source extension (.css, .html, .js, .ts, .go, .py, …) is treated as code without any meta at all, so a theme ingested by an existing tool indexes usefully as it stands. An explicit kind always wins, in both directions: set kind: ["prose"] on a .css document and it is tokenised as prose.

Finding the place, not just the file #

A search result that names the document answers "which file". The question an agent has is "where" — and answering it by reading the file is what makes a one-line change cost thousands of tokens (issue #192).

Ask for highlight: true and every fragment carries the lines it occupies:

{
  "results": [{
    "document": { "key": "css/style.css" },
    "highlights": [{
      "fragment": "…}\n\n.hero-banner {\n  <mark>background</mark>: url(hero.png);",
      "startLine": 158,
      "endLine": 163,
      "startOffset": 4021,
      "endOffset": 4104
    }]
  }]
}

startLine and endLine are 1-based and inclusive. Byte offsets are still there for callers doing their own markup on the same bytes.

Combine it with a projection. fields drops the document body, highlight says where to look; together they answer without carrying the file. The whole response above is under 800 bytes for a 164-line stylesheet. The two are deliberately compatible — a projection keeps the fragments.

fragmentSize is a byte budget tuned for prose. Source lines are short, so 150 bytes covers roughly fifteen lines of CSS against two or three of prose; lower it when searching code.

Vector and hybrid hits carry the same information: in chunk and window retrieval modes each result reports startLine/endLine for the passage it matched, widened along with the passage when a window is requested.

Chunking #

Embedding chunks are the unit a vector search returns, and the prose chunker splits on paragraphs with a sentence fallback. A period inside url(a.png) is not the end of a sentence, so a split there leaves half a declaration in each chunk — a passage that reads as nothing and embeds as noise.

Code documents are segmented on bracket depth instead: a chunk may only end where {}, () and [] are balanced, so one chunk is roughly one CSS rule or one function. Braces inside strings and comments do not count.

Source Boundary preferred
Blank line at depth zero A rule or function just ended — the cleanest cut
Any line end at depth zero Over budget, but the construct closed
A construct larger than the budget Kept whole and oversized — half a function is worth nothing
A minified single line Cut after the last balanced } within budget

Mode selection follows the document: kind: ["code"] (or a known source extension) chunks as code, anything else as prose. MDDB_EMBEDDING_CHUNK_MODE=code|prose overrides it for a whole server, for collections whose documents were ingested without the convention.

Re-embed code collections after upgrading. Chunks are re-derived rather than stored — only the index is kept — so a document embedded under prose chunking and read under code chunking will return the wrong passage. Run vector_reindex (or POST /v1/vector-reindex) on any collection holding source. Prose collections are unaffected: their segmentation is unchanged, byte for byte.

Structured frontmatter and flat meta #

MDDB's metadata is flat, on purpose: map<string, repeated string>, the same shape in proto, REST, GraphQL and MCP. Every filter, facet and index in the system assumes it.

Structured frontmatter does not fit. An SSG page with

faq:
  - question: Is it free?
    answer: Yes, it is free.
  - question: Is there a trial?
    answer: No.

has nowhere to go, and an importer that reaches for Go's %v produces

faq: ["[map[answer:Yes, it is free. question:Is it free?] map[answer:No. question:Is there a trial?]]"]

MDDB stores that faithfully — it is a valid string — and the damage surfaces much later, in a template that cannot render it (issue #187).

Three ways to handle it. Pick by what you need to query, not by what is least work at import time:

Pattern Looks like Round-trip Filterable
JSON in one value faq: ["[{\"question\":…}]"] Lossless No — one opaque string
Flattened keys faq.0.question: ["Is it free?"] Lossless if the shape is fixed Yes, per leaf
Leave it in the body The markdown keeps its frontmatter Lossless No, but full-text searchable

JSON in one value is the usual answer: nothing is lost, and the consumer parses it once. Flatten only the leaves you actually filter on — faq.0.question is queryable, but the numbering makes reordering the source a metadata migration. Leaving the block in the markdown body costs nothing and stays findable through full-text search; choose it when nothing queries the structure.

MDDB's own frontmatter reader (/v1/upload, /v1/ingest with extractFrontmatter, /v1/import-url, mddb-cli add, mddb-cli autoindex) reads flat keys only: a scalar, a comma list, a [flow, list] or a block list of - item lines (2.19.0+; before, a flow list kept its brackets and a block list was dropped). A - key: value item is a map and is not stored, so the faq above does not arrive as garbage; to keep it, use one of the patterns above, or mddb-cli add --no-frontmatter to leave it in the body.

The validator warns, it does not reject. POST /v1/validate (and the gRPC, GraphQL and MCP equivalents) returns a warnings list alongside errors when a value looks like Go stringification:

{
  "valid": true,
  "errors": [],
  "warnings": ["meta.faq: looks like a Go-stringified list of objects (`[map[...] map[...]]`). …"]
}

It stays a warning because such a value is a valid string, and MDDB has no business deciding a string is not what its author meant — a caller storing prose about map[string]int is doing nothing wrong. The lint runs even when a collection has no schema, which is precisely the case an unstructured import lands in.

Symbols: which file declares this? #

Full-text search cannot tell a declaration from a mention. Search a theme for .hero-banner and the stylesheet that defines it ranks alongside every template that merely applies it — and the template usually wins, because it repeats the name more often.

Every code document therefore gets three extra meta keys, filled from its own content on each save:

Key Holds Example (CSS)
defines What this file declares .hero-banner, #nav, --brand
uses What it references but does not declare /images/hero.png
imports What it pulls in reset.css

They are ordinary values in the existing flat meta map, so the metadata filter already answers the question — no new query surface, no schema change:

# The file that declares the selector, not the twelve that apply it.
curl -s "$MDDB/v1/fts?collection=theme&q=hero-banner&meta.defines=.hero-banner"

# Everything that would break if that stylesheet were deleted.
curl -s "$MDDB/v1/fts?collection=theme&q=*&meta.uses=.hero-banner"

Which languages get what. A document is code when its key has one of these extensions (or meta.language says so). Every code document is tokenised for full-text search as code; the languages with symbols also get the three keys above and edges in the connection graph.

Language Extensions Code search Symbols Graph edges
C .c .h ✅ ✅ calls, imports
C++ .cc .cpp .cxx .hpp .hh .hxx ✅ ✅ calls, imports
Assembly .s .S .asm ✅ ✅ calls, imports
Go .go ✅ ✅ calls
Rust .rs ✅ ✅ calls, imports
Java .java ✅ ✅ calls, imports
Python .py ✅ ✅ calls, imports
Ruby .rb ✅ ✅ calls, imports
PHP .php ✅ ✅ calls, imports
JavaScript .js .mjs .cjs .jsx ✅ ✅ imports
TypeScript .ts .tsx ✅ ✅ imports
HTML .html .htm ✅ ✅ uses-selector, imports
CSS / SCSS / Sass / Less .css .scss .sass .less ✅ ✅ uses-selector, imports
Terraform .tf .tfvars ✅ ✅ references
Kubernetes / OpenShift manifests, Kustomize .yaml .yml ✅ ✅ references, imports
Ansible playbooks, task and handler files .yaml .yml ✅ ✅ references, imports
Shell .sh .bash ✅ — —
SQL .sql ✅ — —
M4 .m4 ✅ — —
Other YAML, JSON, TOML, XML, SVG .yaml .yml .json .toml .xml .svg ✅ — (data, not code) —

A YAML file is read by its shape, not its name: a document with apiVersion and kind is a Kubernetes object (an OpenShift Route or DeploymentConfig is one too), a document that is a list is Ansible, and anything else — a CI workflow, a compose file — gets no symbols. A Helm template does not parse as YAML and gets none either.

Go imports name packages, which are directories rather than documents, so they are recorded in imports and can be filtered on, but produce no edge.

What each language contributes:

Language defines uses imports
CSS / SCSS / LESS Selectors, their component classes and ids, --custom-properties url(...) targets @import targets
JavaScript / TypeScript Function, class, and arrow-const names — import and require specifiers
HTML id attributes class names, on* handler names Local src / href targets
C / C++ (.c .h .cc .cpp .hpp …) Function definitions, static prototypes, struct/union/enum tags, typedef names, #define macros, file-scope variables Functions and macros called in function bodies that the file does not define #include targets
Assembly (.S .s .asm) ENTRY(x) and similar macros, .globl symbols call / bl / jal targets #include targets
Go Functions, methods, type names Functions called that the file does not define Import paths (fmt, net/http)
Rust fn, struct, enum, trait, type, union, macro_rules! Functions and macros called that the file does not define use paths as written, extern crate, mod x; as the file beside it
Java Classes, interfaces, enums, records, methods Methods called and classes created with new import a.b.C as a/b/C
Python def and class Functions and classes called that the file does not define import a.b as a/b; from .x import y as ./x
Ruby def, class, module Methods called and Name.new require as written, require_relative from the file
PHP Functions, classes, interfaces, traits, enums Functions called, classes created with new, Class::method() require/include from the file (__DIR__ . '/x.php' too), use namespaces as written
Terraform aws_instance.web, data.aws_ami.ubuntu, module.vpc, var.region, output.ip, local.tags — the way code refers to them var., local., module., data. and resource references the file does not declare, inside "${...}" too Module source (./modules/vpc from the file, registry addresses as written)
Kubernetes / OpenShift Kind/name of each object (Deployment/web) ConfigMap/…, Secret/…, PersistentVolumeClaim/…, ServiceAccount/… and Ingress Service/… it refers to, and any {kind, name} pair: a Route's to, roleRef, subjects, scaleTargetRef A Kustomization's resources, bases, components and patches
Ansible Task and handler names, listen topics notify include_tasks, import_tasks, import_playbook, include_vars, vars_files from the file; roles as roles/NAME

Calls through a value are left out in every language — obj.f(), $this->f(), pkg.F(), Type::f() — because the text alone cannot say which file defines them. A method and a package function look the same.

C details. A non-static prototype is a declaration of something defined elsewhere, so it is not a define — otherwise every header would claim every function it declares. An all-capitals name invoked at file scope (REGISTER_HANDLER(...), DEFINE_COMMAND(...) { }) is a macro, not a function: its body still contributes calls, and a variable declared with a macro type (static LIST_HEAD(, conn) idle_conns;) is a define. Calls through a struct member (ops->start()) are not global symbols and are left out. Checked on a large open-source C codebase: 15,617 files in about 5 seconds, and for a widely included header the extractor and grep agree on the same 730 files.

#include "x.h" resolves next to the including file. #include <net/conn.h> resolves against the collection's include paths, as a compiler's -I does — set them in the collection config:

curl -X PUT "$MDDB/v1/collection-config" -H 'Content-Type: application/json' \
  -d '{"collection":"myproject","code":{"includePaths":["src"]}}'

With ["src"], <net/conn.h> in any file is recorded as src/net/conn.h and matches that document's key. Without include paths it is taken as collection-relative (net/conn.h), which suits a tree keyed from its include root. Set them before loading: documents written earlier keep their imports until they are written again.

Chunk size per collection. MDDB_EMBEDDING_CHUNK_SIZE is one number for the whole server, and 1500 characters suits prose but cuts a long C function in two. A collection can set its own size and mode:

curl -X PUT "$MDDB/v1/collection-config" -H 'Content-Type: application/json' \
  -d '{"collection":"myproject","embedding":{"chunkSize":4000,"chunkMode":"code"}}'

chunkSize is 100–100000 characters, or 0 for the server's size. chunkMode is code, prose, or empty to decide per document. The setting covers documents embedded afterwards and the passages search returns for them; vectors already stored keep their chunks until POST /v1/vector-reindex with "force": true. GET /v1/vector-stats reports each collection's effective chunkSize. The same object is embedding in MCP set_collection_config (chunk_size, chunk_mode) and in gRPC SetCollectionConfig.

Full-text indexing per collection. Postings are usually most of the file. A collection searched only by metadata or vectors can turn them off; POST /v1/fts-reindex then removes the ones it has ("status": "removed"), and full-text and hybrid search find nothing in it:

curl -X PUT "$MDDB/v1/collection-config" -H 'Content-Type: application/json' \
  -d '{"collection":"vectors-only","fts":{"enabled":false}}'

Meta keys kept out of full-text search. Every meta key is a BM25F field meta.<key> with its own postings. Keys that are only ever filters can stay out: fts.excludeMetaKeys lists them, and changing them then costs no full-text work at all. filterMeta, filter and facets still work on them; they read the metadata index, not the full-text one. The list names exceptions rather than the keys to index, so a meta key added later is searchable without a config change.

curl -X PUT "$MDDB/v1/collection-config" -H 'Content-Type: application/json' \
  -d '{"collection":"ports","fts":{"excludeMetaKeys":["url","license","vulnerable"]}}'
curl -X POST "$MDDB/v1/fts-reindex" -d '{"collection":"ports"}'

The list applies to documents written after it is set. After changing it, run POST /v1/fts-reindex: postings already written stay until then, and a key taken off the list is not indexed for existing documents until then. The fts block is replaced as a whole, so send enabled and excludeMetaKeys together. MCP set_collection_config takes it as fts.exclude_meta_keys, gRPC as CollectionFTSProto.exclude_meta_keys.

Three deliberate limits:

  • The extractor owns these keys. They are rewritten on every save and removed when a document stops being code, so they always describe the current content. A hand-supplied defines will not survive the next write — a stale one would point graph queries at a document that no longer exists.
  • Scanners, not parsers. Regex and a brace walker, which is why minified files, @media blocks, and SCSS nesting all work, and why a class name built at runtime (`btn-${size}`) is not found. A missing edge costs a search; a wrong one costs trust.
  • Capped and sorted. At most MDDB_CODE_MAX_SYMBOLS (default 512) per key, deduplicated and sorted. The output is deterministic because these bytes travel through the replication binlog: the same document must produce the same meta on every replica.

Only new writes are enriched. Re-save (or bulk re-ingest) an existing code collection to populate symbols for documents stored before this version.

Semantic code facts #

defines/uses come from scanners. Precise answers — where a symbol is defined, every line that references it, which types implement an interface — need a language server, and mddbd neither runs one nor has the checkout. mddb-cli autoindex --semantic does both and sends what it learnt with each code document as four meta keys (v2.19.3+, opt-in; without the flag nothing changes):

Key One value
symIndex v1 <contentHash> <factsDigest> <source>[ truncated] — exactly one
symDefs <name> <kind> <start>-<end>[ <container>]
symRefs <defPath>#<name> <line>,<line>,... (at most 64 lines per value)
symImpls <ifacePath>#<name> <localName>

The full format, with the shared test cases the server and the CLI both run, is testdata/semantic-facts/README. What the server does with them on every write (add, batch, bulk ingest, update, from any transport):

  • Facts describe one content. contentHash is the first 12 hex digits of SHA-256 over the content as stored. When it does not match — the content was edited after the facts were computed — every sym* key is dropped, and so it is for a document that is not code or has no valid symIndex. A meta-only update that sends the keys back, a TTL change or an updateWhere keeps them.
  • Malformed values are dropped, the rest kept, sorted. A value is at most 1024 bytes and never contains |, so a large one cannot break the write.
  • Capped. At most MDDB_CODE_MAX_FACTS (default 4096) values across the three keys: definitions first, then implementations, then references; symIndex then ends in truncated.
  • Hidden from results. Full-text, vector (graph neighbours and pending documents included), hybrid and cross-collection search, curated pins, metadata search and listing leave the sym* keys out on every transport (REST, gRPC, GraphQL, MCP); a hit would otherwise carry hundreds of reference lines. Reading one document (POST /v1/get, gRPC Get, GraphQL document, MCP get_document_meta) returns them, as does export. Metadata filters and facets work on them like on any key, but the format is not an API to build on: it may become v2.

GET /v1/code-languages lists the languages the CLI computes facts for in semantic ({"c": true, "cpp": true, "go": true, "php": true, "python": true, "rust": true}).

The connection graph #

Symbols answer "which file declares this". The graph answers the questions that follow: what breaks if I change .hero-banner, which pages load checkout.js, what does nothing reference any more.

Nothing is stored. Edges are derived at query time from the defines/uses/ imports meta through the same metadata index — uses on one side matched against defines on the other, an import path matched against a document key. That is deliberate: an edge is a statement about two documents, and storing it means one copy per side, which drift apart the moment someone edits only one of them. Deriving makes a reindex reproduce the graph exactly.

# What breaks if this stylesheet changes?
curl -s "$MDDB/v1/code-graph?collection=theme&key=theme/style.css&direction=in"

# What does this page pull in, two hops out?
curl -s "$MDDB/v1/code-graph?collection=theme&key=theme/index.html&direction=out&depth=2"
{
  "root": "theme/style.css",
  "nodes": [
    { "key": "theme/style.css",  "language": "css",  "depth": 0 },
    { "key": "theme/index.html", "language": "html", "depth": 1 }
  ],
  "edges": [
    { "from": "theme/index.html", "to": "theme/style.css",
      "kind": "uses-selector", "symbol": ".hero-banner", "direction": "in" }
  ],
  "truncated": false
}

direction is in, out or both (the default). An edge is one statement about two documents — from depends on to through symbol — and is listed once. Its direction says which way the walk found it: out from the document that depends, in from the one depended on. With both and depth above 1 the walk meets an edge from both ends; the direction kept is the one found first, the hop nearer the root (before 2.19.0 such an edge was listed twice, once each way).

Every edge carries the symbol that justifies it. Without it the answer is only "these two files are related", which is not actionable; with it, the caller knows what to look at. Add &lines=true to get the first line the symbol appears on for both sides — off by default, because it is the only part of a traversal that reads document content.

Four kinds of edge:

Kind Meaning Derived from
uses-selector A template applies a class or id a stylesheet declares uses ↔ defines
calls A file calls a function or macro another file defines: C, C++ and assembly; Go, Rust, Java, Python, Ruby and PHP uses ↔ defines
references A configuration file names what another declares: a Deployment its ConfigMap, a Terraform output its resource, an Ansible notify its handler uses ↔ defines
imports A document pulls another in by path or #include imports ↔ document key

The uses ↔ defines kind is named by the language of the document doing the using, so a C file calling into assembly is a calls edge and a YAML or Terraform file naming an object is a references edge.

Import paths are resolved against the referring document when it is stored, so href="style.css" inside theme/index.html is recorded as theme/style.css and matches a key directly. One language-specific rule: in HTML and CSS a bare path is relative to the document — which is what makes <link> and @import produce edges at all — while in JavaScript a bare import "lodash" names a package, and rewriting it to theme/lodash would invent an edge to a document that will never exist. Go, Rust, Java, Python, Ruby and PHP follow the JavaScript rule: a bare name is a package or a module on the load path, and an import relative to the file is written ./x. An import without an extension is matched against the code extensions (./models finds models.py).

Three limits, and one of them is reported back:

  • Depth 1–3, default 1. A value above the maximum is clamped, not rejected.
  • At most 100 neighbours per node. A selector such as .title appears in nearly every template, so an unbounded walk of a real theme returns the theme.
  • truncated says whether a limit cut the walk short. "Nothing depends on this" is only safe to act on when truncated is false — which is exactly the answer you need before deleting a file.

Resolution stays inside one collection: a theme is a collection, and a selector shared with an unrelated collection is a coincidence, not a dependency.

The same traversal is available through all three surfaces — GET/POST /v1/code-graph, the code_graph MCP tool (annotated read-only), and the codeGraph GraphQL query — and a test pins that they agree, so they cannot drift apart in what the graph says.

One symbol, everywhere it matters #

GET /v1/symbol?collection=<c>&name=<symbol> (or POST with the same fields as JSON) answers what an agent asks before changing a function, a type or a selector: where it is defined, where it is used and from inside which definition, what it calls, which tests touch it and what lives next to it. Every entry is a passage — path, line range, the definition holding it — so the answer is a list of places to read, not documents to read through.

curl -s "$MDDB/v1/symbol?collection=repo&name=SearchHybrid&include=definitions,callers,tests"
{
  "collection": "repo",
  "symbol": "SearchHybrid",
  "definitions": [{"path": "internal/search/query.go", "lines": {"start": 4, "end": 7},
                   "symbol": "SearchHybrid", "kind": "function", "source": "definitions", ...}],
  "callers": [{"path": "cmd/tool.go", "lines": {"start": 3, "end": 5}, "symbol": "run", ...}],
  "tests": [{"path": "internal/search/query_test.go", "lines": {"start": 4, "end": 4},
             "symbol": "TestSearchHybrid", "content": "SearchHybrid(\"x\")", ...}]
}
Relation Derived from
definitions Documents whose defines holds the name; the span from the definition's first line to the brace, dedent or end that closes it
references Every line using the name in code (comments and prose excluded), with the definition it sits in as symbol; for a function or method only lines that call it
callers The definitions holding the references — callers found without a call parser
callees Names called inside the definition's span, at their own definitions
tests References in test files (_test.go, test_*.py, *.spec.ts, *Test.java, _spec.rb, tests/ …)
siblings Other top-level definitions in the same directory

include limits the relations, limit caps each one (default 20, max 200), and includeContent=true adds the text of definitions, callers and callees — references always carry their line.

(v2.19.13) excludeTests: true (excludeTests=true on GET) leaves out every passage in a test file before limit is applied. path may name a directory (internal/session): the answer then keeps the definitions under it. A file path picks a definition in that file, as before.

curl -s -X POST "$MDDB/v1/symbol" -d '{"collection": "repo", "name": "Close",
  "path": "internal/net", "include": ["references"], "excludeTests": true, "limit": 5}'

limit applies to each relation separately, not to the response: limit=20 with all seven relations returns up to 140 passages. candidates is cut to limit too. The response has no total. truncated is one flag for the whole response: true when at least one relation (or candidates) held more than limit, or when a lookup stopped at its scan bound of 500 documents or facts. It is left out when nothing was cut. (v2.19.13) totals says which relations the limit cut and how many passages each had before it, for example "totals": {"references": 32}; a relation missing from it is complete, unless the scan bound was reached. Before 2.19.13 a list exactly limit long could be the cut one or not. To see more of one relation, ask for it alone (include=references) with a higher limit. When the server's cap (MDDB_SEARCH_MAX_LIMIT, the collection's maxTopK) lowered the requested limit, the response also carries limit (the per-relation limit used) and limitCapped: true; truncated is then judged against that lower limit. Candidates come from the metadata index (defines, uses) and, for uses the extractor cannot see such as x.Method(), from the full-text index; spans are computed from the documents at query time, so nothing is stored and a reindex cannot make the answer drift. The same lookup is the code_symbol MCP tool (read-only, toolset code) and the codeSymbol GraphQL query.

Precise answers from semantic facts (v2.19.3+)

Documents indexed with mddb-cli autoindex --semantic carry a language server's facts (symIndex, symDefs, symRefs, symImpls; format). Where they do, the same endpoint answers from them:

  • name may be qualified (Conn.Close); a bare name (Close) finds every definition whose qualified name ends in it.
  • path (new, optional) picks the definition in one file (meta.path).
  • A bare name with several definitions and no path returns them all with ambiguous: true and candidates (path, qualified name, kind); ask again with a candidate's name and path.
  • References, callers, callees and implementations are read from the facts, and each passage's target (<path>#<qualified name>) says which definition it belongs to — two Close methods get two separate lists. Definition passages also carry container (the type holding a method).
  • include=implementations (new relation) lists the types implementing an interface, at their definitions. It needs facts; without them the list is empty.
  • precision: semantic (every definition and use came from facts), mixed (facts for some files, text matching for the rest), heuristic. It is left out of a heuristic answer to a request that uses neither path nor implementations, so a collection without facts answers exactly as before. semanticSource names the language server (gopls/0.24.0).

In a mixed collection, files without facts are answered as before, and a text match in a file that has facts is dropped when the facts define the name: the facts list every real use, so the match is a namesake.

curl -s "$MDDB/v1/symbol?collection=repo&name=Close&path=internal/net/conn.go&include=definitions,references"
{
  "collection": "repo",
  "symbol": "Close",
  "definitions": [{"path": "internal/net/conn.go", "lines": {"start": 5, "end": 7},
                   "symbol": "Conn.Close", "kind": "method", "container": "Conn", ...}],
  "references": [{"path": "app/main.go", "lines": {"start": 4, "end": 4}, "symbol": "run",
                  "target": "internal/net/conn.go#Conn.Close", "content": "c.Close()", ...}],
  "precision": "semantic",
  "semanticSource": "gopls/0.24.0"
}

Spans by language:

Language Span ends at Kinds
Go, Rust, Java, C, C++, JavaScript, TypeScript, PHP the brace closing the body; a declaration without one spans its line function, method, type, class, impl, macro
Python where indentation returns to the definition's level function, class
Ruby the matching end method, class
CSS, SCSS, Sass, Less the rule's closing brace rule
Terraform the block's closing brace block
Assembly the line before the next label label
HTML, YAML no spans; a definition is placed on the line it first appears —

The heuristic level has no "implementations" (interfaces, traits, abstract classes): telling an implementation from a namesake needs type information a scanner does not have. A collection indexed with mddb-cli autoindex --semantic has it — see "Precise answers from semantic facts" above.

GET /v1/code-languages #

The extension → language table the server classifies source by: {"extensions": {".go": "go", ".tsx": "typescript", ...}, "languages": [...]}. mddb-cli autoindex reads it so a client marks files the way the server would.

Passages instead of documents #

/v1/fts, /v1/vector-search, /v1/hybrid-search and /v1/cross-search take "format": "passages" and "passageLines". The response is then {"passages": [Passage], "total", "contextTruncated"} — each passage a path, a line range, the definition holding it and its text — instead of documents. (v2.19.13) "passageTokens" (1 to 8000) bounds one passage; a passage cut around a hit holds at most 500 tokens by default. A passage over the bound loses context lines first, then the end of its hit line (marked […]), and carries "truncated": true; its lines are the lines returned. Chunks and vector hits are cut only when passageTokens is set. A hit on a Markdown heading returns the heading and the text under it. See SEARCH.md — Passages.

Why the tokeniser differs #

The prose tokeniser stems (classes → class), drops stop words (for, if, class — the keywords of the language being searched) and splits on every punctuation mark, which leaves .hero-banner findable only as two unrelated words. The code tokeniser keeps the whole identifier and emits its parts, across camelCase, snake_case and kebab-case:

In the source Indexed as
.hero-banner hero-banner, hero, banner
checkoutHandler checkouthandler, checkout, handler
XMLHttpRequest xmlhttprequest, xml, http, request
MAX_RETRY_COUNT max_retry_count, max, retry, count

Because both the whole name and its parts are indexed, a code collection is searchable with ordinary queries — nothing in the search path needs to know the collection holds source. The one asymmetry is stemming on the query side: a search for classes stems to class and will not match an unstemmed classes in a code index. Searching source for an English plural is rare enough to accept; searching it for class finds every declaration.

Single characters and digits are kept, unlike in prose: a is a real selector and h2 and utf8 are real names.

Error Handling #

Error Response Format #

{
  "error": "error message description"
}

HTTP Status Codes #

Code Description
200 Success
400 Bad Request - Invalid JSON or missing required fields
403 Forbidden - Write operation in read-only mode
404 Not Found - the document or revision does not exist (every path; some answered 400 before)
500 Internal Server Error

Common Errors #

Missing required fields:

{
  "error": "missing fields"
}

Document not found (404):

{
  "error": "document not found"
}

Read-only mode:

{
  "error": "read-only mode"
}

Best Practices #

1. Document Keys #

  • Use descriptive, URL-friendly keys
  • Keep keys consistent within a collection
  • Example: homepage, about-us, blog-post-1

2. Language Codes #

  • Use standard language codes (ISO 639-1 + ISO 3166-1)
  • Examples: en_US, en_GB, pl_PL, de_DE

3. Metadata #

  • Keep metadata keys consistent across documents
  • Use arrays even for single values (for consistency)
  • Index frequently queried fields

4. Collections #

  • Group related documents in collections
  • Use collections like database tables
  • Examples: blog, pages, products, docs

5. Revisions #

  • Regularly truncate old revisions to save space
  • Keep enough history for your audit requirements
  • Consider keeping 5-10 recent revisions

6. Backups #

  • Schedule regular backups
  • Store backups in a different location
  • Test restore procedures periodically

Performance Tips #

  1. Indexing: Metadata is automatically indexed - use it for filtering
  2. Pagination: Always use limit and offset for large result sets
  3. Batch Operations: Use export/import for bulk operations
  4. Revisions: Truncate old revisions regularly to keep database size manageable
  5. Read Mode: Use read-only mode for read-heavy workloads with separate write instances

Memory RAG Endpoints #

Conversational memory system for RAG applications. Store, search, and recall conversation history with semantic search.

POST /v1/memory/session #

Create a new memory/conversation session.

Request:

{
  "userId": "user-1",
  "scenario": "customer_support",
  "title": "Session about search API",
  "meta": {"department": "engineering"},
  "ttl": 2592000
}
Field Type Required Description
userId string Yes User identifier
scenario string No Session context/scenario
title string No Human-readable title (auto-generated if empty)
meta object No Additional metadata key-value pairs
ttl int No TTL in seconds (default: 30 days)

Response:

{
  "sessionId": "a1b2c3d4e5f6...",
  "userId": "user-1",
  "scenario": "customer_support",
  "title": "Session about search API",
  "createdAt": 1743400000,
  "expiresAt": 1745992000
}

POST /v1/memory/message #

Add a message to an existing session. Messages are automatically embedded for semantic recall.

Request:

{
  "sessionId": "a1b2c3d4e5f6...",
  "role": "user",
  "content": "How does vector search work?",
  "meta": {"topic": "search", "source": "docs"}
}
Field Type Required Description
sessionId string Yes Session ID from /v1/memory/session
role string Yes user, assistant, system, or tool
content string Yes Message content (markdown supported)
meta object No Extra metadata (topic, source, tool_call, etc.)

Response:

{
  "messageId": "memory_messages|...",
  "sessionId": "a1b2c3d4e5f6...",
  "role": "user",
  "createdAt": 1743400100,
  "embedded": true
}

POST /v1/memory/recall #

Semantically recall relevant messages from past conversations using hybrid search (vector + keyword).

Request:

{
  "query": "How does vector search work?",
  "userId": "user-1",
  "sessionId": "",
  "role": "assistant",
  "topK": 10,
  "threshold": 0.5,
  "strategy": "hybrid",
  "alpha": 0.5,
  "includeContent": true,
  "filterMeta": {}
}
Field Type Required Description
query string Yes Natural language recall query
userId string No Filter to sessions belonging to this user
sessionId string No Filter to a specific session
role string No Filter by message role
topK int No Number of results (default: 10)
threshold float No Min similarity score 0-1
strategy string No hybrid (default), semantic, keyword
alpha float No Weight 0-1 (0=keyword, 1=semantic)
includeContent bool No Include full message content
filterMeta object No Additional metadata filters

Response:

{
  "results": [
    {
      "document": {"id": "...", "key": "...", "meta": {...}, "contentMd": "..."},
      "score": 0.87,
      "rank": 1,
      "sessionId": "a1b2c3d4e5f6...",
      "role": "assistant",
      "matchStrategy": "hybrid"
    }
  ],
  "total": 5,
  "strategy": "hybrid",
  "query": "How does vector search work?"
}

POST /v1/memory/summarize #

Generate and store a summary of a session's conversation.

Request:

{
  "sessionId": "a1b2c3d4e5f6...",
  "userId": "user-1"
}

Response:

{
  "summaryId": "memory_summaries|...",
  "sessionId": "a1b2c3d4e5f6...",
  "summary": "# Session Summary: a1b2c3d4\n\nMessages: 5\n\n## Conversation\n\n...",
  "createdAt": 1743401000,
  "messages": 5
}

POST /v1/memory/sessions #

List memory sessions with optional filtering.

Request:

{
  "userId": "user-1",
  "scenario": "customer_support",
  "limit": 50,
  "offset": 0,
  "sort": "createdAt",
  "asc": false
}

Response:

{
  "sessions": [
    {
      "sessionId": "a1b2c3d4e5f6...",
      "userId": "user-1",
      "scenario": "customer_support",
      "title": "Session about search API",
      "createdAt": 1743400000,
      "updatedAt": 1743401000,
      "expiresAt": 1745992000,
      "messageCount": 12
    }
  ],
  "total": 3
}

title is the one given to /v1/memory/session, or the default Session <first 8 characters of the id>. Before 2.19.0 the list left it out; sessions created then list with the title their body was written with. The MCP tool memory_list_sessions returns it too.

POST /v1/memory/history #

Get the full message history for a session, ordered chronologically: by creation time to the nanosecond, then by message id, so messages written within the same second keep the order they were written in (before 2.19.0 they could come back in any order). The MCP tool memory_session_history answers in the same order.

Request:

{
  "sessionId": "a1b2c3d4e5f6...",
  "limit": 100,
  "offset": 0
}

Response:

{
  "messages": [
    {"id": "...", "key": "...", "meta": {"role": ["user"], "sessionId": ["..."]}, "contentMd": "How does vector search work?", "addedAt": 1743400100},
    {"id": "...", "key": "...", "meta": {"role": ["assistant"], "sessionId": ["..."]}, "contentMd": "Vector search uses embeddings...", "addedAt": 1743400110}
  ],
  "total": 2
}

Curation Rules #

Editorial overrides for search ranking: pin documents to fixed positions and/or hide others for specific queries. Applied in FTS + Hybrid pipelines after scoring, before pagination.

GET /v1/curation #

List rules. Pass id=<id> for a single rule, collection=<c> to scope by collection, or omit both to list all.

curl "http://localhost:11023/v1/curation?collection=blog"

POST /v1/curation #

Create a new rule. Server assigns the id.

curl -X POST http://localhost:11023/v1/curation \
  -H 'Content-Type: application/json' \
  -d '{
    "collection": "blog",
    "query": "rust tutorial",
    "matchMode": "exact",
    "enabled": true,
    "pins": [
      {"key": "rust-getting-started", "position": 1},
      {"key": "rust-ownership", "position": 2}
    ],
    "hides": ["legacy-post"]
  }'

Fields:

Field Type Required Description
collection string Yes Collection scope
query string Yes Trigger query text
matchMode string No exact (default) or contains; case-insensitive
pins array No [{key, lang?, position}] — position is 1-based; <=0 appends after organic results
hides array No Document keys to drop from results
enabled bool No Default false via REST — pass true to activate immediately

PUT /v1/curation #

Replace an existing rule. Body must include id. createdAt is preserved server-side.

DELETE /v1/curation?id= #

Remove a rule by id.

Response markers #

Results injected by a pin carry "pinned": true on FTSResultWithDoc and HybridSearchResultItem, so clients can style them.