Skip to main content
Glama
prudhvikollads-source

mcp-data-agent

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 answer

Components:

Path

Role

src/mcp_data_agent/server.py

MCP server on the official Python mcp SDK (v1), stdio transport

src/mcp_data_agent/tools.py

Transport-independent tool logic (unit-testable)

src/mcp_data_agent/safety.py

Read-only SQL validation and LIMIT capping

src/mcp_data_agent/db.py

Deterministic seed data (seed 42): telecom / e-commerce

src/mcp_data_agent/client.py

Agent client: session, tool discovery, call loop

src/mcp_data_agent/llm.py

Planner interface, deterministic MockLLM, optional env-configured provider

src/mcp_data_agent/demo.py

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 pytest

Captured 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

customers

1,200

name, email, city, country, segment

plans

6

Basic, Starter, Plus, Pro, Unlimited, Enterprise

subscriptions

1,800

customer → plan, status, dates

invoices

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:

  1. Lexical validation (safety.py): the query must be a single statement starting with SELECT (or WITH … SELECT). Write / DDL / admin keywords (INSERT, UPDATE, DELETE, DROP, ALTER, CREATE, PRAGMA, ATTACH, …), SQL comments, and multiple statements are rejected before anything executes.

  2. Row limit: a LIMIT is always applied and capped at 100 rows — a query asking for LIMIT 1000 is silently capped, not trusted.

  3. Read-only connection: SQLite is opened with a mode=ro URI, so the engine itself refuses writes.

  4. 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 mcp SDK (pinned to the v1 line in pyproject.toml, where the server class used here is stable). It is a thin wrapper: all logic lives in tools.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 default MockLLM is a deterministic, heuristic planner: schema first (list_tables, then describe_table for 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_MODEL and MCP_DATA_AGENT_LLM_API_KEY are all set, planner_from_env() swaps in an EnvLLM that 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 into in 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 passed

Covering: 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 tools
describe_tableA

Describe one table: column names, types, nullability, primary key.

NameRequiredDescriptionDefault
tableYes

Output Schema

NameRequiredDescription
resultYes

TDQS

A3.6/5.0
Behavior3/5

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.

Conciseness5/5

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.

Completeness4/5

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.

Parameters3/5

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.

Purpose4/5

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.

Usage Guidelines3/5

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.

NameRequiredDescriptionDefault

No parameters

Output Schema

NameRequiredDescription
resultYes

TDQS

A3.5/5.0
Behavior3/5

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.

Conciseness5/5

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.

Completeness4/5

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.

Parameters4/5

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.

Purpose4/5

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.

Usage Guidelines2/5

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.

NameRequiredDescriptionDefault
sqlYes
row_limitNo

Output Schema

NameRequiredDescription
resultYes

TDQS

A4.1/5.0
Behavior4/5

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.

Conciseness5/5

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.

Completeness4/5

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.

Parameters2/5

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.

Purpose5/5

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.

Usage Guidelines4/5

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.

  1. 3 tool updatesv0.1.0
    • First observeddescribe_table
    • First observedlist_tables
    • First observedrun_query

TDQS

A4/5.0

Scored across 3 tools

Disambiguation5/5

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.

Naming Consistency5/5

All tools follow a consistent snake_case verb_noun pattern: list_tables, describe_table, run_query. The convention is predictable and readable throughout.

Tool Count5/5

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.

Completeness4/5

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

ActivityMaintained
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • F
    license
    Not graded
    quality
    C
    maintenance
    Provides AI agents read-only analytical access to a SQLite database over stdio, with tools for listing tables, describing schemas, and running paginated SQL queries.
    -
  • A
    license
    Not graded
    quality
    B
    maintenance
    Enables AI agents to safely query and explore SQLite databases through read-only, guard-protected tools that block writes, sensitive table access, and runaway queries.
    1
    MIT
  • A
    license
    A
    quality
    C
    maintenance
    Enables read-only document retrieval and SQLite exploration through tools over stdio, enforcing a safety gate before SQL execution.
    3
    MIT
  • A
    license
    Not graded
    quality
    C
    maintenance
    Enables 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