NerdlyBuilds

Read-Only Isn't: Testing a SQLite MCP Server Before an Agent Touches It

A SQLite MCP server on the new Python SDK v2, a read-only flag that still let me write a file, and the tests that keep it honest.

·6 min read

Illustration: a glowing database cylinder sealed in a glass case on a workbench, with a robotic arm reaching toward it and stopping at the glass

Giving a coding agent access to a database is one of the most useful things you can do with MCP, and one of the easiest to get quietly wrong. The usual recipe is “open the database read-only, expose a run_query tool, done.” I built exactly that, then went looking for a way to make it write. It took one SQL statement.

This guide builds a small SQLite MCP server on version 2 of the official Python SDK, which renamed the pieces most tutorials still show. It tests the server without any language model in the loop and then plugs it into Claude Code. Along the way it covers three gotchas: a thread error the SDK hides from the client, a read-only connection that can still write files, and an allow-list that blocks perfectly harmless queries.

Tested with: Python 3.13.18, SQLite 3.53.1, mcp 2.3.0, pytest 9.2.0, Claude Code 2.1.312, on Linux, 28 October 2026.

What changed in the MCP Python SDK v2

If you last touched MCP in Python a few months ago, most code you’ll find online is v1. Version 2.0.0 shipped on 28 July 2026, and pip install mcp now gets you 2.x. The parts that matter for this guide, from the what’s new page and the release notes:

  • FastMCP is now MCPServer, imported from mcp.server. The old import path is gone, not deprecated.
  • There is one Client class. Hand it the server object and it talks to it in memory, with no subprocess and no network. That’s the testing story.
  • Sync tool functions now run on a worker thread. Remember that one.
  • Since 2.1.0, an unexpected exception inside a tool is logged on the server, and the client only sees a generic error.

Here’s what an old import does on 2.3.0:

python -c "from mcp.server.fastmcp import FastMCP"
ModuleNotFoundError: No module named 'mcp.server.fastmcp'. This is mcp 2.x, where FastMCP was renamed to MCPServer (from mcp.server.mcpserver import MCPServer) and other APIs changed; see the migration guide at https://py.sdk.modelcontextprotocol.io/v2/migration/#fastmcp-renamed-to-mcpserver or pin 'mcp<2' to keep running v1 code.

That’s a nicer error than most migrations get. Credit where due.

Setup and a toy database

Everything runs in one folder with a virtual environment:

mkdir print-log-mcp && cd print-log-mcp
python3 -m venv .venv && . .venv/bin/activate
pip install "mcp==2.3.0" pytest

The data is a tiny 3D-printing log. It’s small enough to read at a glance and real enough to ask questions about:

# seed.py
import sqlite3

con = sqlite3.connect("shop.db")
con.executescript("""
DROP TABLE IF EXISTS prints;
CREATE TABLE prints (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    filament TEXT NOT NULL,
    grams REAL NOT NULL,
    minutes INTEGER NOT NULL,
    failed INTEGER NOT NULL DEFAULT 0
);
INSERT INTO prints (name, filament, grams, minutes, failed) VALUES
  ('cable clip',      'PLA',  4.2,   18, 0),
  ('benchy',          'PLA', 12.9,   61, 0),
  ('raspberry pi case','PETG', 48.5, 212, 0),
  ('headphone hook',  'PETG', 22.0,  95, 1),
  ('gridfinity bin',  'PLA',  31.7, 140, 0),
  ('fan duct',        'ABS',  15.3,  70, 1);
""")
con.commit()
print(con.execute("SELECT COUNT(*) FROM prints").fetchone()[0], "rows")
$ python seed.py
6 rows

The naive server, and an error you can’t see

Here’s the version almost everyone writes first: one connection opened at import time, shared by the tool.

# server_naive.py
import sqlite3
from mcp.server import MCPServer

mcp = MCPServer("print-log")
con = sqlite3.connect("shop.db")  # one shared connection

@mcp.tool()
def run_query(sql: str) -> list[dict]:
    """Run a read-only SQL query against the print log."""
    cur = con.execute(sql)
    cols = [c[0] for c in cur.description]
    return [dict(zip(cols, row)) for row in cur.fetchall()]

if __name__ == "__main__":
    mcp.run()

And a quick in-memory call through the v2 Client:

# try_naive.py
import anyio
from mcp import Client
from server_naive import mcp

async def main():
    async with Client(mcp) as client:
        result = await client.call_tool("run_query", {"sql": "SELECT name FROM prints LIMIT 2"})
        print(result.is_error, result.content[0].text[:300])

anyio.run(main)

What the client printed:

True Error executing tool run_query

That’s all the agent would see. The real cause was only in the server’s log:

sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread. The object was created in thread id 140407919798080 and this is thread id 140407868487360.

Both behaviors are v2 features working as designed. Sync tools run on a worker thread, so a connection made at import time lives on the wrong thread. Exceptions get sanitized, so the client learns nothing useful. If you only ever look at what the agent reports, you’ll be debugging blind.

The fix for the first problem is to open a connection per call. The fix for the second is to raise ToolError for anything you want the caller to read, because that message gets passed through.

