Vision Nexera
Technical deep-dive

A natural-language-to-MongoDB MCP server, built safely

Plain-English questions become validated MongoDB queries, grounded in retrieved schema context, guarded against destructive operations.

Context

An internal engineering build that became a reference architecture: a Model Context Protocol server, written in TypeScript, that lets an AI assistant query MongoDB in natural language, without the two classic failure modes of hallucinated fields and dangerous operations.

The problem

Naive text-to-query is a security incident with good UX: models invent field names, misread intent, and will happily generate a destructive operation if asked sideways. The engineering problem: ground query generation in the real schema and make unsafe output structurally impossible, not just discouraged.

Constraints that shaped the build

  • The model must never see 'guess the schema' as an option: schema context is retrieved, not assumed.
  • Generated queries are data, not code: parsed, validated, and typed before anything touches the database.
  • Destructive operations are blocked at the validation layer regardless of what the prompt asks for.
  • Failures must be legible: a rejected query explains why, which is how trust in the tool is built.

Architecture

The system, drawn honestly

NL-to-MongoDB pipeline: a natural-language question enters through MCP under an identity and mode, relevant schema is retrieved from a live index, the LLM synthesises a typed query, a validation layer enforces schema + operation allow-list + write-mode gate, a cost estimator rejects unbounded scans, MongoDB executes under a timeout, results are masked for PII, and the full trace is audit-loggedNL questionvia MCP · identityMode gateread · write · dry-runSchema retrievallive index · RAGQuery synthesistyped IRValidateschema · ops · write-gateCost estimateexplain · boundExecuteMongoDB · timeoutMask & shapePII · typesAudit logtrace · replayrejections re-prompt with the reason

Every question enters through MCP carrying an identity (human user, service account, or agent) and a declared intent mode: read, write, or dry-run. The mode gate is enforced by the server, not requested by the model: a read-only session cannot escalate to a write regardless of what the natural-language request asked for. Schema retrieval reads from a live index that reflects the current collections, so drift between the model's picture and reality is a lookup miss rather than a hallucination.

The synthesised query is a typed intermediate representation, not raw MongoDB shell text. The validation layer enforces schema conformance, an operation allow-list, write-gate rules for the current mode, and destructive-operation guards that no prompt can talk past. Before execution, a cost estimator inspects the query plan (collection scans, projection width, expected document count) and rejects unbounded reads that would blow through the timeout or the connection budget. Anything rejected loops back to the model with the reason attached, converting failures into self-correction rather than dead ends.

Execution runs under a hard timeout on a per-tenant connection pool, so a runaway query cannot starve neighbours. Results pass through a masking layer that redacts fields tagged as PII according to the caller's role, then are shaped into typed output. Every step (question, retrieved schema, synthesised IR, validation result, cost estimate, executed query, and shaped output) is written to an append-only audit log with a trace id, so any answer is fully reproducible and any incident is a replay away from an explanation.

Build notes

Decisions worth stealing

  • Typed intermediate representation rather than string queries: the LLM never emits shell text directly, so injection is structurally impossible and the validation layer can reason about intent.
  • Read/write mode is a server-enforced session property, not a prompt hint: the model cannot escalate its own privileges by asking nicely.
  • Cost estimation before execution is what makes the tool safe for large collections: an unbounded scan is caught by the explain plan, not by the DBA at 3 a.m.
  • Schema retrieval reads from a live index that updates on migrations, so a model built on a snapshot cannot reference a field that no longer exists: the failure mode is a clean lookup miss, not a silent wrong answer.
  • PII masking is per-field and per-role, enforced after execution before the caller ever sees the payload: the API cannot return what the mask refuses to expose.
  • Every request is audit-logged with a trace id covering identity, mode, retrieved schema, generated IR, validator outcome, cost estimate, executed query, and returned shape. Reproducibility is a lookup, not a forensic exercise.
  • Per-tenant connection pooling and query timeouts stop a bad question from starving neighbouring tenants: noisy-neighbour behaviour is bounded by construction.
  • The rejection-with-reason loop measurably improved self-correction during development. Most validation failures turn into silent second-attempt successes, and the user just gets an answer a beat later.
  • Open-sourcing is under consideration; if released, the repository will be linked here.

Results

What we measure

  • Query validity rate on first synthesis vs after the correction loop
  • Guardrail interception rate by category
  • Median end-to-end latency per question

This is an engineering artifact, so the honest evidence is the architecture itself. Benchmark figures will be published with methodology if and when the project is released publicly.

Next step

Have a system like this in mind?

A 30-minute scoping call gets you a written scope and an honest estimate, including whether AI is even the right tool for it.

Prefer async? hello@visionnexera.com · We reply within one business day.

ASKArchitect⌘K