mcp-data-agent
Exposes read-only tools for safely exploring a SQLite database: list tables, describe table schemas, and run validated read-only SELECT queries with enforced row limits and timeouts.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@mcp-data-agentwhich plan has the most subscribers?"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
mcp-data-agent
A real Model Context Protocol (MCP) server that lets an agent explore a database safely and read-only, plus an agent client that answers natural-language questions by discovering and calling the server's tools over stdio.
Problem statement
Giving a language-model agent direct database access is useful and risky in
equal measure: the same connection that answers "which plan has the most
subscribers?" can also run a DELETE. This project demonstrates the middle
path — an MCP server that exposes exactly three read-only tools over a real
database, enforces read-only access at several independent layers, and an
agent client that must explore the schema before it is allowed to query.
The whole loop runs offline with a deterministic planner, so anyone can
clone it, run one command, and watch every tool call happen.
Related MCP server: sql-guard-mcp
Architecture
sequenceDiagram
participant User
participant Client as Agent client (client.py)
participant Planner as Planner (llm.py, MockLLM by default)
participant Server as MCP server (server.py, official mcp SDK)
participant DB as SQLite (data/app.db, read-only)
User->>Client: "which plan has the most subscribers?"
Client->>Server: spawn subprocess, JSON-RPC over stdio, initialize
Client->>Server: list_tools
Server-->>Client: list_tables, describe_table, run_query
loop Until the planner stops
Client->>Planner: next step? (question + observations so far)
Planner-->>Client: tool call
Client->>Server: call_tool(name, arguments)
Server->>DB: validated SELECT (read-only connection)
DB-->>Server: rows
Server-->>Client: JSON result
Client->>Client: record observation
end
Client->>Planner: summarise(question, observations)
Planner-->>Client: plain-English answer
Client-->>User: tool-call trace + final answerComponents:
Path | Role |
| MCP server on the official Python |
| Transport-independent tool logic (unit-testable) |
| Read-only SQL validation and LIMIT capping |
| Deterministic seed data (seed 42): telecom / e-commerce |
| Agent client: session, tool discovery, call loop |
| Planner interface, deterministic |
| One-command offline demo |
Quickstart
python3 -m venv .venv
.venv/bin/pip install -e '.[dev]'
# Run the demo (seeds the database on first run, spawns the server over stdio)
.venv/bin/python -m mcp_data_agent.demo "which plan has the most subscribers?"
# Other questions it answers
.venv/bin/python -m mcp_data_agent.demo "what is the total revenue?"
.venv/bin/python -m mcp_data_agent.demo "how many customers are there?"
.venv/bin/python -m mcp_data_agent.demo "which customers spend the most?"
# Run the server on its own (speaks MCP on stdin/stdout)
.venv/bin/python -m mcp_data_agent.server
# Tests (fully offline)
.venv/bin/python -m pytestCaptured demo output
Real output, captured from an actual run of
.venv/bin/python -m mcp_data_agent.demo "which plan has the most subscribers?"
(long result lines are shortened by the demo printer itself, with ...):
Question: which plan has the most subscribers?
Tools discovered: list_tables, describe_table, run_query
Tool calls:
1. list_tables()
-> {"tables": [{"name": "customers", "row_count": 1200}, {"name": "invoices", "row_count": 4200}, {"name": "plans", "row_count": 6}, {"name": "subscriptions", "row_count": 1800}]}
2. describe_table({"table": "plans"})
-> {"table": "plans", "columns": [{"name": "id", "type": "INTEGER", "nullable": true, "primary_key": true}, {"name": "name", "type": "TEXT", "nullable": false, "primary_key": false}, {"name": "monthly_price_usd", "type": "REAL", "nullable": false, "primary_key": false}, {"name": "data_gb", "type": "INTEGER", "nullable": f...
3. describe_table({"table": "subscriptions"})
-> {"table": "subscriptions", "columns": [{"name": "id", "type": "INTEGER", "nullable": true, "primary_key": true}, {"name": "customer_id", "type": "INTEGER", "nullable": false, "primary_key": false}, {"name": "plan_id", "type": "INTEGER", "nullable": false, "primary_key": false}, {"name": "status", "type": "TEXT", "nulla...
4. run_query({"sql": "SELECT p.name AS plan, COUNT(*) AS subscribers FROM subscriptions s JOIN plans p ON p.id = s.plan_id GROUP BY p.name ORDER BY subscribers DESC LIMIT 5"})
-> {"columns": ["plan", "subscribers"], "rows": [{"plan": "Pro", "subscribers": 515}, {"plan": "Unlimited", "subscribers": 449}, {"plan": "Plus", "subscribers": 281}, {"plan": "Starter", "subscribers": 248}, {"plan": "Enterprise", "subscribers": 176}], "row_count": 5, "limit": 100, "truncated": true, "sql": "SELECT p.name...
Final answer: The plan with the most subscribers is Pro with 515 subscriptions.A static version of this recorded run is also in
web/index.html — open it in any browser, no server needed.
Dataset
Synthetic, neutral commercial data generated deterministically
(random.Random(42), standard library only) on first use:
Table | Rows | Contents |
| 1,200 | name, email, city, country, segment |
| 6 | Basic, Starter, Plus, Pro, Unlimited, Enterprise |
| 1,800 | customer → plan, status, dates |
| 4,200 | subscription billing, amount, paid / pending / overdue |
Re-seed any time with .venv/bin/python -m mcp_data_agent.db
(the database file itself is git-ignored; the seed script is the source of
truth). Point the tools at a different database with MCP_DATA_AGENT_DB.
Safety model
run_query is the only tool that touches user-shaped input, and it is
defended in depth — each layer would stop a write on its own:
Lexical validation (
safety.py): the query must be a single statement starting withSELECT(orWITH … SELECT). Write / DDL / admin keywords (INSERT,UPDATE,DELETE,DROP,ALTER,CREATE,PRAGMA,ATTACH, …), SQL comments, and multiple statements are rejected before anything executes.Row limit: a
LIMITis always applied and capped at 100 rows — a query asking forLIMIT 1000is silently capped, not trusted.Read-only connection: SQLite is opened with a
mode=roURI, so the engine itself refuses writes.Engine authorizer + timeout: user SQL runs under a SQLite authorizer that allows only
SELECT/ read / function actions, and a progress-handler deadline aborts queries after 5 seconds.
list_tables and describe_table run only hardcoded internal queries;
describe_table validates the requested name against the real table list
instead of interpolating untrusted input.
Design decisions
Real SDK, thin server. The server uses the official Python
mcpSDK (pinned to the v1 line inpyproject.toml, where the server class used here is stable). It is a thin wrapper: all logic lives intools.py, so it is testable without a subprocess.Planner interface, not a model dependency. The client depends on a two-method planner protocol (
next_step/summarise). The defaultMockLLMis a deterministic, heuristic planner: schema first (list_tables, thendescribe_tablefor the tables the question touches), then one aggregate query built from the question pattern, then a templated answer. No keys, no network, reproducible runs.Optional real provider via environment only. If
MCP_DATA_AGENT_LLM_ENDPOINT,MCP_DATA_AGENT_LLM_MODELandMCP_DATA_AGENT_LLM_API_KEYare all set,planner_from_env()swaps in anEnvLLMthat talks to that generic chat-completions style endpoint with the standard library. No provider is hardcoded or required.Deterministic data. Fixed-seed generation means tests can assert exact counts and the demo answer never drifts between machines.
stdio transport. The simplest real MCP transport: no ports, no network surface, and the server lifecycle is owned by the client.
Limitations
The heuristic planner covers a bounded set of question patterns (subscribers, revenue, averages, top customers, counts, per-city, plan prices) and falls back to a customer count. It is a stand-in for a model, not a replacement for one.
SQLite only, and a single bundled dataset. Other databases would need a different connection / authorizer layer behind the same tools.
Lexical SQL validation is conservative by design: some legitimate read queries (for example, ones containing SQL comments, or the word
intoin a string literal) are rejected.One query per question in the default planner; multi-step analysis (query, inspect, query again) is a property of the interface, not of the mock.
stdio transport only — no HTTP / remote hosting in this version.
Tests
10 passedCovering: table listing and exact seeded counts, schema description,
SELECT execution, rejection of DELETE / UPDATE / INSERT / DROP /
multi-statement payloads (with data verified untouched), row-limit
enforcement (explicit limit and hard cap), and an integration test that
launches the real server over stdio, discovers its tools, and completes
one question end to end, cross-checked against a direct query.
License
MIT — see LICENSE.
Available Tools
3 toolsdescribe_tableA
Describe one table: column names, types, nullability, primary key.
| Name | Required | Description | Default |
|---|---|---|---|
| table | Yes |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description carries the full burden, and it does disclose the output fields, which is the key behavioral fact. However, it says nothing about error behavior for a nonexistent table, permission requirements, or whether the table name must be schema-qualified.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
A single front-loaded sentence with zero filler; every clause adds information about what is returned.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
An output schema exists, so return values needn't be restated, and the description is adequate for a simple one-parameter metadata read. The remaining gap is argument format and failure behavior for unknown tables.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 0% for the single 'table' parameter, so the description must compensate. It only implies the argument is one table identifier and gives no format guidance (e.g., schema-qualified vs bare name, quoting).
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
States a specific verb ('Describe') and resource ('one table'), and enumerates the returned metadata (column names, types, nullability, primary key). The 'one table' scope implicitly separates it from list_tables, but no sibling is named explicitly.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
No explicit when-to-use or when-not-to-use guidance, and no mention of alternatives like list_tables or run_query. Usage is only implied by the nature of a schema-inspection tool.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
list_tablesA
List every table in the database with its row count.
| Name | Required | Description | Default |
|---|---|---|---|
No parameters | |||
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description carries the behavioral burden. It clearly states the operation and that row counts are returned, but it does not explicitly confirm read-only behavior, permissions, performance implications, or whether row counts are exact or estimated.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The definition is a single, front-loaded sentence with no redundant or filler text. Every phrase contributes directly to what the tool does and what it returns.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a simple zero-parameter listing tool with an output schema, the description is nearly complete: it identifies the resource and notes that row counts are included. The remaining gap is the lack of explicit usage guidance and behavioral notes such as read-only status or potential cost of row counts.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The tool has zero parameters, so there are no parameter semantics to explain. The empty schema is self-contained and the description does not need to compensate for undocumented parameters.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description uses a specific verb and resource: it lists every table in the database and includes row counts. This is clearly distinct from describe_table and run_query in practice, but it does not explicitly differentiate itself from those siblings.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
There is no explicit guidance on when to use this tool versus describe_table or run_query, nor any stated exclusions or prerequisites. The intended use is inferable from the description, but the definition provides no usage routing.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
run_queryA
Run a single read-only SELECT query.
Writes, DDL, multiple statements and SQL comments are rejected. Results are capped at 100 rows and queries time out after 5 seconds.
| Name | Required | Description | Default |
|---|---|---|---|
| sql | Yes | ||
| row_limit | No |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description carries the full burden and does well: it discloses read-only enforcement, rejected statement classes, a 100-row cap, and a 5-second timeout. It omits what happens on rejection (error shape) and any permission/auth requirements, which are relevant for a query tool.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Four short sentences, front-loaded with the core action, then constraint bullets. Every sentence carries a distinct operational fact with no waste.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
An output schema exists, so return values needn't be described, and the operational limits (rows, timeout, rejected SQL) cover the main behavioral risks. The remaining gap is the interaction between the documented row cap and the undocumented row_limit parameter.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 0%, so the description must compensate, but it never mentions the 'sql' syntax expectations or the existence of 'row_limit'. Worse, the stated 100-row cap creates ambiguity about whether row_limit can override it. Only the implicit cap is conveyed, leaving both parameters materially unexplained.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description opens with a specific verb and resource ('Run a single read-only SELECT query') and establishes scope ('single') that cleanly separates it from list_tables and describe_table. An agent can tell what this tool does without opening the schema.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description defines the boundary clearly: writes, DDL, multiple statements and comments are rejected, which tells the agent when NOT to use it. It stops short of naming the sibling tools as alternatives for common needs like listing tables.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
3 tool updates
v0.1.0- First observed
describe_table - First observed
list_tables - First observed
run_query
TDQS
Scored across 3 tools
The three tools target clearly distinct operations: listing tables, describing a single table's schema, and executing a SELECT query. There is no overlap between schema discovery and query execution, so an agent can easily select the right tool.
All tools follow a consistent snake_case verb_noun pattern: list_tables, describe_table, run_query. The convention is predictable and readable throughout.
Three tools is a tight, well-scoped surface for a read-only data agent: each tool earns its place and covers a necessary stage of exploration. There are no redundant or filler tools.
The surface covers the core read-only workflow: discover tables, inspect schema, then query data. Minor gaps like schema/table search or query plan explanation exist, but agents can work around them with the provided tools.
Maintenance
Related MCP Connectors
Query 40 databases from Claude, ChatGPT, or Cursor — on any device. Read-only, encrypted, audited.
Safe, read-only Postgres and MySQL access for AI agents. Audit log + column-level controls.
Explore, query, and inspect SQLite databases with ease. List tables, preview results, and view det…
- OleanderOAuthdev.oleander
The all-in-one data stack for agents. Upload files, run SQL, evolve tables, and render charts.
Related MCP Servers
- FlicenseNot gradedqualityCmaintenanceProvides AI agents read-only analytical access to a SQLite database over stdio, with tools for listing tables, describing schemas, and running paginated SQL queries.-
- AlicenseNot gradedqualityBmaintenanceEnables AI agents to safely query and explore SQLite databases through read-only, guard-protected tools that block writes, sensitive table access, and runaway queries.1MIT
- AlicenseAqualityCmaintenanceEnables read-only document retrieval and SQLite exploration through tools over stdio, enforcing a safety gate before SQL execution.3MIT
- AlicenseNot gradedqualityCmaintenanceEnables AI models to securely analyze SQLite datasets and read local text documents through a local stdio interface. It provides read-only querying, schema discovery, pagination, and timeout protections to prevent data leaks or destructive changes.MIT