A server that’s actually read-only

Here’s the full server. Each piece is there for a reason, and the tests further down check every one.

# server.py
import os
import sqlite3
from pathlib import Path

from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError

DB_PATH = Path(os.environ.get("PRINTLOG_DB", "shop.db")).resolve()
MAX_ROWS = 200

mcp = MCPServer("print-log")

# Only these SQLite actions are allowed; everything else is denied.
ALLOWED = {
    sqlite3.SQLITE_SELECT,
    sqlite3.SQLITE_READ,
    sqlite3.SQLITE_FUNCTION,
    sqlite3.SQLITE_RECURSIVE,  # WITH RECURSIVE needs this one too
}


def _authorizer(action, arg1, arg2, db_name, trigger):
    return sqlite3.SQLITE_OK if action in ALLOWED else sqlite3.SQLITE_DENY


def _connect() -> sqlite3.Connection:
    # A fresh connection per call: v2 runs sync tools on a worker thread.
    con = sqlite3.connect(f"file:{DB_PATH}?mode=ro", uri=True)
    con.set_authorizer(_authorizer)
    return con


@mcp.tool()
def list_tables() -> list[str]:
    """List the tables in the print-log database."""
    with _connect() as con:
        rows = con.execute(
            "SELECT name FROM sqlite_schema WHERE type = 'table' ORDER BY name"
        ).fetchall()
    return [r[0] for r in rows]


@mcp.tool()
def run_query(sql: str) -> list[dict]:
    """Run one read-only SELECT against the print log. Returns at most 200 rows."""
    try:
        with _connect() as con:
            cur = con.execute(sql)
            if cur.description is None:
                raise ToolError("Only SELECT statements return rows here.")
            cols = [c[0] for c in cur.description]
            rows = cur.fetchmany(MAX_ROWS + 1)
    except sqlite3.Error as exc:
        # ToolError text reaches the client; other exceptions get sanitized.
        raise ToolError(f"SQLite said: {exc}") from exc
    if len(rows) > MAX_ROWS:
        raise ToolError(f"More than {MAX_ROWS} rows; add a LIMIT or a WHERE clause.")
    return [dict(zip(cols, row)) for row in rows]


if __name__ == "__main__":
    mcp.run()

There are two layers of “read-only” here: the mode=ro URI and the authorizer callback. The next section shows why the URI flag alone isn’t enough.

Why mode=ro alone isn’t enough

mode=ro opens the main database file read-only. It says nothing about other files. SQLite’s ATTACH statement opens another database on the same connection, and if that file doesn’t exist, SQLite creates it. Here’s a test with no authorizer at all:

# ro_only.py
import sqlite3

con = sqlite3.connect("file:shop.db?mode=ro", uri=True)
for sql in [
    "DELETE FROM prints",
    "ATTACH DATABASE 'evil.db' AS evil",
    "CREATE TABLE evil.loot (x)",
    "INSERT INTO evil.loot VALUES (42)",
]:
    try:
        con.execute(sql)
        print("allowed:", sql)
    except sqlite3.Error as exc:
        print("blocked:", sql, "->", exc)
con.commit()
con.close()

print("evil.db contains:", sqlite3.connect("evil.db").execute("SELECT x FROM loot").fetchall())
blocked: DELETE FROM prints -> attempt to write a readonly database
allowed: ATTACH DATABASE 'evil.db' AS evil
allowed: CREATE TABLE evil.loot (x)
allowed: INSERT INTO evil.loot VALUES (42)
evil.db contains: [(42,)]

So a “read-only” connection created a new file on disk and wrote data into it. In a toy folder that’s funny. For a server whose SQL is being written by a model that also reads web pages and README files, it’s the whole ballgame. The path in ATTACH is whatever string the query supplies.

The authorizer closes that hole. SQLite calls it for every action while compiling a statement, and anything not on the allow-list gets SQLITE_DENY. ATTACH, PRAGMA, INSERT and the rest never make it past compilation.

Table of four SQL statements showing that a read-only URI alone blocks DELETE but allows ATTACH and writes into the attached file, while adding the authorizer blocks ATTACH; recursive SELECTs run in both once SQLITE_RECURSIVE is allowed

Testing it without a model

The in-memory Client makes this a plain pytest file. Nothing calls an API, nothing costs tokens, and the whole suite runs in about a second.

# test_server.py
import pytest
from mcp import Client

from server import mcp

pytestmark = pytest.mark.anyio


@pytest.fixture
def anyio_backend():
    return "asyncio"


async def test_lists_tools():
    async with Client(mcp) as client:
        tools = await client.list_tools()
        assert {t.name for t in tools.tools} == {"list_tables", "run_query"}


async def test_select_works():
    async with Client(mcp) as client:
        result = await client.call_tool(
            "run_query",
            {"sql": "SELECT filament, COUNT(*) AS n FROM prints GROUP BY filament ORDER BY n DESC"},
        )
        assert not result.is_error
        assert result.structured_content["result"][0] == {"filament": "PLA", "n": 3}


