gRPC 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.
MDDB provides a high-performance gRPC API alongside the HTTP/JSON API. The gRPC API offers significant performance improvements through binary protocol buffers and HTTP/2.
Table of Contents #
- Overview
- Why gRPC?
- Getting Started
- Service Definition
- Client Examples
- Schema Validation RPCs
- Geo RPCs
- Curation RPCs
- FTS Maintenance RPCs
- Replication Service
- Not Yet Available over gRPC
- Performance Comparison
- Best Practices
Overview #
gRPC Endpoint: localhost:11024
Protocol: HTTP/2 + Protocol Buffers
Reflection: Enabled (for grpcurl and debugging)
Why gRPC? #
Performance Benefits #
| Feature | HTTP/JSON | gRPC |
|---|---|---|
| Payload Size | 100% | ~30% (70% smaller) |
| Serialization | JSON text | Binary protobuf |
| Transport | HTTP/1.1 | HTTP/2 |
| Compression | Optional gzip | Built-in |
| Streaming | Limited | Full duplex |
| Type Safety | Runtime | Compile-time |
Use Cases #
Use gRPC when:
- Performance is critical
- You need type safety
- Building microservices
- High-throughput operations
- Streaming large datasets
Use HTTP when:
- Debugging with curl
- Browser-based clients
- Simple integrations
- Human-readable logs
Getting Started #
Prerequisites #
# Install protoc (Protocol Buffer Compiler)
brew install protobuf
# Install Go gRPC tools
make install-grpc-tools
Testing with grpcurl #
# Install grpcurl
brew install grpcurl
# List available services
grpcurl -plaintext localhost:11024 list
# Describe a service
grpcurl -plaintext localhost:11024 describe mddb.MDDB
# Call a method
grpcurl -plaintext -d '{"collection":"blog","key":"test","lang":"en_US"}' \
localhost:11024 mddb.MDDB/Get
Service Definition #
The complete service definition is in proto/mddb.proto.
Available RPCs (116 implemented) #
| Category | RPC | Request → Response |
|---|---|---|
| Document Management | Add |
AddRequest → Document |
AddBatch |
AddBatchRequest → AddBatchResponse |
|
UpdateDocument |
UpdateDocumentRequest → Document |
|
UpdateBatch |
UpdateBatchRequest → UpdateBatchResponse |
|
DeleteDocument |
DeleteDocumentRequest → DeleteDocumentResponse |
|
DeleteBatch |
DeleteBatchRequest → DeleteBatchResponse |
|
DeleteWhere |
WhereRequest → WhereResponse (by metadata filter, with dry_run) |
|
UpdateWhere |
WhereRequest → WhereResponse |
|
SetTTLWhere |
WhereRequest → WhereResponse |
|
DeleteCollection |
DeleteCollectionRequest → DeleteCollectionResponse |
|
Get |
GetRequest → Document |
|
GetDocumentMeta |
GetDocumentMetaRequest → GetDocumentMetaResponse |
|
Search |
SearchRequest → SearchResponse |
|
Ingest |
IngestRequest → IngestResponse |
|
ImportURL |
ImportURLRequest → Document |
|
SetTTL |
SetTTLRequest → Document |
|
| Full-Text Search | FTS |
FTSRequest → FTSResponse |
FTSReindex |
FTSReindexRequest → FTSReindexResponse |
|
FTSLanguages |
FTSLanguagesRequest → FTSLanguagesResponse |
|
| Vector / Semantic | VectorSearch |
VectorSearchRequest → VectorSearchResponse |
VectorReindex |
VectorReindexRequest → VectorReindexResponse |
|
VectorStats |
VectorStatsRequest → VectorStatsResponse |
|
SearchAdvisor |
SearchAdvisorRequest → SearchAdvisorResponse |
|
GetIndexingStatus |
IndexingStatusRequest → IndexingStatusResponse (queued embeddings and metadata updates — is what was just written searchable yet?) |
|
RunEval |
RunEvalRequest → RunEvalResponse (recall@k, nDCG@k, MRR, latency and tokens per search configuration) |
|
AddEvalQuery |
AddEvalQueryRequest → EvalQueryProto |
|
ListEvalQueries |
ListEvalQueriesRequest → ListEvalQueriesResponse |
|
DeleteEvalQuery |
DeleteEvalQueryRequest → DeleteEvalQueryResponse |
|
GetGain |
GetGainRequest → GetGainResponse (tokens returned and avoided over a window of days) |
|
| Code | CodeSymbol |
CodeSymbolRequest → CodeSymbolResponse (definitions, references, callers, callees, tests and siblings of a symbol) |
| Geo | GeoSearch |
GeoSearchRequest → GeoSearchResponse |
GeoWithin |
GeoWithinRequest → GeoWithinResponse |
|
GeoReindex |
GeoReindexRequest → GeoReindexResponse |
|
GeoStats |
GeoStatsRequest → GeoStatsResponse |
|
GeoEncode |
GeoEncodeRequest → GeoEncodeResponse |
|
GeoDecode |
GeoDecodeRequest → GeoDecodeResponse |
|
| Hybrid & Cross | HybridSearch |
HybridSearchRequest → HybridSearchResponse |
CrossSearch |
CrossSearchRequest → CrossSearchResponse |
|
| Analysis | Classify |
ClassifyRequest → ClassifyResponse |
FindDuplicates |
FindDuplicatesRequest → FindDuplicatesResponse |
|
GetChecksum |
GetChecksumRequest → GetChecksumResponse |
|
GetMetaKeys |
GetMetaKeysRequest → GetMetaKeysResponse |
|
| Revisions | ListRevisions |
ListRevisionsRequest → ListRevisionsResponse |
RestoreRevision |
RestoreRevisionRequest → Document |
|
Truncate |
TruncateRequest → TruncateResponse |
|
| Export & Backup | Export |
ExportRequest → stream ExportChunk |
Backup |
BackupRequest → BackupResponse |
|
Restore |
RestoreRequest → RestoreResponse |
|
| FTS Config | ListSynonyms |
ListSynonymsRequest → ListSynonymsResponse |
AddSynonym |
AddSynonymRequest → AddSynonymResponse |
|
DeleteSynonym |
DeleteSynonymRequest → DeleteSynonymResponse |
|
ListStopwords |
ListStopwordsRequest → ListStopwordsResponse |
|
AddStopwords |
AddStopwordsRequest → AddStopwordsResponse |
|
DeleteStopwords |
DeleteStopwordsRequest → DeleteStopwordsResponse |
|
| Schemas | SetSchema |
SetSchemaRequest → SetSchemaResponse |
GetSchema |
GetSchemaRequest → GetSchemaResponse |
|
DeleteSchema |
DeleteSchemaRequest → DeleteSchemaResponse |
|
ListSchemas |
ListSchemasRequest → ListSchemasResponse |
|
ValidateDocument |
ValidateDocumentRequest → ValidateDocumentResponse |
|
| Webhooks | RegisterWebhook |
RegisterWebhookRequest → WebhookProto |
ListWebhooks |
ListWebhooksRequest → ListWebhooksResponse |
|
DeleteWebhook |
DeleteWebhookRequest → DeleteWebhookResponse |
|
| Automation | ListAutomation |
ListAutomationRequest → ListAutomationResponse |
CreateAutomation |
CreateAutomationRequest → AutomationRuleProto |
|
GetAutomation |
GetAutomationRequest → AutomationRuleProto |
|
UpdateAutomation |
UpdateAutomationRequest → AutomationRuleProto |
|
DeleteAutomation |
DeleteAutomationRequest → DeleteAutomationResponse |
|
TestAutomation |
TestAutomationRequest → TestAutomationResponse |
|
GetAutomationLogs |
GetAutomationLogsRequest → GetAutomationLogsResponse |
|
RunAutomation |
RunAutomationRequest → RunAutomationResponse (2.19.0: run a sync or backup rule now; job_id; Aborted while its previous run is going) |
|
| Collection Config | GetCollectionConfig |
GetCollectionConfigRequest → GetCollectionConfigResponse |
SetCollectionConfig |
SetCollectionConfigRequest → SetCollectionConfigResponse |
|
ListCollectionConfigs |
ListCollectionConfigsRequest → ListCollectionConfigsResponse |
|
| Curation | ListCurationRules |
ListCurationRulesRequest → ListCurationRulesResponse |
CreateCurationRule |
CreateCurationRuleRequest → CurationRuleProto |
|
UpdateCurationRule |
UpdateCurationRuleRequest → CurationRuleProto |
|
DeleteCurationRule |
DeleteCurationRuleRequest → DeleteCurationRuleResponse |
|
| Corpus Packs | ListCorpusPacks |
ListCorpusPacksRequest → ListCorpusPacksResponse |
InstallCorpusPack |
stream InstallCorpusPackRequest → InstallCorpusPackResponse |
|
RemoveCorpusPack |
RemoveCorpusPackRequest → RemoveCorpusPackResponse |
|
BuildCorpusPack |
BuildCorpusPackRequest → stream CorpusPackChunk |
|
| Chat Scenarios | ListChatScenarios |
ListChatScenariosRequest → ListChatScenariosResponse |
GetChatScenario |
GetChatScenarioRequest → ChatScenarioProto |
|
PutChatScenario |
PutChatScenarioRequest → PutChatScenarioResponse |
|
DeleteChatScenario |
DeleteChatScenarioRequest → DeleteChatScenarioResponse |
|
GetChatScenarioPrompt |
GetChatScenarioPromptRequest → GetChatScenarioPromptResponse |
|
| Chat Conversations | CreateChatConversation |
CreateChatConversationRequest → ChatConversationProto |
ListChatConversations |
ListChatConversationsRequest → ListChatConversationsResponse |
|
GetChatConversation |
GetChatConversationRequest → ChatConversationProto |
|
AppendChatMessages |
AppendChatMessagesRequest → ChatConversationProto |
|
EndChatConversation |
EndChatConversationRequest → ChatConversationProto |
|
DeleteChatConversation |
DeleteChatConversationRequest → DeleteChatConversationResponse |
|
DeleteChatConversationsForUser |
DeleteChatConversationsForUserRequest → DeleteChatConversationsForUserResponse |
|
ExportChatConversations |
ExportChatConversationsRequest → stream ChatConversationProto |
|
RateChatMessage |
RateChatMessageRequest → RateChatMessageResponse |
|
ListChatLog |
ListChatLogRequest → ListChatLogResponse |
|
ListChatGaps |
ListChatGapsRequest → ListChatGapsResponse |
|
| System | Stats |
StatsRequest → StatsResponse |
A separate mddb.MDDBReplication service exposes 4 additional RPCs for leader/follower replication — see Replication Service.
Full service definition: proto/mddb.proto
New in v2.19.6 #
Conditional create and delete, and the revision in search results (see conditional writes). New fields, additive with new numbers:
| Message | Field | Number | Meaning |
|---|---|---|---|
AddRequest |
if_absent |
8 | Create only: ABORTED, nothing written, when the document exists (#423) |
DeleteDocumentRequest |
expected_revision |
4 | Delete only at this revision; otherwise ABORTED, also for a missing document (#424) |
Search now fills Document.revision (9) on each result, the value Get
returns (#425). The checks run in the write's own transaction, so of two
racing creates exactly one succeeds.
New in v2.19.3 #
CodeSymbol answers from semantic facts where documents carry them
(mddb-cli autoindex --semantic; see
API). New fields, all
additive with new numbers:
| Message | Field | Number | Meaning |
|---|---|---|---|
CodeSymbolRequest |
path |
6 | The file (meta.path) of the one definition wanted |
CodeSymbolResponse |
implementations |
12 | Types implementing the interface; needs facts |
CodeSymbolResponse |
precision |
13 | semantic, mixed or heuristic; empty for a heuristic answer to a request without path or implementations |
CodeSymbolResponse |
semantic_source |
14 | Language servers behind the facts, e.g. gopls/0.24.0 |
CodeSymbolResponse |
ambiguous |
15 | Several definitions and no path chose one |
CodeSymbolResponse |
candidates |
16 | SymbolCandidate { path = 1, name = 2, kind = 3 }, the definitions an ambiguous name may mean |
CodeSymbolRequest |
exclude_tests |
7 | (v2.19.13) Leave out every passage in a test file, before limit. path may also name a directory |
CodeSymbolResponse |
totals |
17 | (v2.19.13) map<string, int32>: passages each cut relation held before limit |
Passage |
truncated |
16 | (v2.19.13) content was cut to the passage token bound; start_line and end_line are what is left |
Passage |
container |
14 | Type or class holding the definition |
Passage |
target |
15 | <path>#<qualified name> of the looked-up definition this passage is about |
include accepts implementations. A collection without facts answers with
none of these set.
New in v2.19.0 #
Chat scenarios (v2.19.0)
The chat scenario endpoints (/v1/chat/scenarios, #403) over gRPC, calling
the same server functions and gated with the same permissions:
| RPC | Permission | |
|---|---|---|
ListChatScenarios |
any valid credential; filtered to what the caller may read | scenarios (ChatScenarioProto) and version, the counter that grows on every change |
GetChatScenario |
read on every collection the scenario allows | {name} → ChatScenarioProto |
PutChatScenario |
admin, writable server | {scenario} → {scenario, created, version}; creates or replaces the scenario named in it |
DeleteChatScenario |
admin, writable server | {name} → {deleted, version} |
GetChatScenarioPrompt |
as GetChatScenario |
{name} → {name, prompt, version, bytes, approx_tokens, warning, missing_skills}: the composed system prompt and its size |
ChatScenarioProto mirrors the REST body: off_topic (mode,
redirect_template), style (emoji, verbosity, markdown,
citation_template), llm (model, temperature with temperature_set,
because 0 is a meaningful temperature, max_tokens, extra_body_json,
a JSON object as a string, and since 2.19.2 loop_guard — ChatLoopGuardProto:
optional bool enabled, ngram, window, ratio, min_output, unit, each
0 or empty for "keep mddb-chat's [llm.loop_guard] value", #413),
rate_limit (messages_per_minute),
mcp_servers (ChatMcpServerProto, since 2.19.0: name, url, enabled,
secret_ref, allowed_tools, timeout_ms, result_max_chars, and since
2.19.2 forward_identity — ChatMcpForwardIdentityProto {secret_ref, header, ttl_seconds}, #414), and created_at / updated_at in Unix seconds.
GetChatScenarioPrompt also returns mcp_servers (ChatMcpServerStateProto:
active and reason per server and per allowed tool, and
forward_identity).
Errors map as on REST: INVALID_ARGUMENT (400), NOT_FOUND (404),
PERMISSION_DENIED (403), UNAUTHENTICATED (401).
grpcurl -plaintext localhost:11024 mddb.MDDB/ListChatScenarios
grpcurl -plaintext -d '{"name":"support"}' localhost:11024 mddb.MDDB/GetChatScenarioPrompt
See API.
Features (v2.19.0)
The module switches (/v1/features, GO-049) over gRPC.
| RPC | Permission | |
|---|---|---|
ListFeatures |
authenticated | features (FeatureProto: name, title and summary (v2.19.11+, plain texts for people), description (technical detail), enabled, configured, default_enabled, requires, locked_by, blocked_by, updated_at in Unix seconds, updated_by) and version |
SetFeature |
admin, writable server | {name, enabled} → {feature, version}; NOT_FOUND for an unknown module, FAILED_PRECONDITION when MDDB_FEATURES_FORCE_OFF locks it |
Every RPC of a disabled module answers FAILED_PRECONDITION
feature disabled: <name> (after authentication). Replication and core RPCs
are never switched.
grpcurl -plaintext localhost:11024 mddb.MDDB/ListFeatures
grpcurl -plaintext -d '{"name":"geo","enabled":false}' localhost:11024 mddb.MDDB/SetFeature
See API.
Chat skills (v2.19.0)
The chat skill endpoints (/v1/chat/skills, #404) over gRPC. Every RPC
needs a global administrator, reads included: a skill's text is part of
system prompts.
| RPC | Permission | |
|---|---|---|
ListChatSkills |
admin | skills (ChatSkillProto, without content) and version, the scenarios' counter |
GetChatSkill |
admin | {name, version} → ChatSkillProto; version 0 is the current one |
PutChatSkill |
admin, writable server | {skill} → {skill, created, version}; reads name, description, content, source |
DeleteChatSkill |
admin, writable server | {name} → {deleted, version}; FAILED_PRECONDITION naming the scenarios while one attaches it |
ImportChatSkill |
admin | {url} or {content} → ChatSkillPreviewProto (name, description, content, raw, source, bytes, sha256, exists); stores nothing |
UpdateChatSkill |
admin, writable server | {name, confirm, sha256} → {skill, preview, changed, saved, version}; ABORTED when the source changed since the preview |
GetChatSkillUsedBy |
admin | {name} → {name, scenarios} |
ChatSkillProto carries source (url, commit, fetched_at), version,
history (ChatSkillRevisionProto: version, description, bytes,
source, updated_at, without contents), bytes, used_by and the times
in Unix seconds. Other errors map as on REST.
grpcurl -plaintext -d '{"url":"https://github.com/blader/humanizer/blob/main/SKILL.md"}' localhost:11024 mddb.MDDB/ImportChatSkill
grpcurl -plaintext -d '{"name":"humanizer"}' localhost:11024 mddb.MDDB/UpdateChatSkill
See API.
External MCP servers of the chat (v2.19.0)
The external MCP server endpoints (/v1/chat/mcp-secrets, /v1/chat/mcp,
MCP-005) over gRPC. Secrets are write-only: no RPC returns a value.
| RPC | Permission | |
|---|---|---|
ListChatMcpSecrets |
admin | secrets (ChatMcpSecretProto: name, header, set, updated_at, used_by) and encryption_ready, false while no MDDB_ENCRYPTION_KEY is loaded |
PutChatMcpSecret |
admin, writable server | {name, value, header} → {secret, created, version}; FAILED_PRECONDITION naming MDDB_ENCRYPTION_KEY without an at-rest key: a secret is stored only sealed |
DeleteChatMcpSecret |
admin, writable server | {name} → {deleted, version}; FAILED_PRECONDITION naming the scenarios while one uses it |
InspectChatMcpServer |
admin | {url, secret_ref} → {url, server_name, server_version, protocol_version, tools}; FAILED_PRECONDITION while the chatExternalMcp feature is off or for a secret_ref stored unsealed, UNAVAILABLE when the server cannot be reached |
CallChatMcpTool |
read on the scenario; write on the chat collection for a forward_identity server |
{scenario, server, tool, arguments_json, sub} → {content, is_error, truncated, duration_ms}; FAILED_PRECONDITION for a switch that is off, a tool not allowed, or a forward_identity server called without sub (2.19.2, #414) |
ChatMcpToolProto carries read_only_hint and destructive_hint, each
with a *_set flag (an absent hint is not false), allowable and the
reason a scenario may not allow it. A timeout or an upstream failure of
CallChatMcpTool is not an RPC error: is_error is set and content says
what happened in one line.
grpcurl -plaintext -d '{"name":"wiki","value":"…"}' localhost:11024 mddb.MDDB/PutChatMcpSecret
grpcurl -plaintext -d '{"url":"https://wiki.example.com/mcp","secret_ref":"wiki"}' localhost:11024 mddb.MDDB/InspectChatMcpServer
See API.
Chat conversations (v2.19.0)
Persistent per-user chat conversations (/v1/chat/conversations, #405) over
gRPC, on the same store and the same functions as REST: a conversation
written over one transport reads the same over the other, and a list cursor
from one works on the other. The caller is the host application; every
request names the user (sub), and a conversation of another sub is
NOT_FOUND, as a missing one is. The model, limits, retention and the join
token sub comes from are in
API.
| RPC | Permission | |
|---|---|---|
CreateChatConversation |
write, writable server | {sub, scenario, display_name, retention_days} → the conversation (ChatConversationProto) |
ListChatConversations |
read | {sub, scenario, limit, cursor} → conversations (no messages), newest first, and next_cursor |
GetChatConversation |
read | {id, sub, limit} → the conversation with its last limit messages (all when 0), oldest first |
AppendChatMessages |
write, writable server | {id, sub, messages} (1 to 100 ChatMessageProto) → the conversation holding only the messages added, with their ids |
EndChatConversation |
write, writable server | {id, sub} → the conversation, ended |
DeleteChatConversation |
write, writable server | {id, sub} → {deleted, id} |
DeleteChatConversationsForUser |
write, writable server | {sub} → {deleted, sub}: everything of a user (GDPR erasure) |
ExportChatConversations |
read | {sub} → a stream of ChatConversationProto, one conversation per message with all its messages (GDPR export). A stream, so a long history is not bound by the 4 MiB message limit |
The permission is on the chat collection of the caller's tenant
(chat_conversations, or <tenant>/chat_conversations). ChatMessageProto
carries the token usage flat, as prompt_tokens and completion_tokens
(REST: tokens.prompt, tokens.completion).
Errors map as on REST: INVALID_ARGUMENT (400: no sub, a refused message),
NOT_FOUND (404), FAILED_PRECONDITION (409: an append to an ended
conversation), UNAUTHENTICATED (401), PERMISSION_DENIED (403).
grpcurl -plaintext -d '{"sub":"user-42","scenario":"support"}' localhost:11024 mddb.MDDB/CreateChatConversation
grpcurl -plaintext -d '{"id":"<id>","sub":"user-42","messages":[{"role":"user","content":"hi"}]}' \
localhost:11024 mddb.MDDB/AppendChatMessages
grpcurl -plaintext -d '{"sub":"user-42"}' localhost:11024 mddb.MDDB/ExportChatConversations
Answer feedback and the conversation log (v2.19.0, #406)
The rating of an answer and the admin review of the turn log, as
POST /v1/chat/conversations/{id}/feedback, GET /v1/chat/log and
GET /v1/chat/gaps (API).
| RPC | Permission | |
|---|---|---|
RateChatMessage |
write on the chat collection, writable server — as AppendChatMessages |
{id, sub, message_id, rating, comment} → {conversation_id, message_id, feedback}; rating is up or down, comment at most 2000 characters; NOT_FOUND for a message that is not an answer of the conversation |
ListChatLog |
global admin | {scenario, from, to, rating, outcome, cursor, limit} → turns (ChatLogTurnProto) newest first and next_cursor; from/to are unix seconds (0: no bound) |
ListChatGaps |
global admin | {scenario, from, to, min_count, threshold, limit} → gaps (ChatGapProto: question, example, count, no_results, last_asked_at, scenarios) and the threshold used |
The export (GET /v1/chat/log/export, CSV or JSON) is REST only: walk
ListChatLog with its cursor for the same turns over gRPC.
Since 2.19.2 (#413) ChatMessageProto (field 13) and ChatLogTurnProto
(field 20) carry loop_stopped: mddb-chat's repetition-loop guard cut that
answer short.
Additive message fields: ChatMessageProto gains outcome (answered,
noResults, refused, error — a logged turn), latency_ms and feedback
(ChatFeedbackProto: rating, comment, at), and keeps an id the
client sends when it matches [A-Za-z0-9_-]{1,64}; ChatToolCallProto gains
query, result_keys, top_score and server (the external MCP server of the tool, MCP-005); AppendChatMessagesRequest gains
redact (sticky: the conversation's redact is set and every later write of
it is redacted). ChatScenarioProto gains logging (ChatLoggingProto:
enabled, retention_days, optional bool redact — unset means on).
grpcurl -plaintext -d '{"id":"<id>","sub":"user-42","message_id":"<answer id>","rating":"down","comment":"Wrong port"}' \
localhost:11024 mddb.MDDB/RateChatMessage
grpcurl -plaintext -H "authorization: Bearer $ADMIN_TOKEN" -d '{"rating":"down","limit":20}' localhost:11024 mddb.MDDB/ListChatLog
grpcurl -plaintext -H "authorization: Bearer $ADMIN_TOKEN" -d '{"min_count":2}' localhost:11024 mddb.MDDB/ListChatGaps
Corpus packs (v2.19.0)
The corpus pack endpoints (/v1/corpus/*, AGT-005) over gRPC, calling the
same server functions and gated with the same permissions:
| RPC | Permission | |
|---|---|---|
ListCorpusPacks |
read, filtered to the caller's tenant | packs (CorpusPackProto: collection, read_only, corpus as CorpusInfoProto) and total |
InstallCorpusPack |
admin, writable server | client stream. The first message holds either url (an https:// URL the server downloads through its SSRF guard, no redirect out of TLS) or the first data chunk; sha256, in the first message, is the pack file's checksum, checked before anything is installed. Capped at MDDB_CORPUS_MAX_BYTES |
RemoveCorpusPack |
admin, writable server | {name} → {status, name, deleted} |
BuildCorpusPack |
admin | {collection, version, description, license, sources}, or name and collections (CorpusCollectionProto{name, license, sources}, v2.19.11) instead of collection → a stream of CorpusPackChunk (at most 1 MiB of data each); the first also carries filename and doc_count |
Errors map as on REST: INVALID_ARGUMENT (400), NOT_FOUND (404),
ALREADY_EXISTS (409), PERMISSION_DENIED (403), INTERNAL (500).
grpcurl -plaintext localhost:11024 mddb.MDDB/ListCorpusPacks
grpcurl -plaintext -d '{"url":"https://example.org/k8s-docs-1.31.mddbpack","sha256":"<sum>"}' \
localhost:11024 mddb.MDDB/InstallCorpusPack
See CORPUS-PACKS.
Quota usage, sync rules, corpus collections and result limits #
GetCollectionConfigResponse.usage (4, CollectionQuotaUsageProto) is what
a collection with a quota uses of it (GO-043): documents, bytes,
vectors, and today's (UTC) embedding_calls and embedding_tokens —
compare each with the CollectionQuotaProto limit. Unset for a collection
without a quota. The same numbers as REST GET /v1/collection-config
(usage); see API.
CollectionFTSProto.exclude_meta_keys (2) lists meta keys kept out of
full-text search (#367): no meta.<key> postings, so changing them costs no
full-text work, while metadata filters and facets still use them. It applies
to documents written afterwards; call FTSReindex after changing it. Every
write path — Add, AddBatch, UpdateDocument and UpdateBatch — now
re-indexes only what changed; UpdateBatch did not re-index full text at all
before.
UpdateBatch now runs the same after-write step as every other write
(GO-048): the embedding queue, geo, temporal tracking, the doc.updated
webhook and SSE event, and automation triggers, which it never fired; a
document's vectors and geo point followed its old content and meta until a
reindex. UpdateDocument now sends the SSE event too. An empty content_md
in UpdateBatch still means "leave the content as it is"; to empty a
document, use UpdateDocument with update_content: true or Add. An
emptied document loses its content postings and vectors and keeps its meta
fields in full-text search.
AutomationRuleProto.sync (26, SyncActionProto) is a cron rule's third
action: keep a collection in step with a sitemap, a URL list or an S3
prefix (source, collection, lang, url, urls, bucket, prefix,
storage_config, prune, max_documents, max_bytes). Validation,
defaults and secret masking are those of the REST body; see
AUTOMATIONS. Since 2.19.5 source may
be git (a repository at a branch, a tag or its latest release), with
ref (12), include (13), exclude (14), forge (15),
token_secret_ref (16), hook_secret_ref (17) and adopt (18); a git
run's AutomationRunResultProto adds ref (10), commit (11),
commit_url (12) and up_to_date (13). See
AUTOMATIONS.
CollectionConfigProto.read_only (23) and corpus (24, CorpusInfoProto:
name, version, license, building server version, document count, archive
sha256, install time in unix seconds, vectors_disabled and the pack's
embedding provider, model and dimensions) show a collection installed from a
corpus pack. Both are output only: SetCollectionConfig keeps them as
stored. Every write to a read-only collection answers PERMISSION_DENIED;
see CORPUS-PACKS.
IndexingStatusResponse.training_collections (11) lists the collections
whose IVF, PQ, OPQ, SQ and SQ4 indexes are still training after a load
(GO-047), as trainingCollections does over REST. VectorSearch with one of
those algorithms on such a collection answers UNAVAILABLE naming it; flat and
HNSW answer already.
Every search RPC's result count is capped by MDDB_SEARCH_MAX_LIMIT (default
1000) and the collection's RetrievalProfileProto.max_top_k (17), which can
only lower the server value (#368). When the cap lowered a request's
limit / top_k, the response says so in two new fields:
| Response | limit_capped |
limit |
|---|---|---|
FTSResponse |
9 | 10 |
SearchResponse |
3 | 4 |
VectorSearchResponse |
11 | 12 |
HybridSearchResponse |
12 | 13 |
CrossSearchResponse |
11 | 12 |
CodeSymbolResponse |
10 | 11 |
GeoSearchResponse |
5 | 6 |
limit is the count used and is set only with limit_capped; a request under
the cap leaves both at their zero values, so its response is unchanged. See
SEARCH.
Query planner, relevance feedback, summaries, images and backups #
The query planner (SRCH-013) is available over gRPC. VectorSearch and
CrossSearch take algorithm: "auto"; HybridSearch takes
vector_algorithm: "auto". All three requests gained explain and
latency_target_ms:
| Field | Number on VectorSearchRequest / HybridSearchRequest / CrossSearchRequest |
Meaning |
|---|---|---|
explain |
19 / 28 / 20 | Return plan with the response |
latency_target_ms |
20 / 29 / 21 | Latency goal for auto, 0–60000 ms |
The responses carry SearchPlan plan: field 9 on VectorSearchResponse, 10
on the other two. A plan has algorithm, prefilter, candidates,
iterative_scan, reasons, strategy (9, v2.19.8: how a filtered search ran — prefilter, graph+filter, ivf or scan+filter) and, for cross search, one SearchPlan per
target in collections. RetrievalProfileProto.vector_algorithm (14) stores
a collection's default, for example "auto". The table the planner decides by
is in SEARCH.
Relevance feedback (SRCH-015) is available on the same three requests:
| Field | Number on VectorSearchRequest / HybridSearchRequest / CrossSearchRequest |
Meaning |
|---|---|---|
positive, negative (repeated FeedbackExample) |
21–22 / 30–31 / 22–23 | Examples: key (a document key or ID) or vector |
feedback_mode |
23 / 32 / 24 | query (default) or rescore |
feedback_weight |
24 / 33 / 25 | Rescore weight; 0 = 0.5 |
rocchio (RocchioWeights) |
25 / 34 / 26 | optional double alpha, beta, gamma; unset = 1, 0.75, 0.25 |
With explain, SearchPlan.feedback (7, FeedbackApplied) reports the
correction. An example that names nothing usable is INVALID_ARGUMENT. All
of this is additive.
Query decomposition (SRCH-020) is string query_decomposition on
VectorSearchRequest (28) and HybridSearchRequest (36): off (default)
or auto. With explain, SearchPlan.decomposition (8,
QueryDecomposition) holds int32 parts (1 = not split) and repeated string texts. Another mode is INVALID_ARGUMENT. See
SEARCH.
Summaries (RAG-009) need no new request field. A document carries its
client-written summary in the metadata key summary. The collection profile
decides what searches do with it, and VectorSearch and HybridSearch
follow it:
| Field | Message | Meaning |
|---|---|---|
summary_mode (15) |
RetrievalProfileProto |
off (default), blend or expand; see SEARCH |
summary_weight (16, optional double) |
RetrievalProfileProto |
BM25F weight of meta.summary while summaries are on, 0–10; unset = 2.0 |
summary_mode (10) |
EvalConfigProto |
Measure a mode with RunEval; empty = the profile's |
summary_documents (13), summary_ratio (14) |
CollectionProfile |
Sampled documents with a summary, and their share |
summary_mode (11) |
SearchAdvisorResponse |
blend when at least half the sampled documents have a summary |
With expand and format: "passages", a summary hit returns one passage per
chunk it brought in. All of this is additive.
Images (RAG-010) are additive fields; see SEARCH:
| Field | Message | Meaning |
|---|---|---|
include_images |
VectorSearchRequest (26), FTSRequest (17), HybridSearchRequest (35), CrossSearchRequest (27) |
Attach each hit's images; on vector and hybrid also return image_hits when image vectors exist |
query_image (27) |
VectorSearchRequest |
Search by an image: base64, a data URI or an http(s) URL. FAILED_PRECONDITION without a provider that embeds images, INVALID_ARGUMENT for an unreadable image |
images (repeated ImageRef) |
VectorSearchResult (10), FTSResult (7), HybridSearchResult (11), CrossSearchResultItem (7), Passage (13) |
The hit's image documents |
image_hits (repeated ImageRef) |
VectorSearchResponse (10), HybridSearchResponse (11) |
Images the query matched by their picture |
images (ImageIndexingStatus, 10) |
IndexingStatusResponse |
documents, embedded, model, note; unset without images |
images (repeated IngestImage, 12) |
IngestDocument |
Files a Markdown document's links name: path, content |
extract_images (7), fetch_remote_images (8) |
IngestOptions |
Store Markdown and PDF images as image documents; fetch http(s) links |
ImageRef is key, lang, alt_text, caption, page, mime_type,
width, height, parent, score (image hits) and url.
Scheduled backups (OPS-023) and the lexical provider (SRCH-014) reach gRPC too:
| Field | Message | Meaning |
|---|---|---|
backup (25, BackupActionProto) |
AutomationRuleProto |
A cron rule's backup, instead of webhook_id; unset on UpdateAutomation keeps the stored backup unless webhook_id is set |
target (1), path (2), bucket (3), prefix (4), keep (5, int32), collections (6, repeated) |
BackupActionProto |
As the REST backup block; see AUTOMATIONS |
storage_config (7, StorageConfigProto) |
BackupActionProto |
S3 endpoint, region, credentials, TLS. secret_key is write-only: reads return it empty with secret_key_set: true, and an update without one keeps the stored key |
semantic (15, optional bool) |
CollectionProfile |
false for the lexical provider, true for a model; unset when nothing is embedded |
Validation and masking are the REST code, so a rule is the same whichever surface wrote it. All of this is additive.
Shared search options, indexing status and filter-based writes #
GetIndexingStatus reports queued work for a collection, or for the server
when collection is empty (GO-042), as GET /v1/indexing-status does.
RetrievalProfileProto gained group_by_key (9) and group_by_per_group
(10), the collection's default result grouping (SRCH-016), and format (11,
AGT-002). Document.revision (9) and UpdateDocumentRequest.expected_revision
(10) make updates conditional (INT-021): a stale revision is ABORTED.
CodeConfigProto.role (2) marks reference collections (AGT-003).
The search RPCs run the shared search code. FTS, VectorSearch,
HybridSearch and CrossSearch call the code that REST and MCP use. They take the same options:
| Field | On | Meaning |
|---|---|---|
filter (map<string, MetaCondition>) |
Search, FTS, VectorSearch, HybridSearch, CrossSearch |
Operators any_of (REST in), prefix, contains, gt/gte/lt/lte, none_of (REST not), exists; ANDed with filter_meta (SRCH-017) |
group_by (GroupBy) |
FTS, VectorSearch, HybridSearch, CrossSearch |
At most per_group results per metadata value, document or collection; results carry group and group_rank (SRCH-016) |
format, passage_lines |
the same four | "passages" returns repeated Passage passages: a path, lines, the enclosing symbol and the text (AGT-002) |
passage_tokens |
the same four | (v2.19.13) Most tokens per passage (default 500, max 8000); a cut passage has truncated set |
wait_for_index_ms, wait_for_keys, read_level |
VectorSearch, HybridSearch, CrossSearch |
Wait for queued embeddings; the response carries indexing (GO-042) |
retrieval_mode, window_size |
VectorSearch |
chunk and window modes; results carry chunk_text, start_line, end_line |
bm25_k1, bm25_b |
FTS, HybridSearch, EvalConfigProto, RetrievalProfileProto |
BM25 parameters (SRCH-018); unset = the collection profile, then 1.2 / 0.75 |
search_type |
CrossSearch |
vector (default), fts or hybrid; targets may be role:reference (AGT-003) |
any_of and none_of are named for the REST in and not, which are
keywords in Python. Behaviour now matches REST and MCP. The collection's
context budget applies, and so do curation rules on hybrid search, which MCP
did not apply before either. Errors map as follows. A vector index still
loading is UNAVAILABLE. No embedding provider is FAILED_PRECONDITION. A
cross-search source document without a vector is NOT_FOUND. An invalid
option is INVALID_ARGUMENT.
DeleteWhere, UpdateWhere and SetTTLWhere (GO-045) act on every
document a metadata filter matches. They share one WhereRequest: filter,
filter_meta, limit, cursor, dry_run, meta and ttl.
The new RPCs CodeSymbol, RunEval, AddEvalQuery, ListEvalQueries,
DeleteEvalQuery and GetGain match GET /v1/symbol, POST /v1/eval,
/v1/eval-queries and GET /v1/gain.
All of this is additive. Clients built against an older proto keep working.
Per-query boost #
FTSRequest and HybridSearchRequest each have a map<string, double> boost field (field number 8 on FTSRequest, 15 on HybridSearchRequest) for per-query metadata-based score boosting/demotion. Keys are in "metaKey:metaValue" form; positive values multiply matching documents' scores, negative values demote. Adding fields is backwards compatible — clients compiled against an older proto continue to work and simply omit the new field. See SEARCH.md — Per-Query Boost/Demote for semantics.
Message Types #
Document
message Document {
string id = 1;
string key = 2;
string lang = 3;
map<string, MetaValues> meta = 4;
string content_md = 5;
int64 added_at = 6;
int64 updated_at = 7;
}
AddRequest
message AddRequest {
string collection = 1;
string key = 2;
string lang = 3;
map<string, MetaValues> meta = 4;
string content_md = 5;
}
Client Examples #
Go Client #
package main
import (
"context"
"log"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
pb "mddb/proto"
)
func main() {
// Connect to server
conn, err := grpc.Dial("localhost:11024",
grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Fatal(err)
}
defer conn.Close()
client := pb.NewMDDBClient(conn)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// Add a document
doc, err := client.Add(ctx, &pb.AddRequest{
Collection: "blog",
Key: "hello-world",
Lang: "en_US",
Meta: map[string]*pb.MetaValues{
"category": {Values: []string{"blog", "tutorial"}},
"author": {Values: []string{"John Doe"}},
},
ContentMd: "# Hello World\n\nWelcome to MDDB!",
})
if err != nil {
log.Fatal(err)
}
log.Printf("Document added: %s", doc.Id)
// Get a document
doc, err = client.Get(ctx, &pb.GetRequest{
Collection: "blog",
Key: "hello-world",
Lang: "en_US",
Env: map[string]string{
"year": "2024",
},
})
if err != nil {
log.Fatal(err)
}
log.Printf("Content: %s", doc.ContentMd)
// Search documents
resp, err := client.Search(ctx, &pb.SearchRequest{
Collection: "blog",
FilterMeta: map[string]*pb.MetaValues{
"category": {Values: []string{"blog"}},
},
Sort: "updatedAt",
Asc: false,
Limit: 10,
})
if err != nil {
log.Fatal(err)
}
log.Printf("Found %d documents", len(resp.Documents))
// Get stats
stats, err := client.Stats(ctx, &pb.StatsRequest{})
if err != nil {
log.Fatal(err)
}
log.Printf("Total documents: %d", stats.TotalDocuments)
}
Python Client #
import grpc
import mddb_pb2
import mddb_pb2_grpc
# Connect to server
channel = grpc.insecure_channel('localhost:11024')
client = mddb_pb2_grpc.MDD BStub(channel)
# Add a document
doc = client.Add(mddb_pb2.AddRequest(
collection='blog',
key='hello-world',
lang='en_US',
meta={
'category': mddb_pb2.MetaValues(values=['blog', 'tutorial']),
'author': mddb_pb2.MetaValues(values=['John Doe'])
},
content_md='# Hello World\n\nWelcome to MDDB!'
))
print(f'Document added: {doc.id}')
# Get a document
doc = client.Get(mddb_pb2.GetRequest(
collection='blog',
key='hello-world',
lang='en_US',
env={'year': '2024'}
))
print(f'Content: {doc.content_md}')
# Search documents
resp = client.Search(mddb_pb2.SearchRequest(
collection='blog',
filter_meta={
'category': mddb_pb2.MetaValues(values=['blog'])
},
sort='updatedAt',
asc=False,
limit=10
))
print(f'Found {len(resp.documents)} documents')
# Get stats
stats = client.Stats(mddb_pb2.StatsRequest())
print(f'Total documents: {stats.total_documents}')
Node.js Client #
const grpc = require('@grpc/grpc-js');
const protoLoader = require('@grpc/proto-loader');
// Load proto file
const packageDefinition = protoLoader.loadSync('mddb.proto', {
keepCase: true,
longs: String,
enums: String,
defaults: true,
oneofs: true
});
const mddb = grpc.loadPackageDefinition(packageDefinition).mddb;
// Create client
const client = new mddb.MDDB('localhost:11024',
grpc.credentials.createInsecure());
// Add a document
client.Add({
collection: 'blog',
key: 'hello-world',
lang: 'en_US',
meta: {
category: { values: ['blog', 'tutorial'] },
author: { values: ['John Doe'] }
},
content_md: '# Hello World\n\nWelcome to MDDB!'
}, (err, doc) => {
if (err) throw err;
console.log(`Document added: ${doc.id}`);
});
// Get a document
client.Get({
collection: 'blog',
key: 'hello-world',
lang: 'en_US',
env: { year: '2024' }
}, (err, doc) => {
if (err) throw err;
console.log(`Content: ${doc.content_md}`);
});
// Search documents
client.Search({
collection: 'blog',
filter_meta: {
category: { values: ['blog'] }
},
sort: 'updatedAt',
asc: false,
limit: 10
}, (err, resp) => {
if (err) throw err;
console.log(`Found ${resp.documents.length} documents`);
});
// Get stats
client.Stats({}, (err, stats) => {
if (err) throw err;
console.log(`Total documents: ${stats.total_documents}`);
});
Schema Validation RPCs #
Schema validation enforces structure on document metadata per collection. See the Schema Validation Guide for full details.
Message Types #
The schema travels as a JSON string (the same document /v1/schema/set
takes), not as a structured message.
message SetSchemaRequest {
string collection = 1;
string schema = 2; // JSON Schema string
}
message SetSchemaResponse {
string status = 1;
}
message GetSchemaRequest {
string collection = 1;
}
message GetSchemaResponse {
string collection = 1;
string schema = 2;
bool enabled = 3;
}
message DeleteSchemaRequest {
string collection = 1;
}
message DeleteSchemaResponse {
string status = 1;
}
message ListSchemasRequest {}
message ListSchemasResponse {
repeated SchemaInfo schemas = 1;
}
message SchemaInfo {
string collection = 1;
string schema = 2;
}
message ValidateDocumentRequest {
string collection = 1;
map<string, MetaValues> meta = 2;
}
message ValidateDocumentResponse {
bool valid = 1;
repeated string errors = 2;
repeated string warnings = 3; // advisory, never fail validation (DOC-012)
}
grpcurl Examples #
# Set a schema for a collection
grpcurl -plaintext -d '{
"collection": "blog",
"schema": "{\"required\":[\"category\",\"author\"],\"properties\":{\"category\":{\"type\":\"string\",\"enum\":[\"blog\",\"tutorial\",\"news\"]},\"author\":{\"type\":\"string\"}}}"
}' localhost:11024 mddb.MDDB/SetSchema
# Get schema for a collection
grpcurl -plaintext -d '{"collection": "blog"}' \
localhost:11024 mddb.MDDB/GetSchema
# Delete schema
grpcurl -plaintext -d '{"collection": "blog"}' \
localhost:11024 mddb.MDDB/DeleteSchema
# List all schemas
grpcurl -plaintext -d '{}' \
localhost:11024 mddb.MDDB/ListSchemas
# Validate metadata against schema
grpcurl -plaintext -d '{
"collection": "blog",
"meta": {
"category": {"values": ["blog"]},
"author": {"values": ["John Doe"]}
}
}' localhost:11024 mddb.MDDB/ValidateDocument
Go Client Example #
// Set a schema
_, err := client.SetSchema(ctx, &pb.SetSchemaRequest{
Collection: "blog",
// The schema is a JSON document in a string.
Schema: `{"required":["category","author"],
"properties":{"category":{"type":"string","enum":["blog","tutorial","news"]},
"author":{"type":"string"}}}`,
})
// Validate a document before adding
resp, err := client.ValidateDocument(ctx, &pb.ValidateDocumentRequest{
Collection: "blog",
Meta: map[string]*pb.MetaValues{
"category": {Values: []string{"blog"}},
"author": {Values: []string{"Jane Doe"}},
},
})
if resp.Valid {
log.Println("Metadata is valid")
} else {
log.Printf("Validation errors: %v", resp.Errors)
}
Geo RPCs #
Geospatial search over documents with lat/lng metadata, backed by an in-memory R-tree. Implemented in services/mddbd/geo_grpc.go.
GeoSearch #
Finds documents within radius_meters of a (lat, lng) point, ordered by ascending distance.
message GeoSearchRequest {
string collection = 1;
double lat = 2;
double lng = 3;
double radius_meters = 4;
int32 top_k = 5;
map<string, MetaValues> filter_meta = 6;
bool include_content = 7;
}
message GeoSearchResultItem {
Document document = 1;
double distance_meters = 2;
int32 rank = 3;
}
message GeoSearchResponse {
repeated GeoSearchResultItem results = 1;
int32 total = 2;
double radius_meters = 3;
string algorithm = 4;
}
GeoWithin #
Finds documents inside the axis-aligned bounding box [min_lat, max_lat] × [min_lng, max_lng].
message GeoWithinRequest {
string collection = 1;
double min_lat = 2;
double max_lat = 3;
double min_lng = 4;
double max_lng = 5;
map<string, MetaValues> filter_meta = 6;
bool include_content = 7;
}
message GeoWithinResponse {
repeated GeoSearchResultItem results = 1;
int32 total = 2;
string algorithm = 3;
}
GeoReindex #
Force-rebuilds the in-memory geo R-tree from BoltDB and optionally loads postcode lookup CSVs. An empty collection means "rebuild all".
message GeoPostcodeLoadProto {
string country = 1;
string csv_path = 2;
}
message GeoReindexRequest {
string collection = 1;
repeated GeoPostcodeLoadProto load_postcodes = 2;
}
message GeoReindexResponse {
int32 points = 1;
string collection = 2;
map<string, int32> postcodes_loaded = 3;
int64 duration_ms = 4;
}
GeoStats #
Returns geo index statistics per collection plus loaded postcode datasets.
message GeoStatsRequest {}
message GeoCollectionStatProto {
int32 points = 1;
int64 last_rebuild_unix = 2;
}
message GeoStatsResponse {
map<string, GeoCollectionStatProto> collections = 1;
map<string, int32> postcode_datasets = 2;
bool ready = 3;
}
GeoEncode #
Encodes a (lat, lng) pair into a geohash string at the requested precision.
message GeoEncodeRequest {
double lat = 1;
double lng = 2;
int32 precision = 3;
}
message GeoEncodeResponse {
string geohash = 1;
int32 precision = 2;
}
GeoDecode #
Decodes a geohash back to its centroid (lat, lng) and bounding box.
message GeoDecodeRequest {
string geohash = 1;
}
message GeoDecodeResponse {
double lat = 1;
double lng = 2;
double min_lat = 3;
double max_lat = 4;
double min_lng = 5;
double max_lng = 6;
}
grpcurl Example #
grpcurl -plaintext -d '{
"collection": "places",
"lat": 51.5074,
"lng": -0.1278,
"radius_meters": 5000,
"top_k": 10
}' localhost:11024 mddb.MDDB/GeoSearch
Curation RPCs #
Curation rules let editors pin specific documents to fixed positions and hide others for a given query, overriding organic ranking. Rules are persisted in the curation bucket and applied in the FTS and HybridSearch post-processing stages. Implemented in services/mddbd/grpc_curation.go.
Message Types #
message PinnedDocProto {
string key = 1;
string lang = 2;
int32 position = 3; // 1-based; <=0 means "append after organic results"
}
message CurationRuleProto {
string id = 1;
string collection = 2;
string query = 3;
string match_mode = 4; // "exact" (default) or "contains"
repeated PinnedDocProto pins = 5;
repeated string hides = 6; // document keys to drop
bool enabled = 7;
int64 created_at = 8;
int64 updated_at = 9;
}
ListCurationRules #
Lists rules scoped to a collection, or all rules when collection is empty.
message ListCurationRulesRequest {
string collection = 1; // optional; "" = list all
}
message ListCurationRulesResponse {
repeated CurationRuleProto rules = 1;
int32 total = 2;
string collection = 3;
}
CreateCurationRule / UpdateCurationRule #
Create a new rule, or replace an existing rule by id. Both return the stored CurationRuleProto.
message CreateCurationRuleRequest {
CurationRuleProto rule = 1;
}
message UpdateCurationRuleRequest {
CurationRuleProto rule = 1;
}
DeleteCurationRule #
Removes a rule by id.
message DeleteCurationRuleRequest {
string id = 1;
}
message DeleteCurationRuleResponse {
string status = 1;
string id = 2;
}
grpcurl Example #
grpcurl -plaintext -d '{
"rule": {
"collection": "blog",
"query": "getting started",
"match_mode": "exact",
"pins": [{"key": "quickstart", "lang": "en_US", "position": 1}],
"hides": ["outdated-guide"],
"enabled": true
}
}' localhost:11024 mddb.MDDB/CreateCurationRule
FTS Maintenance RPCs #
FTSReindex #
Rebuilds the full-text index for a collection, re-applying language-aware stemming.
message FTSReindexRequest {
string collection = 1; // collection to reindex
}
message FTSReindexResponse {
string status = 1; // "ok"
int32 reindexed = 2; // number of documents reindexed
int32 skipped = 3; // number of documents skipped
}
FTSLanguages #
Lists the FTS languages supported by the server and its default language.
message FTSLanguagesRequest {}
message FTSLanguageInfo {
string code = 1; // language code, e.g. "en", "pl"
string name = 2; // language name, e.g. "English", "Polish"
}
message FTSLanguagesResponse {
repeated FTSLanguageInfo languages = 1;
string default_lang = 2; // server's default language
}
Replication Service #
Leader/follower replication is exposed as a separate gRPC service, mddb.MDDBReplication, on the same port. These RPCs are used by follower nodes and are normally not called by application clients. See REPLICATION for setup, authentication, and operational details.
| RPC | Request → Response | Description |
|---|---|---|
RequestSnapshot |
SnapshotRequest → stream SnapshotChunk |
Streams a full database snapshot to a follower |
StreamBinlog |
StreamBinlogRequest → stream BinlogEntryProto |
Long-lived server stream of binlog entries from a given LSN |
ReplicationStatus |
ReplicationStatusRequest → ReplicationStatusResponse |
Current replication state of this node (role, LSN, followers, lag) |
AcknowledgeLSN |
AcknowledgeLSNRequest → AcknowledgeLSNResponse |
Follower confirms it has applied up to a given LSN |
message SnapshotRequest {
string follower_id = 1;
uint64 current_lsn = 2;
}
message SnapshotChunk {
bytes data = 1;
uint64 offset = 2;
uint64 total_size = 3;
bool is_last = 4;
uint64 snapshot_lsn = 5;
}
message StreamBinlogRequest {
string follower_id = 1;
uint64 from_lsn = 2;
}
message BinlogEntryProto {
uint64 lsn = 1;
uint32 type = 2;
int64 timestamp = 3;
string bucket_name = 4;
bytes key = 5;
bytes value = 6;
uint32 checksum = 7;
}
message ReplicationStatusRequest {}
message ReplicationStatusResponse {
string node_id = 1;
string role = 2;
uint64 current_lsn = 3;
string leader_addr = 4;
int64 last_applied_at = 5;
repeated FollowerInfo followers = 6;
int64 replication_lag_ms = 7;
uint64 binlog_oldest_lsn = 8;
int64 binlog_size_bytes = 9;
}
message FollowerInfo {
string follower_id = 1;
uint64 confirmed_lsn = 2;
int64 last_seen_at = 3;
string address = 4;
int64 lag_ms = 5;
}
message AcknowledgeLSNRequest {
string follower_id = 1;
uint64 confirmed_lsn = 2;
}
message AcknowledgeLSNResponse {
bool ok = 1;
uint64 leader_lsn = 2;
}
Not Yet Available over gRPC #
The following RPCs are declared in proto/mddb.proto but not yet implemented server-side. Calling them returns gRPC status Unimplemented — use the HTTP endpoints instead:
| RPC | HTTP alternative |
|---|---|
SpellSuggest |
POST /v1/spell-suggest |
SpellCleanup |
POST /v1/spell-cleanup |
TemporalQuery |
POST /v1/temporal/query |
TemporalHot |
POST /v1/temporal/hot |
Performance Comparison #
Payload Size Example #
HTTP/JSON (Add Request):
{
"collection": "blog",
"key": "hello-world",
"lang": "en_US",
"meta": {
"category": ["blog", "tutorial"],
"author": ["John Doe"]
},
"contentMd": "# Hello World\n\nWelcome to MDDB!"
}
Size: ~180 bytes
gRPC/Protobuf (Same Request): Binary representation: ~55 bytes (70% smaller)
Benchmark Results #
Operation HTTP/JSON gRPC Improvement
─────────────────────────────────────────────────────
Add Document 2.5ms 0.8ms 3.1x faster
Get Document 1.8ms 0.5ms 3.6x faster
Search (10 docs) 5.2ms 1.4ms 3.7x faster
Bulk Add (100) 250ms 75ms 3.3x faster
Best Practices #
Connection Management #
// ✅ Good: Reuse connections
var (
conn *grpc.ClientConn
client pb.MDD BClient
)
func init() {
var err error
conn, err = grpc.Dial("localhost:11024",
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithBlock(),
)
if err != nil {
log.Fatal(err)
}
client = pb.NewMDDBClient(conn)
}
// ❌ Bad: Create new connection for each request
func badExample() {
conn, _ := grpc.Dial("localhost:11024", ...)
defer conn.Close()
client := pb.NewMDDBClient(conn)
// Use client...
}
Error Handling #
import "google.golang.org/grpc/status"
doc, err := client.Get(ctx, req)
if err != nil {
st, ok := status.FromError(err)
if ok {
switch st.Code() {
case codes.NotFound:
log.Println("Document not found")
case codes.InvalidArgument:
log.Println("Invalid request:", st.Message())
case codes.PermissionDenied:
log.Println("Permission denied:", st.Message())
default:
log.Println("Error:", st.Message())
}
}
return err
}
Timeouts #
// Set reasonable timeouts
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
doc, err := client.Get(ctx, req)
Metadata #
import "google.golang.org/grpc/metadata"
// Add metadata to request
md := metadata.Pairs(
"client-id", "my-app",
"version", "1.0.0",
)
ctx := metadata.NewOutgoingContext(context.Background(), md)
doc, err := client.Get(ctx, req)
Generating Client Code #
Go #
cd services/mddbd
./generate.sh
Python #
python -m grpc_tools.protoc \
-I proto \
--python_out=. \
--grpc_python_out=. \
proto/mddb.proto
Node.js #
npm install @grpc/grpc-js @grpc/proto-loader
# Use proto-loader to load .proto file at runtime
Other Languages #
See gRPC documentation for language-specific guides.
Debugging #
Enable Logging #
import "google.golang.org/grpc/grpclog"
grpclog.SetLoggerV2(grpclog.NewLoggerV2(os.Stdout, os.Stderr, os.Stderr))
Use grpcurl #
# List all methods
grpcurl -plaintext localhost:11024 list mddb.MDDB
# Get method details
grpcurl -plaintext localhost:11024 describe mddb.MDDB.Add
# Call with JSON
grpcurl -plaintext -d @ localhost:11024 mddb.MDDB/Add <<EOF
{
"collection": "blog",
"key": "test",
"lang": "en_US",
"content_md": "# Test"
}
EOF
Reflection #
The server has reflection enabled, allowing tools like grpcurl to discover services without .proto files.
Migration from HTTP #
Side-by-Side #
Both HTTP and gRPC APIs run simultaneously:
- HTTP:
localhost:11023 - gRPC:
localhost:11024
You can gradually migrate clients from HTTP to gRPC.
API Parity #
All HTTP endpoints have equivalent gRPC methods with the same functionality.
See Also #
- API Documentation - HTTP/JSON API reference
- Examples - More code examples
- Protocol Buffers - Protobuf documentation
- gRPC - gRPC documentation
License #
The server is under the Business Source License 1.1 (LICENSE); the .proto definitions are BSD-3-Clause (proto/LICENSE), so any client generated from them is yours. Map in LICENSING.