← All posts

Designing safer MCP access to SQLite and Datasette

A Datasette MCP server is a useful pattern for agent access to structured data, but it shifts risk into the database boundary. The key work is constraining schema exposure, query execution, result shaping, and audit trails before an LLM tool ever touches live data.

Simon Willison’s note on datasette-mcp 0.4 points to a simple shift with large operational impact. An MCP server puts a data system behind a tool interface an LLM agent can call. In this case, the backing system is Datasette, a strong fit for SQLite-backed publishing and query work.

If you build AI systems for internal data access, this matters because the hard part is rarely SQL. The hard part is control. Which tables exist. Which queries run. Which rows leave the boundary. Which tool outputs an agent sees, stores, or forwards. MCP makes tool use easier. It also makes weak data boundaries easier to cross.

For practitioners, the useful angle is not the release itself. It is the design pattern. You expose a database through an LLM-facing protocol. You gain speed and reach. You also inherit a new set of failure modes around prompt-driven query generation, schema overexposure, result shaping, and auditability. Those are solvable if you treat the MCP layer as part of your security and reliability model, not as a thin adapter.

Start with the database boundary, not the model

Most teams begin with the model prompt and tool schema. Start one layer lower. Decide what the MCP server is allowed to reveal and execute.

A safe design usually has these properties:

  • Read-only access at the database role level.
  • Access to a curated set of views, not raw application tables.
  • Row and column filtering before data reaches the MCP tool.
  • Timeouts and row limits enforced outside the model.
  • Separate databases or replicas for agent-facing workloads.

SQLite and Datasette make this easier because the deployment unit is small and explicit. You know which file, which attached databases, which plugins, and which canned queries exist. Use that to your advantage. Publish a narrow analytical surface.

Common mistakes show up fast:

  • Exposing internal tables with operational data, API keys, or staff notes.
  • Letting the agent inspect the full schema, then infer joins across unrelated datasets.
  • Assuming prompt instructions will stop broad queries.
  • Sharing the same database path between public serving and agent workloads.

If you need agents to answer business questions, create dedicated views with stable names and clear semantics. Hide join complexity inside the view. Rename fields so their meaning is obvious. Remove columns you would hesitate to paste into a ticket or chat. If the model never sees the sensitive column, prompt mistakes have less room to grow.

Treat query generation as untrusted code

An agent-generated SQL statement is code produced from ambiguous input. Treat it the same way you would treat user-supplied code in any other execution path.

Inspection points worth enforcing:

  • Allow only SELECT statements.
  • Block multiple statements in one request.
  • Reject access to SQLite pragmas and attachment features unless there is a strong need.
  • Set hard caps on execution time, returned rows, and output bytes.
  • Log the prompt context, generated SQL, parameters, latency, and row count.

Why this matters in practice:

  • A harmless business question often expands into a full table scan.
  • A summarization task may ask for raw rows when aggregates would do.
  • A model under prompt injection pressure may attempt exploratory schema queries.
  • A broad LIKE or cross join may turn a cheap request into a denial of service path.

For SQLite-backed systems, resource control is part of safety. Long-running reads block other work in the wrong setup. Large result sets consume memory twice, once in query execution and again in tool serialization. Even if your agent does nothing unsafe, an oversized result is enough to degrade the service.

A practical pattern is a two-step tool flow. First, expose a metadata tool for approved datasets, columns, and example queries. Second, expose a query tool that accepts a constrained template or parameterized query ID, not arbitrary SQL. Free-form SQL feels flexible, but most production use cases repeat. Encode those repeats as named operations.

Shape results for the model you have, not the data you own

Raw database output is rarely the right tool payload. LLMs handle small, structured, high-signal results better than wide, noisy tables.

Good result shaping includes:

  • Aggregates instead of row dumps when the task is analytical.
  • Stable sort order so repeated calls produce comparable outputs.
  • Explicit null handling.
  • Units and timestamps normalized before serialization.
  • Truncation rules with a visible marker when rows are omitted.

This is a reliability issue as much as a safety issue. If the same query returns rows in arbitrary order, the model may produce inconsistent summaries. If values come back with mixed units, the model may compare unlike numbers. If free-text columns dominate the payload, the model may anchor on anecdotes instead of the dataset trend.

Canned queries help here. Datasette already fits a publishing workflow where named queries and faceted exploration matter. Carry the same discipline into MCP. Define outputs for model consumption, not for human browsing alone.

One strong pattern is to split tools by intent:

  • list_datasets for discovery.
  • describe_dataset for schema and caveats.
  • run_report for approved metrics.
  • sample_rows for a small, bounded preview.

That structure reduces the chance that an agent reaches for the most permissive tool first. It also improves tracing. When a bad answer appears, you know whether the issue came from discovery, interpretation, or execution.

Read prompt injection as a data-layer problem too

Teams often frame prompt injection as a model alignment issue. In database tools, it is also a data access issue.

If an agent reads untrusted text from the database, tickets, wiki pages, or user-submitted rows, that text may contain instructions aimed at the agent. Once the same agent also holds a query tool, the attack path widens. The model reads hostile content, then uses a legitimate tool in an unsafe way.

Signals to inspect:

  • Tools that let one agent both fetch untrusted text and query sensitive datasets.
  • Database rows with rich text fields passed straight into the model context.
  • Missing separation between retrieval tools and execution tools.
  • System prompts that rely on language rules without hard tool-side guards.

Defenses should live at multiple layers:

  • Separate agents by role where possible.
  • Strip or isolate untrusted text before it reaches the tool-planning context.
  • Require human approval for tools with broader query scope.
  • Prefer precomputed reports for high-value datasets.

If you test these systems, test with hostile records inside the dataset, not only hostile user prompts. That gives you a clearer picture of how the agent behaves when the attack enters through content it retrieved itself. Prompt-Injection & System-Prompt-Leak Tester applies to the model side of this problem. You still need database-side controls because a prompt test does not enforce query limits.

Make auditing first-class from day one

The moment an LLM can query a live dataset, you need replayable traces. Without them, you will struggle to explain cost spikes, odd answers, or data exposure incidents.

At minimum, log:

  • The user request or upstream task ID.
  • The model tool call name and arguments.
  • The exact SQL or query identifier executed.
  • The schema object names touched.
  • Row count, bytes returned, and latency.
  • Any truncation, timeout, or policy rejection.

Then review those logs for patterns:

  • Which prompts trigger repeated schema discovery.
  • Which datasets drive the largest payloads.
  • Which tools correlate with failed or low-quality answers.
  • Which columns appear often in abandoned or truncated runs.

This gives you a path to tighten the interface. If one report accounts for most useful traffic, formalize it. If free-form querying produces noisy outputs, remove it. If a small set of joins creates latency spikes, materialize them ahead of time. MCP makes tooling accessible. It does not remove the need for product discipline around data contracts.

What to watch next

Expect more teams to put MCP in front of internal analytics stores, SQLite files, and published data catalogs. The useful question is not whether an agent can reach your data. It is how narrow, observable, and repeatable you make that reach.

Watch for better patterns around parameterized query tools, result budgeting, and role-separated agents. Those will matter more than model benchmarks for many business systems. The teams with the fewest problems will be the ones that treat the MCP server as part of the database perimeter, with the same care they already apply to APIs and admin panels.