@pytest.mark.parametrize(
    "sql",
    [
        "DELETE FROM prints",
        "UPDATE prints SET failed = 0",
        "DROP TABLE prints",
        "ATTACH DATABASE 'evil.db' AS evil",
        "PRAGMA writable_schema = ON",
    ],
)
async def test_writes_are_refused(sql):
    async with Client(mcp) as client:
        result = await client.call_tool("run_query", {"sql": sql})
        assert result.is_error
        assert "SQLite said" in result.content[0].text


async def test_row_cap():
    async with Client(mcp) as client:
        result = await client.call_tool(
            "run_query",
            {"sql": "WITH RECURSIVE n(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM n LIMIT 500) SELECT x FROM n"},
        )
        assert result.is_error
        assert "LIMIT" in result.content[0].text

Two details worth knowing. A tool that returns a list shows up in structured_content wrapped as {"result": [...]}. And a ToolError reaches the client as Error executing tool run_query: SQLite said: not authorized. That’s specific enough for an agent to correct itself.

$ python -m pytest -v
test_server.py::test_lists_tools PASSED                                  [ 12%]
test_server.py::test_select_works PASSED                                 [ 25%]
test_server.py::test_writes_are_refused[DELETE FROM prints] PASSED       [ 37%]
test_server.py::test_writes_are_refused[UPDATE prints SET failed = 0] PASSED [ 50%]
test_server.py::test_writes_are_refused[DROP TABLE prints] PASSED        [ 62%]
test_server.py::test_writes_are_refused[ATTACH DATABASE 'evil.db' AS evil] PASSED [ 75%]
test_server.py::test_writes_are_refused[PRAGMA writable_schema = ON] PASSED [ 87%]
test_server.py::test_row_cap PASSED                                      [100%]
============================== 8 passed in 1.05s ===============================

The in-memory client skips the real stdio transport, so one smoke test over stdio is still worth it. Since 2.1.0, Client takes StdioServerParameters directly:

# smoke_stdio.py
import sys
import anyio
from mcp import Client, StdioServerParameters

params = StdioServerParameters(command=sys.executable, args=["server.py"])

async def main():
    async with Client(params) as client:
        tables = await client.call_tool("list_tables", {})
        print("tables:", tables.structured_content)
        result = await client.call_tool(
            "run_query",
            {"sql": "SELECT name, grams FROM prints WHERE failed = 1"},
        )
        print("failed prints:", result.structured_content)

anyio.run(main)
tables: {'result': ['prints']}
failed prints: {'result': [{'name': 'headphone hook', 'grams': 22.0}, {'name': 'fan duct', 'grams': 15.3}]}

Plugging it into Claude Code

Claude Code registers servers with claude mcp add, as described in its MCP docs. Using absolute paths to the venv’s Python means you never depend on whichever environment happens to be active:

claude mcp add print-log -- "$PWD/.venv/bin/python" "$PWD/server.py"
claude mcp list
Added stdio MCP server print-log with command: ./.venv/bin/python ./server.py to local config
print-log: ./.venv/bin/python ./server.py - √ Connected

(I trimmed the absolute paths to ./ for readability.) From there, you’d ask Claude Code something like “which filament fails most often?” and it would call run_query. I didn’t test that model-driven step here. The checks above stop at the health check.

What went wrong when I tested it

  • The shared connection. The first server died with sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread, and the client only saw Error executing tool run_query. Fix: a connection per call, plus ToolError for messages the caller should read.
  • mode=ro let a write through. ATTACH created evil.db and an INSERT landed in it. Fix: the authorizer allow-list.
  • The allow-list was too tight. My first ALLOWED set had only SELECT, READ and FUNCTION. The row-cap test used a recursive CTE and failed with SQLite said: not authorized, not the row-limit message. A quick probe showed recursive CTEs also trigger SQLITE_RECURSIVE. Adding that to the set fixed it. Lesson: write the allow-list, then throw odd-but-legal queries at it.
  • Project scope waits for a human. My first try registered the server with --scope project, which writes a shareable .mcp.json. claude mcp list then reported ⏸ Pending approval (run `claude` to approve) instead of connecting. That’s a sensible safety default, since a repo shouldn’t silently launch programs on your machine. Just don’t mistake it for a broken server. Local scope connected straight away.

When to use this, and when not to

Use it when the data already lives in SQLite or can be exported to it: app databases, scraped datasets, a print log, home-lab metrics. You want an agent to answer questions about the data without being able to change it. The whole server is under 70 lines, and the tests make it safe to change.

Don’t use it as your access control for a shared server database. Postgres and MySQL have real read-only roles, so use those and let the database enforce them. Don’t rely on the 200-row cap as a cost control either, because a query can still scan a huge table before returning a few rows. And if the tables hold anything sensitive, remember that “read-only” still means “the model reads all of it.” Expose a view with only the columns you’re happy for it to see.

If you’re running models locally rather than through a cloud agent, the same server works for them too. That’s the setup in The Brain in the Basement. And whatever an agent can reach is one more thing to have backed up, a point If a Drive Dies Tonight makes better than I can.

Sources

How this was made: researched and drafted with AI assistance, with every code sample run and tested before publishing, then reviewed by Colby.

Get an email when I publish something new