MCP Server Configuration

MDDB has a built-in MCP (Model Context Protocol) server implementing both the stateless 2026-07-28 specification and the handshake-based 2025-11-25, side by side. This document covers all MCP configuration options.

→ Protocol revisions: what each one requires | → LLM client setup (Claude, Cursor, ChatGPT, Ollama) | → Custom YAML tools

Transports #

Transport Endpoint Spec Version Status
Stdio stdin/stdout 2026-07-28 + 2025-11-25 Default for Claude Desktop
Streamable HTTP POST /mcp (plus GET/DELETE for handshake clients) 2026-07-28 + 2025-11-25 Recommended for remote
SSE (legacy) GET /sse + POST /message 2024-11-05 Backward compatible

GET /mcp and DELETE /mcp belong to the handshake era only; 2026-07-28 removed sessions and the standalone stream. Both stay available for the clients that still use them.

All transports run on the MCP port (default: 9000, configurable via MDDB_MCP_ADDR).

The MCP port also answers plain JSON requests, for scripts and for checking a deployment without an MCP client. They take the same credentials as the MCP transports:

Endpoint What it does
GET /tools The tool catalog, built-in and custom tools, as {"tools": [...]}
POST /tools/call Run one tool: {"name": "...", "arguments": {...}}. Answers with the same result a JSON-RPC tools/call gets: content, and structuredContent where the tool has it (see Structured Output). Answers 403 when the HTTP mode is read, and 503 while writes wait for the freelist after a crash, whatever the tool
GET /resources The resource catalog and resource templates
POST /resources/read Read one resource: {"uri": "mddb://..."}
GET /events The server-sent document change events, as GET /v1/events on the HTTP port

Protocol Revisions #

MDDB serves two revisions at once, and each request declares its own: one carrying io.modelcontextprotocol/protocolVersion in params._meta is served statelessly under 2026-07-28, and one without it is served under 2025-11-25 as before. A handshake client and a stateless client can share a port, a connection, or a stdio process.

→ Full details of both revisions — required _meta fields, server/discover, the mirrored HTTP headers, caching hints, error codes, and what 2026-07-28 removed.

initialize still negotiates for handshake clients, and only ever offers a revision that has a handshake:

Client sends in initialize MDDB answers with
a handshake revision MDDB speaks that revision
anything else (including 2026-07-28) its own newest handshake revision, and the client decides whether to continue

GET /v1/config reports the current state without a request, which cannot be learned from a handshake — that answers for one client, and cannot show that a pin is in force or what else would have been accepted:

{
  "protocols": {
    "mcp": {
      "enabled": true,
      "addr": ":9000",
      "stdio": false,
      "revision": "2026-07-28",
      "supportedRevisions": ["2026-07-28", "2025-11-25"],
      "revisionPinned": false,
      "handshakeRevision": "2025-11-25"
    }
  }
}

Pinning a revision #

MDDB_MCP_PROTOCOL_VERSION forces one revision and disables negotiation entirely. Set it when a client's own version handling is the thing that is broken; leave it unset otherwise, because a pin also stops MDDB from serving clients that ask for anything else.

MDDB_MCP_PROTOCOL_VERSION=2026-07-28

Pinning the stateless revision takes the handshake off the table: initialize is then refused with -32022 naming what the server does serve.

A pin naming a revision this build does not implement stops the server at startup, listing what it can speak. Accepting it would produce a handshake that succeeds and a session that then misbehaves, far from the cause.

The MCP-Protocol-Version header #

Required on every stateless POST, where it must also match the revision in the body's _meta — a disagreement is -32020. For a handshake client the header stays optional, and naming a revision MDDB cannot speak (or one that disagrees with a pin) is refused with 400 and a body naming what would work.

curl -X POST http://localhost:9000/mcp \
  -H "MCP-Protocol-Version: 2024-01-01" -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}'
# {"error":"unsupported MCP revision 2024-01-01; this server speaks: 2026-07-28, 2025-11-25"}

A stateless client (2026-07-28) sends the call it wants, with no handshake before it:

curl -X POST http://localhost:9000/mcp \
  -H "Content-Type: application/json" \
  -H "MCP-Protocol-Version: 2026-07-28" -H "Mcp-Method: tools/list" \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{"_meta":{
        "io.modelcontextprotocol/protocolVersion":"2026-07-28",
        "io.modelcontextprotocol/clientCapabilities":{}}}}'

A handshake client (2025-11-25) opens as it always did:

# Initialize
curl -X POST http://localhost:9000/mcp \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}'

# Session ID returned in MCP-Session-Id header — use it for all subsequent requests

Client Configuration #

{
  "mcpServers": {
    "mddb": {
      "type": "http",
      "url": "http://localhost:9000/mcp"
    }
  }
}

Claude Code: claude mcp add --transport http mddb http://localhost:9000/mcp (add --header "X-API-Key: mcp_…" when API keys are on). The Panel's LLM Connections → Claude tab generates both for your server; see LLM Connections.

MDDB in the MCP Registry #

MDDB is listed in the official MCP Registry as com.tradik/mddb. The entry is server.json at the root of the repository: one OCI package, docker.io/tradik/mddb:<version>, served over stdio with MDDB_MCP_STDIO=true, run with --network host and a volume on /app/data — the same command as the README's Connect to Claude / Cursor / Windsurf (MCP) snippet, so a host that reads the registry and a user who pastes the snippet start the same server. The description is the one-liner from LISTING, which every catalogue uses.

