DEV Community

Mohammed Arshad Ansari
Mohammed Arshad Ansari

Posted on Originally published at hikmahtechnologies.com

Build a safe MCP server in Python with FastMCP

Building an MCP server in Python takes a few minutes with FastMCP. Building one you would point at real data takes longer. The extra time goes into what happens when the model sends a query that never ends, asks for every row, or reads a file it shouldn't.

This post builds a small server: one read-only DuckDB query tool with a row cap, a timeout and a call log. I ran every line of it, and the output is below. One of my first assumptions failed the test: the framework's timeout did not stop the query. Then I show the production version, the MCP server in my own system, AEGIS, and the rules it adds once other people's data is involved.

What you need

uv venv && uv pip install fastmcp duckdb
Enter fullscreen mode Exit fullscreen mode

That installed FastMCP 4.0.10, the MCP Python SDK 2.2.0 and DuckDB 1.5.6 on Python 3.13. FastMCP 4.0.0 (31 August 2026) was a rewrite on the MCP Python SDK v2 for the 2026-07-28 protocol revision. If you follow a FastMCP 2 or 3 tutorial, most code still works. I hit two deprecation warnings, covered at the end.

The server

Here is the whole file, exactly as I ran it:

"""A read-only DuckDB MCP server: row cap, timeout, call log."""
import json, os, threading, time

import duckdb
from fastmcp import FastMCP
from fastmcp.exceptions import ToolError

DB_PATH = os.environ.get("DUCKDB_PATH", "shop.duckdb")
MAX_ROWS = int(os.environ.get("MAX_ROWS", "200"))
TIMEOUT_S = float(os.environ.get("QUERY_TIMEOUT_S", "5"))
LOG_PATH = os.environ.get("CALL_LOG", "calls.jsonl")

# One read-only connection. Then shut the doors a read-only file leaves open:
# reading other files (read_csv('/etc/passwd')), installing extensions, and
# the model SETting either back.
db = duckdb.connect(DB_PATH, read_only=True)
db.execute("SET enable_external_access = false")
db.execute("SET autoinstall_known_extensions = false")
db.execute("SET autoload_known_extensions = false")
db.execute("SET lock_configuration = true")

mcp = FastMCP("shop-readonly", mask_error_details=True)


def log(**entry):
    entry["ts"] = time.strftime("%Y-%m-%dT%H:%M:%S")
    with open(LOG_PATH, "a") as f:
        f.write(json.dumps(entry) + "\n")


@mcp.tool(annotations={"readOnlyHint": True})
def list_tables() -> list[dict]:
    """List tables and their columns."""
    rows = db.cursor().execute(
        "SELECT table_name, column_name, data_type FROM information_schema.columns "
        "ORDER BY table_name, ordinal_position").fetchall()
    log(tool="list_tables", rows=len(rows), outcome="ok")
    return [{"table": t, "column": c, "type": d} for t, c, d in rows]


@mcp.tool(annotations={"readOnlyHint": True})
def query(sql: str) -> dict:
    """Run one read-only SQL query. Returns at most MAX_ROWS rows."""
    cur = db.cursor()
    timer = threading.Timer(TIMEOUT_S, cur.interrupt)  # stops the query itself
    started = time.perf_counter()
    timer.start()
    try:
        cur.execute(sql)
        rows = cur.fetchmany(MAX_ROWS + 1)
        cols = [d[0] for d in cur.description]
    except duckdb.InterruptException:
        log(tool="query", sql=sql, outcome="timeout", ms=round((time.perf_counter() - started) * 1000))
        raise ToolError(f"Query stopped after {TIMEOUT_S:g}s. Add a filter or an aggregate.")
    except duckdb.Error as e:
        log(tool="query", sql=sql, outcome="error", error=str(e)[:300])
        raise ToolError(str(e).splitlines()[0][:300])
    finally:
        timer.cancel()
    truncated = len(rows) > MAX_ROWS
    rows = rows[:MAX_ROWS]
    log(tool="query", sql=sql, outcome="ok", rows=len(rows), truncated=truncated,
        ms=round((time.perf_counter() - started) * 1000))
    return {"columns": cols, "rows": [list(map(str, r)) for r in rows], "truncated": truncated}


if __name__ == "__main__":
    mcp.run()  # stdio
Enter fullscreen mode Exit fullscreen mode

What each part is for:

  • read_only=True stops writes to the database file. That is all it stops.
  • enable_external_access = false stops SQL from reading other files. Without it, a read-only connection happily ran read_csv('/etc/passwd') in my test. If the server runs as you, that includes your cloud credentials.
  • lock_configuration = true stops the model from running SET to undo the line above.
  • fetchmany(MAX_ROWS + 1) caps the rows and tells the model when it hit the cap, so it can add a filter instead of guessing.
  • cur.interrupt() on a timer is the timeout. More on why below.
  • mask_error_details=True hides stack traces. Only the ToolError messages I wrote, cut to 300 characters, reach the model.
  • calls.jsonl records every call: the SQL, the outcome, the row count and the time taken.

This is the first part. The full post — including the rest of the working details — is on my site: Build a safe MCP server in Python with FastMCP

Top comments (0)