query_db
Execute read-only SELECT queries against a local SQLite database to retrieve data.
Instructions
Run a read-only SELECT query against local SQLite demo.db.
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| sql | Yes |
Output Schema
| Name | Required | Description | Default |
|---|---|---|---|
| result | Yes |
Implementation Reference
- server.py:99-108 (handler)The `query_db` tool handler function. It accepts a SQL string, validates it starts with SELECT (read-only), executes it against a local SQLite database, and returns results as JSON. Decorated with @mcp.tool() which registers it as an MCP tool.
@mcp.tool() def query_db(sql: str) -> str: """Run a read-only SELECT query against local SQLite demo.db.""" normalized = sql.strip().lower().rstrip(";") if not normalized.startswith("select"): raise ValueError("Only SELECT queries are allowed for this demo.") with _db_connection() as conn: rows = conn.execute(sql).fetchall() return json.dumps([dict(r) for r in rows], indent=2) - server.py:99-99 (registration)The @mcp.tool() decorator on line 99 registers the `query_db` function as an MCP tool with the FastMCP server instance.
@mcp.tool() - server.py:37-40 (helper)The `_db_connection()` helper function used by query_db to get a SQLite connection with row_factory set to sqlite3.Row.
def _db_connection() -> sqlite3.Connection: conn = sqlite3.connect(DB_PATH) conn.row_factory = sqlite3.Row return conn