Installing from the registry. A host or a client that browses the registry (and the aggregators that copy it hourly: Glama, PulseMCP, mcp.so, the clients' own sub-registries) finds the entry by name or by searching "mddb", reads the latest version and runs the package it names:

curl -s https://registry.modelcontextprotocol.io/v0.1/servers/com.tradik%2Fmddb/versions/latest \
  | jq '.server | {version, image: .packages[0].identifier}'
# the release version, and docker.io/tradik/mddb:<that version>

What the host then runs is docker run -i --rm --network host -v mddb-data:/app/data -e MDDB_MCP_STDIO=true docker.io/tradik/mddb:<version>; the registry's runtimeArguments and environmentVariables spell it out, and a host may ask for a different volume name or a MDDB_MCP_TOOLSETS value before starting. Without a registry-aware host, the README snippet is the same thing by hand.

Refreshed with every tag. The publish-mcp-registry job in .github/workflows/release.yml runs after the Docker image is on Docker Hub: it downloads the pinned mcp-publisher release and checks its Sigstore bundle with cosign verify-blob, validates server.json, checks that its version and image tag are the tag being released, logs in, publishes and then asserts that the registry serves the new version. The registry keeps one record per version and refuses a re-publish, so server.json is one of the files scripts/bump-version.sh rewrites and scripts/check-version.sh compares; services/mddbd/mcp_registry_doc_test.go checks the entry against the server before a release (name equal to the image label, version equal to VERSION, description within 100 characters with the tool count, every environment variable a real setting).

Why the image carries a label. The registry proves that an entry owns the image it names by reading the image's io.modelcontextprotocol.server.name label, which must equal the entry's name. Both Dockerfiles and the release workflow set it to com.tradik/mddb (DOCKER).

Owner setup (once). The com.tradik namespace is proven with a DNS TXT record and an Ed25519 key:

openssl genpkey -algorithm Ed25519 -out mcp-registry-key.pem        # OpenSSL 3
PUBLIC_KEY="$(openssl pkey -in mcp-registry-key.pem -pubout -outform DER | tail -c 32 | base64)"
echo "tradik.com. IN TXT \"v=MCPv1; k=ed25519; p=${PUBLIC_KEY}\""     # add this record
PRIVATE_KEY="$(openssl pkey -in mcp-registry-key.pem -noout -text | grep -A3 'priv:' | tail -n +2 | tr -d ' :\n')"
  1. Add the TXT record on the apex tradik.com (not under a selector such as _mcp-auth.tradik.com; the registry checks the apex only), and wait for it to propagate.
  2. In the repository settings, environment mcp-registry (GitHub creates it on the job's first run; create it earlier to set the rules), add the secret MCP_DNS_PRIVATE_KEY with the value of PRIVATE_KEY (hex), and restrict the environment's deployment branches and tags to v*. The key goes nowhere else: not into the repository, not into a repository-level secret.
  3. Until the secret exists, the job validates server.json and ends with a notice saying nothing was published; the release is not held back. With the secret, the first tag publishes the entry.
  4. To rotate the key, generate a new pair, replace the TXT record (remove the old one: a stale record is tried first and fails the login) and the secret.

The fallback, should DNS block a release, is the GitHub namespace io.github.tradik/mddb with mcp-publisher login github-oidc and no secret; a change of namespace later is a new entry, with the old one marked deprecated, which is why the DNS name was chosen first.

Environment Variables #

Core #

Env Var Default Description
MDDB_MCP_ENABLED true Enable MCP HTTP server
MDDB_MCP_ADDR :9000 MCP HTTP listen address
MDDB_MCP_PORT 9000 MCP HTTP port (alternative to ADDR)
MDDB_MCP_STDIO false Run in MCP stdio mode (replaces HTTP/gRPC)
MDDB_MCP_DOMAIN — Server hostname for Panel config generation
MDDB_MCP_PUBLIC_URL — (v2.19.9) Base URL clients dial behind a proxy or tunnel, without /mcp, e.g. https://mcp.example.com. See How clients reach MCP
MDDB_MCP_MODE — Access mode override: read, write, or wr (inherits MDDB_MODE)

How clients reach MCP (v2.19.9) #

GET /v1/config reports under protocols.mcp what a client needs to connect, and the Panel's LLM Connections page builds its examples from it:

Field Source Meaning
publicUrl MDDB_MCP_PUBLIC_URL; if unset, MDDB_MCP_OAUTH_ISSUER while OAuth runs; else empty The base URL clients dial, without /mcp and without a trailing slash (both are removed from the setting when present)
apiKeyEnabled MDDB_MCP_API_KEY_ENABLED Whether /mcp asks for an MCP API key
oauthEnabled The OAuth server the listener runs true only when OAuth is on and could start (API keys on, valid issuer); a custom connector can then authorize

MDDB_MCP_PUBLIC_URL must be an absolute http or https URL, like the OAuth issuer; any other value is logged and ignored. The report carries no key, no key list and no secret. A Panel older than v2.19.9 ignores the three fields; a newer Panel against an older server treats them as empty and off, and shows its API key field as optional.

Server Info #

Env Var Default Description
MDDB_MCP_SERVER_NAME mddbd Server name in MCP initialize response
MDDB_MCP_SERVER_DESCRIPTION — Server description
MDDB_MCP_SERVER_VENDOR — Vendor name
MDDB_MCP_SERVER_HOMEPAGE — Homepage URL
MDDB_MCP_INSTRUCTIONS — System prompt for LLM — guidance on how to use this server. (v2.19.13) Unset, a server that holds code sends a default of about 120 tokens that says which tool answers which question (code_symbol with format: "lines", code_search), when the key is bound to no chat scenario and may use the code toolset. A server without code sends nothing, as before. none turns the default off.
MDDB_MCP_INSTRUCTIONS_FILE — Path to a file holding the instructions, read at startup. For multi-paragraph text that cannot go into a compose .env file. MDDB_MCP_INSTRUCTIONS wins when both are set.

Tools #

Env Var Default Description
MDDB_MCP_CONFIG — Path to YAML file with custom tool definitions
MDDB_MCP_BUILTIN_TOOLS true Set to false to hide all 116 built-in tools (only custom tools exposed)
MDDB_MCP_TOOLSETS all Comma-separated toolsets to expose, e.g. search,code. See Toolsets
MDDB_MCP_CONFIRM_DESTRUCTIVE off off, elicit or require: ask the user, through MCP elicitation, before a destructive tool runs. See Confirming Destructive Tools

API Key Authentication #

Env Var Default Description
MDDB_MCP_API_KEY_ENABLED false Require API key for MCP HTTP access
MDDB_MCP_API_KEYS — Static keys: key1:name1,key2:name2 (defined at startup); each may add :toolsets:collections:ro (Scoped keys)
MDDB_MCP_API_KEY_CACHE_TTL 60s Cache TTL for dynamic key lookups

⚠️ MCP exposure vs. main auth (SEC-002). The MCP listener (default :9000) is a separate port that grants full read/write access to the database. Its own MCPAPIKeyMiddleware is inactive unless MDDB_MCP_API_KEY_ENABLED=true. To prevent MCP from becoming an unauthenticated bypass of the main API, the server reconciles MCP exposure with MDDB_AUTH_ENABLED at startup:

MDDB_AUTH_ENABLED MDDB_MCP_API_KEY_ENABLED MCP listener behaviour
true false Gated by the main AuthManager — MCP requires the same Authorization: Bearer / X-API-Key credentials as the HTTP API. Anonymous tools/call → 401. MCP API keys (mcp_…) are not checked: one sent in either header gets 401 with {"error":"MCP API key auth is not enabled on this server: set MDDB_MCP_API_KEY_ENABLED=true to use mcp_ keys"} (2.19.10, #445; before, invalid token / invalid api key).
true true Gated by MCP API keys (as configured below).
false true Gated by MCP API keys.
false false No authentication. If MCP is bound beyond loopback (e.g. the default :9000), the server logs a prominent startup warning. Use only on a trusted/loopback bind, or set one of the flags above.

Two sources of keys:

  • Static — MDDB_MCP_API_KEYS env var (defined at startup, no restart needed to validate)
  • Dynamic — REST API (/v1/mcp/keys) stored in BoltDB, persists across restarts, managed without downtime

Clients authenticate via:

  • X-API-Key: <key> header
  • Authorization: Bearer <key> header
  • ?api_key=<key> query parameter (for SSE connections)
# Static keys only
docker run -d \
  -e MDDB_MCP_API_KEY_ENABLED=true \
  -e "MDDB_MCP_API_KEYS=sk-prod:claude-prod,sk-dev:cursor-dev" \
  -p 9000:9000 \
  tradik/mddb:latest

Dynamic Key Management API

Keys stored in internal BoltDB bucket (_mcp_api_keys). Requires admin auth when MDDB_AUTH_ENABLED=true.

# Create a key (full key shown only once in response)
curl -X POST http://localhost:11023/v1/mcp/keys \
  -H "Authorization: Bearer <admin-token>" \
  -d '{"name": "claude-prod", "expiresAt": 0}'
# Response: {"key":"mcp_a1b2c3d4e5f6...","name":"claude-prod","createdAt":1711...}
# Without MDDB_MCP_API_KEY_ENABLED=true the key is still created, and the
# response adds "warning": the MCP listener does not check it (2.19.10, #445).

# List keys (no key material: the "mcp_" scheme marker and a fingerprint,
# four bytes of SHA-256 of the key that the server log shows too)
curl http://localhost:11023/v1/mcp/keys \
  -H "Authorization: Bearer <admin-token>"

# Delete a key
curl -X DELETE http://localhost:11023/v1/mcp/keys \
  -H "Authorization: Bearer <admin-token>" \
  -d '{"key": "mcp_a1b2c3d4e5f6..."}'

# ...or name it by the fingerprint the listing shows (2.19.6); the same works
# for disable. A fingerprint two keys share is refused with 409.
curl -X DELETE http://localhost:11023/v1/mcp/keys \
  -H "Authorization: Bearer <admin-token>" \
  -d '{"fingerprint": "9f2a41c7"}'

# Disable a key (revoke without deleting)
curl -X POST http://localhost:11023/v1/mcp/keys/disable \
  -H "Authorization: Bearer <admin-token>" \
  -d '{"key": "mcp_a1b2c3d4e5f6..."}'

Key features:

  • TTL support — expiresAt Unix timestamp (0 = never expires)

  • Disable without delete — revoke instantly, keep for audit

  • Cache — lookups cached for MDDB_MCP_API_KEY_CACHE_TTL (default 60s), auto-invalidated on create/delete/disable

  • Panel UI — manage keys from the web panel (LLM Connections → API Keys tab); each key is listed as mcp_… · <fingerprint> with its scope, and its Disable and Delete buttons name it by that fingerprint. The create form takes an optional scope (collections, read-only, chat scenario, and from 2.19.11 the read-only collections among the chosen ones and a memory namespace); Chat → a scenario lists the keys bound to it, with create and delete. When /v1/config reports protocols.mcp.apiKeyEnabled: false, both places say the server does not check MCP keys, name MDDB_MCP_API_KEY_ENABLED=true and disable Create; a warning returned with a new key is shown with it (2.19.10, #445)

    LLM Connections page, API Keys tab: a new key shown once with a copy button, and the stored key docs-agent

Scoped keys: collections, read-only, a chat scenario (v2.19.9)

A key can be confined to some collections, to reads, or to the reach of one chat scenario. All three fields are optional; a key with none of them — every key stored before 2.19.9 and every static key in an older format — behaves exactly as before: limited by its toolsets only.

# Reads of one collection only
curl -X POST http://localhost:11023/v1/mcp/keys \
  -H "Authorization: Bearer <admin-token>" \
  -d '{"name": "site-reader", "collections": ["philkonieczny"], "readOnly": true}'

# The reach of the chat scenario "support": its allowed collections, read-only,
# and its composed prompt as the MCP instructions
curl -X POST http://localhost:11023/v1/mcp/keys \
  -H "Authorization: Bearer <admin-token>" \
  -d '{"name": "support-widget", "scenario": "support"}'
Field Meaning
collections Collections, aliases or role: targets (e.g. role:reference) the key may reach. Stored as given and resolved on every call, the way RBAC resolves them: an alias reaches its collection now, a role: target every collection that holds the role now. Empty = every collection.
readOnly The key may call only the tools read-only mode (MDDB_MCP_MODE=read) allows.
scenario Binds the key to a chat scenario (400 when no scenario has that name). The key's collections are the scenario's allowedCollections, read from the stored scenario on every call — editing the scenario changes the key's reach — intersected with collections when both are set. A bound key is always read-only.
readOnlyCollections (v2.19.11) Names among collections the key may read but not write; it writes only to the others. Each must be in collections by name or reach a subset of it after alias and role: resolution (400 otherwise), and is resolved on every call as collections is. Naming every one of collections stores the key as readOnly: true. readOnly: true keeps its meaning: nothing is written.
memoryNamespace (v2.19.11) The memory namespace of a key limited to collections or a scenario (400 on any other key; 1–128 characters, no surrounding spaces). Keys with the same name share their memory sessions; without it the key has a namespace of its own. See Memory namespaces.

What a scoped key may call, by the tool's access class (mcpToolAccessRules):

Class Verdict for a scoped key
Collection read or write For a key limited to collections or a scenario: allowed when every collection the call names, after alias and role: resolution, is in the scope; a call that names no collection is refused, unless the tool's default targets are in the scope (reference_* with role:reference in the scope). A write is refused to a read-only key, and (v2.19.11) a write that names any of readOnlyCollections — in collection, collections, source_collection or target_collections, by name or alias — is refused too; a write counts as any tool read-only mode refuses. The memory collections are never in a scope.
Every collection at once (get_stats, vector_stats, list_schemas, bulk_ingest_status, …) Refused when the key is limited to collections or a scenario; allowed to a key that is only read-only, when the tool reads.
Administration (create_backup, chat_skill_*, automations, …) Refused.
sync_refresh (2.19.11) Allowed to a key when the collection it names is in the scope, a read-only key and a collection in readOnlyCollections included: it brings a sync rule's mirror up to date and writes nothing of the caller's. With the main authentication it needs write permission on the collection. It runs only the sync rules writing to that collection; run_automation stays administration.
Handled inside the tool (chat_scenario_get, chat_conversation_*) Refused.
Memory store (memory_*) (v2.19.11) For a key limited to collections or a scenario: allowed inside the key's memory namespace; to a read-only key only memory_recall, memory_list_sessions and memory_session_history. Refused to a key that is only read-only: it is not limited, so it has no namespace.
No collection data (fts_languages, geo_encode, feature_list, …) Allowed; to a read-only key only when read-only mode allows the tool.

The same check covers resources/read (mddb://{collection}/{key} and mddb-search://{collection} must be in the scope; mddb://stats is every collection), the /tools/call and /resources/read endpoints, custom tools (gated as the built-in action they wrap, so a custom tool pinned to another collection is refused), completion/complete (offers only the collections in the scope), the rag-pipeline prompt (reads the response prompt of an in-scope collection only), chat_scenario_list (lists the scenarios whose collections are all in the scope) and /events (a scoped key must name an in-scope ?collection=). A refused call answers tool "<name>": forbidden. tools/list leaves out the tools a key can never call: writes for a read-only key, the every-collection, administration and handler tools, and the memory tools for a key with no namespace (the memory writes too for a read-only key). A key with readOnlyCollections that may still write to one collection sees the write tools.

A test (TestKeyScopeTablePinned) pins the verdict of every built-in tool for each kind of key, so a tool added later, or an edit that opens one, fails it until the table says so.

Memory namespaces (v2.19.11)

A key limited to collections or a scenario reads and writes its own part of the memory store, so an agent with a project key can hand a session over to the next one (Work tracking).

  • The namespace is derived from the key (a hash, not the key), or is the key's memoryNamespace; the two forms can never be equal.
  • memory_start_session, memory_add_message and memory_summarize stamp what they store with the namespace (meta field memoryNamespace, over any value the caller's meta sets).
  • memory_list_sessions and memory_recall return only the namespace's sessions and messages; memory_session_history, memory_add_message and memory_summarize on a session of another namespace answer session not found, as for one that does not exist.
  • Sessions stored before 2.19.11, or by an unscoped key or a main-auth user, carry no namespace: they are the global namespace, which no limited key sees. An unscoped key and a main-auth user see every session, as before.
  • Deleting a key keeps its memory. A new key gets a new namespace, unless it names the same memoryNamespace.
  • memory_recall finds the messages written with a key of the namespace; a message a main-auth user adds to a namespaced session is in its history but not in the key's recall.

A scenario-bound key follows the scenario: while it is disabled or deleted, or the chat module is off, every tools/call and resources/read of the key is refused, and initialize (and server/discover) answer with the server's own instructions. While the scenario is served, the instructions are its composed prompt — the text of GET /v1/chat/scenarios/{name}/prompt, skills and guardrails included. An empty allowedCollections reaches no collection: mddb-chat falls back to its own default_collection, which mddbd does not know, so the key fails closed. The scenario's external MCP servers are not proxied to the key.

An OAuth token minted from a scoped key has the key's scope: the token stands for the key, which is validated on every request, so disabling or deleting the key stops the token too (within MDDB_MCP_API_KEY_CACHE_TTL for a token presented to another replica; at once on the replica that made the change).

A static key takes the same scope as a fourth field and a trailing :ro; a static key limited to collections has a memory namespace derived from it. readOnlyCollections and memoryNamespace are fields of stored keys only:

MDDB_MCP_API_KEYS=key:name:toolsets:collections:ro
# one collection, read-only, every toolset
MDDB_MCP_API_KEYS=sk-site:site-reader::philkonieczny:ro
# the reference collections, with the code toolset
MDDB_MCP_API_KEYS=sk-ref:ref-reader:code:role:reference

Toolsets and collections are |-separated and either may be empty. The collections field runs to the end of the entry (so it may hold role: targets); :ro at the end makes the key read-only — key:name:search::ro is read-only on every collection. key, key:name and key:name:toolsets read as they always did. Static keys cannot be bound to a scenario.

OAuth 2.1 for claude.ai connectors #

Claude Code and the Claude API's MCP connector send an API key. claude.ai's "Add custom connector" cannot: it supports OAuth or no authentication at all. With OAuth on, the MCP listener is its own minimal authorization server, as the MCP authorization spec describes:

  • GET /.well-known/oauth-protected-resource and GET /.well-known/oauth-authorization-server — discovery metadata (RFC 9728, RFC 8414). A request to /mcp without credentials gets a 401 whose WWW-Authenticate header points at the first one.
  • POST /oauth/register — dynamic client registration (RFC 7591). Public clients only; a redirect URI must be in MDDB_MCP_OAUTH_REDIRECT_URIS or an http://localhost / 127.0.0.1 / [::1] URI on any port.
  • GET|POST /oauth/authorize — authorization code with PKCE (S256 only). The consent page asks for an MCP API key: mddb has no user accounts, so the key is what identifies the person authorizing.
  • POST /oauth/token — authorization_code and refresh_token grants.

Every token stands for the API key entered on the consent page, and the listener checks it as that key. A token can do what its key can; deleting or disabling the key revokes its tokens within MDDB_MCP_API_KEY_CACHE_TTL, and refreshing fails from then on. API keys keep working beside OAuth.

MDDB_MCP_API_KEY_ENABLED=true            # required: tokens stand for keys
MDDB_MCP_OAUTH_ENABLED=true
MDDB_MCP_OAUTH_ISSUER=https://mcp.example.com    # the listener's public URL
MDDB_MCP_OAUTH_SECRET=<32+ random characters>    # e.g. openssl rand -base64 48

Then add https://mcp.example.com/mcp as a custom connector in claude.ai, and paste an MCP API key on the page that opens.

Tokens and client IDs are sealed with AES-256-GCM under MDDB_MCP_OAUTH_SECRET and stored nowhere, so they survive restarts and work on every replica that shares the secret. Without the secret a random one is used and every token dies with the process. Authorization codes live in memory for one minute and are single-use. Refresh tokens are not rotated server-side (nothing is stored to rotate); they expire after MDDB_MCP_OAUTH_REFRESH_TTL. Expose the listener over HTTPS — through cloudflared or a reverse proxy — since the issuer must be an https URL.

Rate Limiting #

Env Var Default Description
MDDB_MCP_RATE_LIMIT_ENABLED false Enable per-client rate limiting
MDDB_MCP_RATE_LIMIT_REQUESTS 100 Max requests per window
MDDB_MCP_RATE_LIMIT_WINDOW 60 Window duration in seconds
MDDB_MCP_RATE_LIMIT_BURST 20 Burst allowance above limit
MDDB_MCP_RATE_LIMIT_BY ip Rate limit key: ip, api_key, or session

Response headers: X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset. Returns 429 Too Many Requests with Retry-After header when exceeded.

Request Logging #

Env Var Default Description
MDDB_MCP_LOGGING_ENABLED false Enable structured JSON audit logs
MDDB_MCP_LOGGING_LEVEL info Log level: debug, info, warn, error

Two records exist, both behind the same switch.

Request record — one line per HTTP request on the MCP listener:

{"timestamp":"2026-03-26T10:30:00Z","method":"POST","path":"/mcp","status":200,"duration_ms":45,"client_ip":"1.2.3.4","key_name":"claude-prod","session_id":"abc123","user_agent":"claude-code/1.0"}

Tool-call record — one line per tools/call, on every transport (Streamable HTTP, SSE, /tools/call, stdio). Every tool call is a POST /mcp with status 200, so the request record cannot tell a lookup that found something from one that did not. This record can:

{"time":"2026-10-11T18:54:33Z","level":"INFO","msg":"MCP tool call","tool":"version_check","query":"alloy","duration_ms":3,"hits":0,"found":false,"key_name":"claude-prod","client_ip":"1.2.3.4","session_id":"abc123"}
Field Meaning
tool Tool name as the client sent it (built-in or custom)
query The query argument, cut to 200 characters; empty when the tool has none
hits, found Documents in the result (total, or the results/documents array). Absent when the result is not a search
key_name, client_ip, session_id Caller, when the HTTP middleware resolved one; absent on stdio
error The failure, logged at WARN instead of INFO

Set MDDB_LOG_FORMAT=json so a log shipper (Alloy, Promtail, Vector) can parse the fields with | json. A dashboard of "what do people ask for, and what do we not have?" is sum by (query) (count_over_time({...} | json | msg="MCP tool call" | found="false" [24h])).

Three counters land in /metrics whether or not the log is on (see TELEMETRY): mddb_operations_total{operation="mcp_tool_call"|"mcp_tool_miss"|"mcp_tool_error",label="<tool>"}.

Agent Instructions #

The tool schemas say what each tool accepts; they do not say which one fits a question, or that asking for a projection instead of whole documents changes the cost by more than an order of magnitude. Measured on this engine, the same full_text_search over five 12 KB documents returns ~19 700 tokens by default and ~327 with fields: ["key"].

integrations/agent-instructions/ ships that guidance in the formats agents read:

File For
AGENTS.md Paste into a project; the source every other variant is generated from
claude-code/SKILL.md Claude Code skill
cursor/mddb.mdc Cursor rule
windsurf/mddb.md Windsurf rule

Edit AGENTS.md and run make agent-instructions; CI fails if a variant was edited directly, and a test fails if the instructions name a tool that no longer exists.

Locating a Match #

full_text_search accepts highlight: true, which returns each matching fragment with the lines it occupies:

{"name": "full_text_search", "arguments": {
  "collection": "theme", "query": "background",
  "highlight": true, "fragment_size": 80, "fields": ["key"]
}}
css/style.css:158-163
"…}\n\n.hero-banner {\n  <mark>background</mark>: url(hero.png);"

fields drops the document body and highlight says where to look, so the two together answer the question without carrying the file — under 800 bytes for a 164-line stylesheet, against ~20 000 tokens for the same search returning whole documents. Projections keep the fragments deliberately: dropping them would leave a caller with neither the text nor its location.

Lower fragment_size for source. The default of 150 is a byte budget tuned for prose; code lines are short, so it covers about fifteen lines of CSS.

search_documents, semantic_search, full_text_search, hybrid_search, cross_search and aggregate take filter next to filter_meta. One condition per metadata key, with the operators in, prefix, contains, gt, gte, lt, lte, not and exists:

{"name": "full_text_search", "arguments": {
  "collection": "repo", "query": "retry",
  "filter": {"path": {"prefix": "internal/"}, "kind": {"not": ["test"]}}
}}

The filter is evaluated on the metadata index before scoring, so narrowing to one directory costs nothing extra. An unknown operator is an error naming it. Full semantics: Filter Operators.

semantic_search, full_text_search, hybrid_search and cross_search also take group_by, which keeps at most per_group results for each value of a key — one passage per file instead of five from the same one:

{"name": "semantic_search", "arguments": {
  "collection": "repo", "query": "retry with backoff", "retrieval_mode": "chunk",
  "group_by": {"key": "path", "per_group": 1}
}}

Each result reports its group and groupRank. See Grouping Results.

Letting the Server Choose the Index #

semantic_search and cross_search take algorithm: "auto", and hybrid_search takes vector_algorithm: "auto". With it, the query planner chooses the vector index for each query. It goes by the collection size, the indexes already built and how much of the collection the filter admits. explain: true adds a plan to the response: the index used, whether the filter was applied first, and why. latency_target_ms is optional; 10 or less favours a quantized index on a large collection.

{"name": "semantic_search", "arguments": {
  "collection": "repo", "query": "retry with backoff", "algorithm": "auto",
  "filter": {"path": {"prefix": "internal/net/"}}, "explain": true
}}

Send auto rather than guessing an index. Without algorithm, the search is flat, as before. The table behind the choice is in auto: the server chooses.

Telling the Search Which Results Were Right #

semantic_search, hybrid_search and cross_search take positive and negative. These are the keys of results from an earlier call (vectors work too). The second search moves towards the positives and away from the negatives. You don't have to rewrite the query:

{"name": "semantic_search", "arguments": {
  "collection": "kb", "query": "rotate the signing key",
  "positive": ["key-rotation"], "negative": ["tls-certificates"]
}}

feedback_mode is query (default) or rescore. query moves the query vector (Rocchio; weights in rocchio: {alpha, beta, gamma}). rescore re-ranks the candidates by similarity to the examples, with feedback_weight (default 0.5). On hybrid_search only the vector half changes. With explain: true, plan.feedback shows the correction. See Relevance Feedback.

Query decomposition #

semantic_search and hybrid_search take query_decomposition: off (default) or auto. With auto, a question with several needs is also searched clause by clause (at most 4 clauses), and each document keeps its best score:

{"name": "semantic_search", "arguments": {
  "collection": "kb", "query": "set up a read replica and take a backup of the database",
  "query_decomposition": "auto", "explain": true
}}

Ask one combined question instead of two searches. Each clause costs one embedding call. On hybrid_search only the vector half is split. With explain: true, plan.decomposition gives the parts. See Query Decomposition.

Model reranking (v2.19.8) #

semantic_search, hybrid_search, full_text_search and cross_search take rerank: {enabled, candidates, top_n, explain}. With a reranking model configured on the server, the search fetches candidates results, the model orders them by reading the query and each passage together, and top_k (or top_n) come back:

{"name": "hybrid_search", "arguments": {
  "collection": "kb", "query": "rotate the signing key", "top_k": 5,
  "rerank": {"enabled": true, "candidates": 30, "explain": true}
}}

The answer carries rerank (model, candidates, cached, durationMs, and with explain each candidate's before/after rank). When the model times out, fails or the collection's budget is spent, the search's own order comes back with rerankSkipped naming why — the tool never fails because of the model. Off unless asked for here or in the collection's retrieval profile. See Model reranking.

Result Limits #

Every tool that takes a result count — limit, top_k or top_n on full_text_search, search_documents, autocomplete, semantic_search, hybrid_search, cross_search, code_symbol and geo_search — returns at most MDDB_SEARCH_MAX_LIMIT results (default 1000), or the collection's retrieval.maxTopK when that is lower. A capped call still succeeds; its JSON text adds "limit" (the count used) and "limitCapped": true, and the tool result also carries them as data:

{"content": [{"type": "text", "text": "{ ... \"limit\": 1000, \"limitCapped\": true }"}],
 "structuredContent": {"limitCapped": true, "limit": 1000}}

That is the shape for a tool without an output schema, such as code_symbol; under the cap it has no structuredContent and its text is unchanged. A tool that declares an output schema (full_text_search, search_documents, semantic_search, hybrid_search) returns its whole JSON answer as structuredContent on every call, so limit and limitCapped are fields of that object (see Structured Output). See Result Limits.

Structured Output (v2.19.12+) #

Nine tools declare an outputSchema in tools/list: search_documents, get_stats, aggregate, semantic_search, vector_stats, full_text_search, classify_document, hybrid_search and get_checksum. Every successful call of one of them returns the answer twice: as text in content, as before, and as the same JSON object in structuredContent, which conforms to the declared schema. This holds on both protocol revisions and on plain POST /tools/call. A get_checksum call, for example:

{"content": [{"type": "text", "text": "{\"collection\": \"docs\", \"checksum\": \"...\", \"documentCount\": 42}"}],
 "structuredContent": {"collection": "docs", "checksum": "...", "documentCount": 42}}

The other tools declare no schema and return structuredContent only for a capped limit or a refused call (a quota or rate limit, a read-only collection). code_search declares none either (v2.19.13): a tool with an output schema must return structuredContent, and a client that receives it may give the model that JSON instead of the text, so the line answers are on tools without one.

Before 2.19.12 the nine tools answered with content only. The MCP specification requires structuredContent from a tool with an output schema, and a client that checks refused every such answer with "Tool X has an output schema but did not return structured content" (#461). Clients that read the text are unaffected by the change: a field is added and nothing is removed.

Passages for Code #

search_documents, full_text_search, semantic_search, hybrid_search and cross_search take format: "passages" (and passage_lines). Each hit then comes back as a path, a line range, the definition holding it and those lines, instead of the document. (v2.19.13) A passage cut around a hit holds at most 500 tokens; passage_tokens (1 to 8000) changes the bound, and a passage cut to it carries truncated: true. With fields set, passages come without their text unless include_content: true is passed:

{"name": "full_text_search", "arguments": {
  "collection": "theme", "query": "background", "limit": 1, "format": "passages"
}}

For code this replaces "search, then read the file" with one call; see Passages — What an Agent Gets.

Line Answers for Agents (v2.19.13+) #

code_search and code_symbol with format: "lines" answer in lines, the way grep does: a path once for consecutive hits in one file (the next hit in the same file starts with :), one hit per line, and a count at the end that says whether the list is complete. N of N means it is; more with limit means the limit cut it. JSON stays the default on code_symbol.

code_search takes collection, query, mode, path (a directory prefix) and limit. mode: "exact" lists every line that holds the query as written, ignoring case, with the definition it sits in. It reads the documents under path (up to 5 000; past that the count says how many it read), and shows 50 lines by default:

app/main.go:4: [run] c.Close()
  :5: [run] f.Close()
2 of 4 lines in 2 files, more with limit or a narrower path

mode: "words" (the default) is the full-text search and mode: "meaning" the hybrid one, five hits by default. Each hit is its line range and enclosing definition, then the matching line with two lines of context, numbered. On a server without embeddings meaning answers by words and says so on the first line.

file/file.go:5-8  File.Close
  5: func (f *File) Close() error {
  6: flush()
  7: return nil
  8: }
1 of 1 hits

code_symbol with format: "lines" writes path:start-end kind Name for definitions, callers, callees, implementations and siblings, path:line in Enclosing.Func: text for references and tests, and a count line per relation asked for, also when it is empty:

Closer: semantic (gopls/0.24.0)
definitions: 1 of 1
io/closer.go:3-5  interface  Closer
implementations: 3 of 3
buf/buf.go:3-3  struct  Buffer
file/file.go:3-3  struct  File
net/conn.go:3-3  struct  Conn

When the name has several definitions, each use names its target, and a relation cut by limit gives its total:

references: 1 of 4, more with limit
app/main.go:5  in run: f.Close()  -> file/file.go#File.Close

With include_content: true the text of a definition follows its line, indented by four spaces.

Toolsets #

Every tool's schema sits in the model's context on every turn, and a long menu makes the choice worse as well as more expensive. Each built-in tool belongs to one toolset, and a server or a key can expose only the toolsets it needs:

Toolset Tools
search search_documents, aggregate, semantic_search, full_text_search, hybrid_search, cross_search, autocomplete, fts_languages, search_advisor, get_indexing_status, run_eval, add_eval_query, get_gain, find_duplicates, classify_document, get_meta_keys
code code_graph, code_symbol, code_search, reference_search, reference_symbol, reference_examples, reference_dependencies
documents add_document, update_document, delete_document, get_document_meta, set_ttl, add_documents_batch, delete_documents_batch, export_documents, list_revisions, restore_revision, delete_where, update_where, set_ttl_where
ingest import_url, upload_file, ingest_documents, bulk_ingest_*, sync_refresh
memory memory_*
schema set_schema, get_schema, delete_schema, list_schemas, validate_document
admin stats, reindexing, backups, collection deletion and configs, synonyms, stopwords, curation rules, corpus packs (corpus_list, corpus_install, corpus_remove), chat conversations, read-only (chat_conversation_list, chat_conversation_get), the chat conversation log, read-only, global admin (chat_log_list, chat_gaps), chat scenarios (chat_scenario_list, chat_scenario_get, chat_scenario_put, chat_scenario_delete), chat skills (chat_skill_list, chat_skill_get, chat_skill_put, chat_skill_delete), chat MCP secrets (chat_mcp_secret_list, chat_mcp_secret_put, chat_mcp_secret_delete), module switches (feature_list, feature_set)
geo, automation, webhooks, wordpress the tools of that area
  • Server: MDDB_MCP_TOOLSETS=search,code (default all). MDDB_MCP_BUILTIN_TOOLS=false still hides every built-in tool.
  • Per key: POST /v1/mcp/keys with "toolsets": ["search", "code"], or a third field in a static key: MDDB_MCP_API_KEYS=key:name:search|code. A key sees the intersection of its toolsets and the server's.
  • A tool outside the caller's toolsets is not listed, and calling it anyway is answered with JSON-RPC -32601 — the list is not the authorisation.
  • Custom tools are never filtered by toolset: they are the operator's explicit choice.
  • A scoped key (v2.19.9) also does not list the tools its scope can never call — writes for a read-only key; every-collection, administration, handler and memory tools for a key limited to collections or a scenario — and a custom tool by the action it wraps. Calling one anyway is answered tool "<name>": forbidden.

Measured on a full list of 93 tools, the tools/list schemas take about 94 KB (≈23 600 tokens) per turn. The 22 tools of search,code take about 43 KB (≈10 800 tokens), less than half.

Agent Toolsets
Reads and reviews code search,code
Answers from a knowledge base search
Keeps notes across sessions search,memory,documents
Imports content ingest,documents,search
Operates the server admin (with a key of its own)

Searching What You Just Wrote #

A write returns once the document's full text and metadata are indexed, so full_text_search finds it at once. Its embedding is computed afterwards by a background worker, so semantic_search finds it a moment later. Three ways to handle the gap, cheapest first:

  1. Pass wait_for_index (ms, up to 30000) and wait_for_keys with the keys you just wrote to semantic_search, hybrid_search or cross_search. The search starts as soon as those embeddings land; if they do not land in time it runs anyway and reports indexing.timedOut.
  2. Pass read_level: "indexedPlusPending" to semantic_search to also get still-queued documents that match by text, marked pendingEmbedding. hybrid_search always includes them and marks them the same way.
  3. Call get_indexing_status to see the queue.

add_document reports indexing.embeddingQueued when it queued an embedding.

Images of the Documents You Find #

Pass include_images: true to full_text_search, semantic_search, hybrid_search or cross_search and each hit carries images: its image documents with altText, caption, page and the url of the bytes. Alt text and captions are searchable text, so an image is also a hit of its own. With a provider that embeds images, semantic_search and hybrid_search also return imageHits (pictures matching the query by what they show), and semantic_search takes query_image to search by a picture. Images are stored when a write asks for them: extract_images on upload_file and ingest_documents. See SEARCH.

Built-in Tool Catalog #

All 116 built-in tools, grouped by area. Tool inputs are self-describing via MCP schema discovery (tools/list); the semantic_search tool additionally supports retrieval_mode/window_size (passage-level results) and mmr/mmr_lambda (result diversification).

Documents #

Tool Description
add_document Add or update a document in MDDB. expected_revision writes only over that revision; if_absent (v2.19.6) only when the document does not exist yet, otherwise a revision conflict and nothing written.
search_documents Search documents with filters and sorting. Since v2.19.6 each document carries revision, the value POST /v1/get returns (also without the body; not in a fields projection).
delete_document Delete a document from MDDB. expected_revision (v2.19.6) deletes only while the document is at that revision.
import_url Import a markdown document from a URL.
set_ttl Set or remove time-to-live on a document.
validate_document Validate document metadata against collection schema without adding the document.
add_documents_batch Add multiple documents to a collection in a single batch operation.
delete_documents_batch Delete multiple documents from a collection in a single batch operation.
delete_where Delete every document a metadata filter/filter_meta matches, through the normal delete. Destructive: run with dry_run first. limit (default 1000) and cursor page through large sets.
update_where Merge meta into every document a filter matches; content is untouched.
set_ttl_where Set the time to live (ttl seconds, 0 removes it) of every document a filter matches.
get_meta_keys List all unique metadata keys and their values for a collection.
get_checksum Get a collection's checksum (16 hex digits): equal on two nodes that hold the same documents, changed by any document added, removed or modified.
ingest_documents Bulk ingest documents with URL-based key derivation, YAML frontmatter extraction, content deduplication, and automatic metadata injection. A document may carry a file (format, content_base64) that the server converts, and options take text_only; options extract_images / fetch_remote_images and a document's images ([{path, content_base64}]) store its images as image documents (images).
upload_file Upload a file and convert it to markdown. Also takes text_only; formats include xlsx, ods, csv, tsv, pptx, odp, epub, eml and mbox; the result carries conversionConfidence, conversionWarnings and parts (the keys of an email's attachments or a mailbox's messages, stored with meta.parent); extract_images, fetch_remote_images and images store a Markdown file's or PDF's images as image documents, listed in parts.
Tool Description
aggregate Compute metadata facets (value counts) and date histograms over a collection, with optional metadata pre-filtering.
semantic_search Search documents by meaning using semantic similarity. Takes filter, group_by, and read_level / wait_for_index / wait_for_keys to see documents whose embedding is still queued; algorithm: "auto", explain, latency_target_ms, relevance feedback (positive, negative, feedback_mode, feedback_weight, rocchio), include_images (each hit's images, and imageHits with an image-capable provider), query_image (search by an image; query may then be omitted) and query_decomposition (off/auto). Since v2.19.8: rerank (model reranking, see above).
get_indexing_status Is what was just written searchable yet? Queued and failed embeddings, progress and the oldest queued job, for a collection or the server. Read-only.
run_eval Measure search configurations on the collection's evaluation set: recall@k, nDCG@k, MRR, p50/p99 latency and tokens per configuration. Read-only. See Measuring Instead of Guessing. A configuration takes summaryMode (off, blend, expand) to measure summaries.
get_gain What retrieval saved over a window of days: searches by type and algorithm, tokens returned and tokens avoided by passages and chunks. Counts only. Read-only.
add_eval_query Add a query and the keys of the documents that should answer it, optionally graded 0–3, to the collection's evaluation set.
full_text_search Search documents by text content using full-text search with term matching and relevance scoring. It runs the same search as POST /v1/fts and takes filter_meta, disable_stem, disable_synonyms, mode, distance and facet_by (the last was in the schema before and ignored). It also takes filter and group_by (see Narrowing a Search). include_images attaches each hit's images. Since v2.19.8: rerank.
autocomplete Prefix autocomplete — returns top-N terms starting with the query, ranked by document frequency.
classify_document Zero-shot document classification.
hybrid_search Combined sparse (FTS) + dense (vector) search with alpha blending or Reciprocal Rank Fusion. Takes vector_algorithm: "auto", explain, latency_target_ms, relevance feedback on the vector half (positive, negative, feedback_mode, feedback_weight, rocchio), include_images and query_decomposition (off/auto, vector half only). Since v2.19.8: rerank. Since v2.19.12 facet_by and facet_max_values are read (they were in the schema before and ignored): facets counts the results per value of each key, as on POST /v1/hybrid-search.
cross_search Search across multiple collections using a source document's embedding or a text query. search_type is vector, fts or hybrid, and role:reference in target_collections means every reference collection. algorithm: "auto" plans each target; explain, latency_target_ms, relevance feedback (positive, negative, feedback_mode, feedback_weight, rocchio), and include_images (each hit's images from its own collection). Since v2.19.8: rerank (needs query).
find_duplicates Find duplicate and similar documents within a collection.

Geo #

Tool Description
geo_search Find documents within a given radius (in meters) of a latitude/longitude point.
geo_within Find documents inside an axis-aligned bounding box (minLat..maxLat × minLng..maxLng).
geo_polygon Find documents whose coordinates fall inside a GeoJSON Polygon (outer ring + optional holes) or MultiPolygon (union of polygons).
geo_stats Report per-collection indexed-point counts plus any loaded postcode datasets.
geo_encode Convert a (lat, lng) pair into a geohash string of the requested precision (1..12, default 12).
geo_decode Convert a geohash string back to the (lat, lng) centroid of its cell.

Vectors #

Tool Description
vector_reindex Re-embed all documents in a collection.
vector_stats Get vector/embedding statistics including provider info and per-collection embedding coverage.

FTS admin #

Tool Description
fts_reindex Reindex full-text search for a collection.
fts_languages List all supported FTS languages with their codes and names.
list_synonyms List all synonym entries for a collection.
add_synonym Add or update a synonym group for a term.
delete_synonym Delete a synonym group for a term in a collection.
list_stopwords List all stop words (default + custom) for a collection.
add_stopwords Add custom stop words to a collection's FTS index.
delete_stopwords Remove custom stop words from a collection.

Revisions #

Tool Description
truncate_revisions Truncate revision history for a collection, keeping only the N most recent revisions per document.
list_revisions List revision history for a document.
restore_revision Restore a document to a previous revision by timestamp.

Curation #

Tool Description
list_curation_rules List curation rules that pin or hide documents for specific search queries.
create_curation_rule Create a rule that pins specific documents to fixed positions or hides others when a query matches.
update_curation_rule Replace an existing curation rule by id.
delete_curation_rule Remove a curation rule by id.

Automation #

Tool Description
list_automation List all automation rules (webhooks, triggers, crons). type filters by kind; collection (2.19.0) lists the rules acting on a collection — the sources syncing into it — each sync and backup with lastResult.
create_automation Create a new automation rule (webhook target, search trigger, or cron schedule). A cron rule's sync object takes source: "git" since 2.19.5, with url, ref (a branch, a tag or latest-release), include, exclude, forge, tokenSecretRef, hookSecretRef and adopt — see AUTOMATIONS.
get_automation Get a specific automation rule by ID.
update_automation Update an existing automation rule.
delete_automation Delete an automation rule by ID.
test_automation Test a trigger rule by running its search and returning matches (dry run, no webhook fired).
get_automation_logs List automation execution logs with optional filtering by rule ID and status.
run_automation (2.19.0) Run a cron rule's sync or backup now, as its schedule would; returns the run's jobId. Fails while the previous run is still going.

create_automation takes source: "issues" since 2.19.11 — a read-only mirror of a forge's issues and pull requests, with state, since, include (issues, pulls), comments and repositoryFrom — see AUTOMATIONS.

Webhooks #

Tool Description
register_webhook Register a webhook to receive HTTP callbacks when documents are added, updated, or deleted.
list_webhooks List all registered webhooks.
delete_webhook Delete a registered webhook by ID.

Schemas #

Tool Description
set_schema Set JSON Schema for collection metadata validation.
get_schema Get JSON Schema for a collection.
delete_schema Delete/disable schema validation for a collection.
list_schemas List all collection schemas.

Memory RAG #

Tool Description
memory_start_session Start a new memory/conversation session for RAG.
memory_add_message Add a message to an existing memory session.
memory_recall Semantically recall relevant messages from past conversations.
memory_summarize Generate a summary of a conversation session.
memory_list_sessions List memory/conversation sessions with optional filtering by user, scenario, and sorting.
memory_session_history Get the full message history of a specific conversation session, ordered chronologically.

WordPress #

Tool Description
wordpress_publish Create or update a WordPress post/page via the mddb-sync plugin, including tags, categories, custom taxonomies, meta fields and Polylang/WPML language assignment.
wordpress_set_status Change the publishing status of a WordPress post/page (publish, draft, pending, private, future, trash) via the mddb-sync plugin.

Bulk ingest #

Tool Description
bulk_ingest_submit Queue a long-running bulk ingest job and return immediately with a job identifier.
bulk_ingest_status Return the current status record (counters, timestamps, up to 50 errors) for a previously-submitted bulk ingest job.
bulk_ingest_list List bulk ingest jobs newest-first, optionally filtered by collection.
bulk_ingest_cancel Cancel a pending bulk ingest job.
sync_refresh (2.19.11) {collection, number?}: refresh a synced collection now — with number, that one issue or pull request of the issues sync writing to it; without, an incremental run of each sync rule writing to it. At most once every 30 s per rule; the answer says when each rule last ran. A key limited to the collection may call it. See AUTOMATIONS.

Ops #

Tool Description
get_stats Get MDDB server statistics.
export_documents Export documents from a collection in NDJSON format. Optional keys (2.19.7+, [{key, lang}]) exports only those documents.
create_backup Create a backup of the MDDB database.
restore_backup Restore the MDDB database from a backup file.
corpus_list (v2.19.0) The corpus packs installed in the caller's tenant: collection, name, version, licence, document count, whether its vectors are disabled. Read-only. See CORPUS-PACKS.
corpus_install (v2.19.0, admin) Install a .mddbpack the server downloads from an https:// URL (url, optional sha256 of the pack file). The download goes through the SSRF guard, a redirect may not leave https, and it is capped at MDDB_CORPUS_MAX_BYTES. Refused with a conflict when the collection already holds data.
corpus_remove (v2.19.0, admin) Remove an installed pack by name: its collection, documents and indexes. Gated by MDDB_MCP_CONFIRM_DESTRUCTIVE, which asks for the pack's name to be typed. There is no corpus_build tool: a build's product is a file a tool answer cannot carry; build with mddb-cli corpus build, POST /v1/corpus/build or the BuildCorpusPack RPC.
chat_scenario_list (v2.19.0) The chat scenarios the caller may read — an assistant's prompt, guardrails, allowed collections, style, LLM parameters and limits — and the store's version, which grows on every change. Read-only. See API.
chat_scenario_get (v2.19.0) One scenario by name, with its composed system prompt (prompt), its size (bytes, approxTokens), a warning past 75% of MDDB_CHAT_PROMPT_MAX_BYTES, and missingSkills: skills the scenario names that are not stored, and mcpServers: each external server's active state and reason. Needs read permission on every collection the scenario allows. Read-only.
chat_scenario_put (v2.19.0, admin) Create a scenario or replace it whole: name and scenario, the body of PUT /v1/chat/scenarios/{name}. A field left out is reset to its default; every allowed collection must exist. mcpServers (MCP-005) names external MCP servers; with the chatExternalMcp feature on, each allowed tool is checked read-only against the server before saving.
chat_scenario_delete (v2.19.0, admin) Delete a scenario by name. Gated by MDDB_MCP_CONFIRM_DESTRUCTIVE, which asks for the scenario's name to be typed.
feature_list (v2.19.0, GO-049) The server's optional modules — chat, geo, temporal, spell, curation, automation, memory, codeIntel, eval, corpus, classify, duplicates, images, webhooks, schemas, aliases, crossSearch, searchTuning, ftsTuning, chatExternalMcp — with enabled (works now), configured, default, requires, lockedBy (MDDB_FEATURES_FORCE_OFF), blockedBy and the store's version. Read-only. See API.
feature_set (v2.19.0, GO-049, admin) Switch a module on or off: name, enabled. The data stays. A module locked by MDDB_FEATURES_FORCE_OFF is refused. The tools of a disabled module leave tools/list and their calls are refused.
chat_skill_list (v2.19.0, #404, admin) The chat skills — reusable SKILL.md instruction blocks that scenarios attach by name — with description, version, bytes, source and usedBy, without contents, and the scenarios' version counter. Admin only, as every skill tool: a skill's text is part of system prompts. Read-only. See API.
chat_skill_get (v2.19.0, #404, admin) One skill by name with its content and the list of its kept earlier versions (the last 10); version reads one of those. Read-only.
chat_skill_put (v2.19.0, #404, admin) Create a skill or store a new version: name, content (the instructions, or a whole SKILL.md whose front matter gives the description), optional description and source (url, commit, fetchedAt). A put that changes nothing stores nothing. There is no import tool: importing from a URL is a preview an operator reads in the panel, over REST or gRPC.
chat_skill_delete (v2.19.0, #404, admin) Delete a skill by name; refused while a scenario attaches it, and the error names the scenarios. Gated by MDDB_MCP_CONFIRM_DESTRUCTIVE, which asks for the skill's name to be typed.
chat_mcp_secret_list (v2.19.0, MCP-005, admin) The credentials of the external MCP servers chat scenarios use: name, header, set: true, updatedAt and usedBy, plus encryptionReady, false while no MDDB_ENCRYPTION_KEY is loaded and no secret can be set. Values are write-only and never returned. Read-only. See API.
chat_mcp_secret_put (v2.19.0, MCP-005, admin) Set or replace a credential: name, value (a bearer token, or the value of header when one is given). Stored only sealed with the at-rest key: without MDDB_ENCRYPTION_KEY the tool fails with "…set MDDB_ENCRYPTION_KEY and restart mddbd" and stores nothing. The answer has no value. Inspecting a server and calling its tools are not MCP tools: they are REST, gRPC and the panel's.
chat_mcp_secret_delete (v2.19.0, MCP-005, admin) Delete a credential by name; refused while a scenario's server names it, and the error names the scenarios. Gated by MDDB_MCP_CONFIRM_DESTRUCTIVE, which asks for the secret's name to be typed.
chat_conversation_list (v2.19.0, #405) One user's persistent chat conversations (sub, optional scenario, limit, cursor), newest first: id, scenario, title, message count, times, ended. Read-only. See API.
chat_conversation_get (v2.19.0, #405) One conversation of a user (id, sub, optional limit for the last N messages) with its messages: role, content, tool calls, model, tokens. A conversation of another sub is not found. Read-only: the host writes conversations over REST or gRPC, and no tool creates, appends to or deletes one.
chat_log_list (v2.19.0, #406) The logged chat turns across users (scenarios with logging.enabled), newest first: question, answer, outcome (answered, noResults, refused, error), rating and comment, tools with queries, result keys and scores, model, latency, tokens. Filters: scenario, from, to (unix seconds, RFC 3339 or YYYY-MM-DD), rating (up, down, none, any), outcome, limit, cursor. Global admin; read-only. See API.
chat_gaps (v2.19.0, #406) Docs gaps: the questions whose searches found nothing or scored below threshold (default MDDB_CHAT_GAP_SCORE or 0.3), grouped by normalised text with counts and the last asked time, most frequent first. Filters: scenario, from, to, minCount, limit. Global admin; read-only.
update_document Partially update a document. expected_revision makes it conditional: pass the revision from a previous read or write, and a concurrent change is reported instead of overwritten. Every MCP write, batch updates included, runs the same after-write step as REST and gRPC: embeddings, geo, full text, webhooks, SSE and triggers. An empty content_md empties the document: its content postings and vectors are removed, its meta fields stay searchable. A batch update reads an empty content_md as "leave it".
get_document_meta Get document metadata without content.
reference_search Search reference code — other projects indexed with mddb-cli reference add — hybrid, as passages. See REFERENCE-CODING.
reference_symbol Where reference code defines and uses a symbol.
reference_examples The definitions in reference code that call a symbol, with their text.
reference_dependencies What a file in a reference collection imports, or what imports it.
code_symbol Everything about one symbol as path + line passages: definitions with their span, references with the definition each sits in, callers, callees, tests that touch it and siblings in the same directory. Read-only. (v2.19.3) After mddb-cli autoindex --semantic it answers from a language server's facts: precision: semantic (mixed when only some files have facts), qualified names (Conn.Close), path to pick one definition, ambiguous + candidates for a name with several, references grouped per definition (target), and the implementations relation, which needs those facts. (v2.19.13) format: "lines" answers in lines instead of JSON; exclude_tests: true leaves out every passage in a test file before the limit; path may name a directory (internal/session) and keeps the definitions under it; totals gives, per relation the limit cut, how many passages it had.
code_search (v2.19.13) Search a code collection and answer in lines: mode exact (every line holding an identifier or literal, ignoring case, with its enclosing definition), words (default, full-text) or meaning (hybrid; by words on a server without embeddings), path prefix, limit. Ends with a count that says whether the list is complete. No output schema. Read-only.
code_graph Code connection graph: what a document depends on and what depends on it: which stylesheet declares a selector, which pages load a script, which file defines a function this one calls (C, C++, assembly, Go, Rust, Java, Python, Ruby, PHP), which manifest declares the ConfigMap a Deployment refers to (Kubernetes, OpenShift, Kustomize, Terraform, Ansible). Edge kinds: uses-selector, calls, references, imports.
delete_collection Delete an entire collection and all its documents, revisions, and metadata indices.
get_collection_config Get configuration attributes for a collection (type, description, icon, color, custom metadata).
set_collection_config Set or update configuration attributes for a collection. Only the arguments sent change. code.include_paths sets where C #include <...> resolves (#319). embedding.chunk_size / embedding.chunk_mode set the collection's chunking for embeddings. fts.enabled: false stops full-text postings for the collection; fts_reindex then removes existing ones. fts.exclude_meta_keys keeps meta keys used only as filters out of full-text search, so changing them costs no FTS work; run fts_reindex after changing the list. quota (max_documents, max_bytes, max_vectors, embedding_calls_per_day, embedding_tokens_per_day; {} removes it) caps the collection — global admin only when auth is on (GO-043, see MULTI_TENANCY). A write refused by a quota is a tool error whose structuredContent carries {code: "QUOTA_EXCEEDED", status, resource, limit, used}.
list_collection_configs List all collections that have custom configuration set.

Access Modes #

Each protocol can have its own read/write mode:

Env Var Protocol Default
MDDB_MODE Global wr
MDDB_API_MODE HTTP/REST + GraphQL inherits global
MDDB_GRPC_MODE gRPC inherits global
MDDB_MCP_MODE MCP (all transports) inherits global
MDDB_HTTP3_MODE HTTP/3 (QUIC) inherits global

In read-only mode:

  • Built-in tools with readOnlyHint=true (search, stats, list, export) → allowed
  • Built-in tools with writes/deletes → blocked with error
  • Custom tools → allowed: every action a custom tool can wrap is read-only (semantic_search, search_documents, full_text_search, hybrid_search, code_graph, aggregate, fts_languages; see CUSTOM-TOOLS)
# Public MCP: read-only, custom tools only, API keys, rate limited
docker run -d \
  -e MDDB_MCP_MODE=read \
  -e MDDB_MCP_BUILTIN_TOOLS=false \
  -e MDDB_MCP_API_KEY_ENABLED=true \
  -e "MDDB_MCP_API_KEYS=sk-public:external" \
  -e MDDB_MCP_RATE_LIMIT_ENABLED=true \
  -e MDDB_MCP_RATE_LIMIT_REQUESTS=60 \
  -e MDDB_MCP_LOGGING_ENABLED=true \
  -e MDDB_MCP_CONFIG=/app/tools.yml \
  tradik/mddb:latest

Confirming Destructive Tools #

destructiveHint is advice to the client, and a client may ignore it. With MDDB_MCP_CONFIRM_DESTRUCTIVE set, MDDB asks for itself: before a destructive tool runs, it sends the client an elicitation, which the client shows its user as a question. Nothing happens unless the answer is yes.

Value Client declared elicitation Client did not
off (default) runs as before runs as before
elicit asked first runs as before
require asked first refused with -32021 (MissingRequiredClientCapability, data.requiredCapabilities.elicitation)

Gated tools are the built-in tools annotated destructive and not idempotent: delete_collection, delete_documents_batch, delete_where, truncate_revisions, restore_backup, corpus_remove, chat_scenario_delete, chat_skill_delete and chat_mcp_secret_delete (all four v2.19.0). Deleting one named object (delete_document, delete_schema, …) is not gated. The read-only mode check comes first: a read-only server refuses these tools without asking.

The question asks for confirm: true. delete_collection also asks for the collection's name to be typed, corpus_remove for the pack's and chat_scenario_delete for the scenario's and chat_skill_delete for the skill's and chat_mcp_secret_delete for the secret's (name), so a yes clicked out of habit is not enough:

{
  "message": "An MCP client asked MDDB to run delete_collection with {\"collection\":\"docs\"}. This cannot be undone. Allow it?",
  "requestedSchema": {
    "type": "object",
    "properties": {
      "confirm": {"type": "boolean", "title": "Allow delete_collection"},
      "collection": {"type": "string", "title": "Collection name"}
    },
    "required": ["confirm", "collection"]
  }
}

Declining, cancelling, a wrong name, an error from the client, the client going away, or no answer within 5 minutes all refuse the call with a tool error that ends "nothing was changed".

How it is asked depends on the request's protocol revision:

Revision Mechanism
2026-07-28 The call returns an InputRequiredResult (resultType: "input_required") whose inputRequests.confirm is the elicitation/create request, plus a requestState. The client asks its user and repeats the same call with inputResponses.confirm and the echoed requestState. The state is a hash of the tool and its arguments, so an answer cannot be reused for a different call. See MCP-REVISIONS.
2025-11-25 over stdio MDDB writes an elicitation/create request to stdout mid-call and waits for the client's response on stdin.
2025-11-25 over Streamable HTTP The tools/call POST is answered as an SSE stream: first the elicitation/create request, then — after the client POSTs its response to /mcp with the same Mcp-Session-Id (answered 202) — the tool's result. Without a question the response stays plain JSON.
The SSE transport (/sse) and the REST /mcp/tools/call Cannot ask: served as a client without elicitation.

Whether a handshake client can be asked is read from the capabilities it sent in initialize; a stateless client declares it per request in io.modelcontextprotocol/clientCapabilities.

The default stays off throughout 2.18.x and 2.19.x so existing deployments see no change; elicit is the intended future default.

Protocol Features #

Feature Description
Tool Annotations readOnlyHint, destructiveHint, idempotentHint, openWorldHint on all tools
Elicitation Destructive tools ask the user to confirm when MDDB_MCP_CONFIRM_DESTRUCTIVE is set — InputRequiredResult for 2026-07-28, elicitation/create for 2025-11-25. See Confirming Destructive Tools
Structured Output outputSchema on 9 key tools, and structuredContent conforming to it on every successful call of those tools (v2.19.12+). See Structured Output
5 Prompts analyze-collection, search-help, summarize-collection, import-guide, rag-pipeline
Completion Autocomplete for collection names and prompt arguments
Logging RFC 5424 levels (debug → emergency): logging/setLevel for handshake clients, io.modelcontextprotocol/logLevel per request for stateless ones
Progress Tokens notifications/progress for long-running operations
Cursor Pagination tools/list and resources/list
Resource Templates resources/templates/list — the patterns (mddb://{collection}/{key}) live here rather than among the readable resources
Discovery (2026-07-28) server/discover — supported revisions, capabilities and identity in one call
Caching Hints (2026-07-28) ttlMs + cacheScope on every list and read
Notifications notifications/initialized, notifications/cancelled
Memory RAG Tools 6 tools for conversational memory: start session, add message, recall, summarize, list sessions, history
Async Bulk Ingest Tools 4 tools for long-running ingest jobs: submit, status, list, cancel
Autocomplete Tool Prefix autocomplete over the FTS index — top-N suggestions ranked by document frequency
Per-Query Boost full_text_search and hybrid_search tools accept a boost map keyed by "metaKey:metaValue" to boost/demote matching documents at query time

Async Bulk Ingest Tools #

Queue long-running bulk ingest jobs from LLMs without blocking on the tool call. The worker drains jobs FIFO in 500-document chunks; status records persist across restarts.

Tool Description Write?
bulk_ingest_submit Queue a new job with documents + optional callback_url; returns job ID Yes
bulk_ingest_status Return current status record (counters, timestamps, errors) No
bulk_ingest_list List all jobs newest-first, optionally filtered by collection No
bulk_ingest_cancel Cancel a pending job (in-flight jobs run to completion) Yes

Autocomplete Tool #

Tool Description Write?
autocomplete Top-N prefix suggestions over the FTS inverted index, ranked by doc frequency; supports field scoping No

WordPress Publishing Tools #

Publish straight from MCP into WordPress sites running the mddb-sync plugin with Remote publishing enabled. Posts and pages, tags/categories/custom taxonomies, post meta ("metafields") and Polylang/WPML language assignment + translation linking are all supported.

Tool Description Write?
wordpress_publish Create or update a post/page (upsert by post_id, else post_type+slug) with content (Markdown or HTML), status, tags, categories, taxonomies, meta and language Yes
wordpress_set_status Change publishing status: publish, draft, pending, private, future (with date) or trash Yes

The target site comes from the collection's config — one collection per WordPress site, matching how the sync plugin pushes content in:

// 1. Pin the WordPress target to the collection (once)
{"name": "set_collection_config", "arguments": {
  "collection": "example_com",
  "wordpress": {"url": "https://example.com", "api_key": "<publish key from Settings → MDDB Sync>"}
}}

// 2. Publish a post with tags, meta and a language
{"name": "wordpress_publish", "arguments": {
  "collection": "example_com",
  "post_type": "post",
  "title": "Hello from MDDB",
  "content_markdown": "# Hello\n\nPublished via MCP.",
  "status": "publish",
  "tags": ["mddb", "mcp"],
  "categories": ["News"],
  "meta": {"seoTitle": "Hello from MDDB"},
  "lang": "en_US"
}}

// 3. Later: unpublish it
{"name": "wordpress_set_status", "arguments": {"collection": "example_com", "post_id": 123, "status": "draft"}}

The site URL must be https:// (plain http:// only for localhost). Both tools also accept explicit site_url + api_key arguments to skip the collection config. Translations: pass lang plus translation_of: <post id> to link a new post as a translation via Polylang or WPML.

Projection note: for search_documents / full_text_search / semantic_search / hybrid_search, passing fields now also drops the document body by default — pass include_content: true explicitly to keep it.

Memory RAG Tools #

Built-in MCP tools for conversational memory and RAG:

Tool Description Write?
memory_start_session Start a new conversation session Yes
memory_add_message Add a message (auto-embedded) Yes
memory_recall Semantic/hybrid/keyword recall across sessions No
memory_summarize Generate and store session summary Yes
memory_list_sessions List sessions with filters No
memory_session_history Get chronological message history No

Example: Agent with Memory #

// 1. Start session
{"name": "memory_start_session", "arguments": {"user_id": "user-1", "scenario": "support"}}

// 2. Store messages as conversation progresses
{"name": "memory_add_message", "arguments": {"session_id": "abc...", "role": "user", "content": "How do I use vector search?"}}
{"name": "memory_add_message", "arguments": {"session_id": "abc...", "role": "assistant", "content": "Use POST /v1/vector-search..."}}

// 3. In a future session, recall relevant context
{"name": "memory_recall", "arguments": {"query": "vector search usage", "user_id": "user-1", "top_k": 5, "include_content": true}}

// 4. Summarize when done
{"name": "memory_summarize", "arguments": {"session_id": "abc..."}}

Built-in Prompts #

Prompt Arguments Description
analyze-collection collection (required) Document count, metadata keys, content patterns, suggestions
search-help use_case (required) Which search method to use for your use case
summarize-collection collection (required), limit Topic overview, themes, distribution
import-guide source (required) Step-by-step import from wordpress/url/file/api/scraping
rag-pipeline collection (required), model RAG pipeline design with embedding and search strategy

Custom prompts #

Prompts of your own go in the MDDB_MCP_CONFIG file, next to custom_tools. They are listed by prompts/list after the built-in ones, and prompts/get renders them by substituting ``, the same substitution responsePrompt and automations use:

custom_prompts:
  - name: review_function
    description: "Review one function for a given category"
    arguments:
      - { name: function, required: true }
      - { name: category, required: true }
    template: |
      Review `` for : fetch it with codeFunctionFind,
      then similar changes with codeChangesSimilar, then report.

A missing required argument is an error. A missing optional one becomes empty. A name that clashes with a built-in prompt or another custom prompt, an unnamed argument, or a prompt without a template makes the set invalid: it is logged at startup and no custom prompts are served.


← Back to README | → LLM Connections | → Custom Tools