MCP SQLite Server (Read-Only)
Enables AI agents to safely inspect and query a SQLite database through read-only MCP tools for listing tables, describing schemas, and running paginated SELECT queries.
README
MCP SQLite Server (Read-Only)
A production-ready Model Context Protocol server that provides AI agents with safe, read-only access to a SQLite database (shop.db). Built with the official mcp Python SDK using the stdio transport.
Features
- 3 MCP tools:
list_tables,describe_table,query_database - Defense-in-depth read-only safety: SQLite URI read-only mode +
PRAGMA query_only+ SQL validator + EXPLAIN opcode inspection - Query validation: Rejects
INSERT/UPDATE/DELETE/DROP/ALTER/CREATE/REPLACE/TRUNCATE/ATTACH/DETACH, multi-statement queries (;), SQL comments (--,/* */), and modifyingPRAGMA— without false positives on string literals - Pagination: Default row limit (100),
limit/offsetparameters, truncated-output flag - Stderr-only logging: All logs/tracebacks go to
sys.stderr;stdoutis reserved exclusively for JSON-RPC - Full type hints:
mypy --strictclean - TDD: 105 tests covering security, DB layer, MCP tools, 8 benchmark queries, and the stderr guard
Quick Start
Prerequisites
- Python 3.10+
- A SQLite database file (default:
./shop.db)
Local Setup
python -m venv .venv
source .venv/bin/activate
pip install -e ".[dev]"
Configure
Copy .env.example and set the database path:
cp .env.example .env
# Edit DATABASE_PATH to point to your SQLite file
Or set the environment variable directly:
export DATABASE_PATH=/abs/path/to/shop.db
Run the Server
python -m mcp_server.server
The server communicates over stdin/stdout using the MCP stdio transport. You don't interact with it directly — an MCP client (e.g., Claude Desktop, your AI agent) connects to it.
MCP Client Configurations
Standard Python
Add this to your MCP client configuration (e.g., Claude Desktop's claude_desktop_config.json):
{
"mcpServers": {
"sqlite-shop": {
"command": "python",
"args": ["-m", "mcp_server.server"],
"env": {
"DATABASE_PATH": "/abs/path/to/shop.db"
}
}
}
}
Docker
First build the image:
docker build -t mcp-shop:latest .
Then configure your MCP client:
{
"mcpServers": {
"sqlite-shop": {
"command": "docker",
"args": [
"run", "-i", "--rm",
"-v", "/abs/path/to/shop.db:/app/shop.db",
"-e", "DATABASE_PATH=/app/shop.db",
"mcp-shop:latest"
]
}
}
}
Docker Compose
docker compose up -d
Tools
list_tables
Lists all user tables and views in the database (excludes internal sqlite_* tables).
Parameters: none
Returns:
{
"tables": ["customers", "orders", "order_items", "products"],
"count": 4
}
describe_table
Describes the schema of a table: columns, foreign keys, row count, and the CREATE statement.
Parameters:
table(string, required): Name of the table to describe.
Returns:
{
"table": "customers",
"columns": [
{"cid": 0, "name": "id", "type": "INTEGER", "notnull": 0, "default": null, "pk": 1},
{"cid": 1, "name": "first_name", "type": "TEXT", "notnull": 1, "default": null, "pk": 0}
],
"foreign_keys": [],
"row_count": 150,
"sql": "CREATE TABLE customers (...)"
}
query_database
Executes a read-only SQL query with pagination support.
Parameters:
sql(string, required): A single read-only SQL statement (SELECT,WITH,EXPLAIN, or read-onlyPRAGMA).limit(integer, optional): Maximum rows to return. Default: 100. Max: 1000.offset(integer, optional): Number of rows to skip. Default: 0.
Returns:
{
"columns": ["id", "first_name"],
"rows": [{"id": 1, "first_name": "Alice"}, {"id": 2, "first_name": "Bob"}],
"row_count": 2,
"truncated": false,
"limit": 100,
"offset": 0
}
When truncated is true, more rows are available — increase offset to fetch the next page.
Security
The server implements defense-in-depth to guarantee read-only access:
Layer 1: SQLite Connection (URI read-only mode)
The database is opened with file:<path>?mode=ro, which prevents writes at the SQLite engine level. Additionally, PRAGMA query_only = ON is set on every connection.
Layer 2: SQL Query Validator (security.py)
Before any query reaches SQLite, it passes through a multi-stage validator:
- String literal stripping: String literals (
'...',"...") are replaced with placeholders so keywords inside data (e.g., a product named "Deleted Item") don't trigger false positives. - Comment detection: SQL comments (
--,/* */) are rejected to prevent comment-based bypasses. - Multi-statement rejection: Any semicolon (
;) is rejected, preventing stacked queries. - Keyword analysis: The first real statement keyword must be
SELECT,WITH,EXPLAIN, orPRAGMA. Destructive keywords (INSERT,UPDATE,DELETE,DROP,ALTER,CREATE,REPLACE,TRUNCATE,ATTACH,DETACH,VACUUM, etc.) are blocked. - PRAGMA validation: Read-only PRAGMAs (
table_info,database_list, etc.) are allowed. Any PRAGMA with an assignment (=) or in the mutating-PRAGMA blocklist (journal_mode,synchronous,foreign_keys, etc.) is rejected.
Layer 3: EXPLAIN Opcode Inspection
As a final defense, the query is run through SQLite's own parser via EXPLAIN <query>. The resulting opcode stream is inspected for write opcodes (OpenWrite, Insert, Delete, Create, Drop, etc.) and write-transaction flags. If any are found, the query is rejected.
Layer 4: Sanitized Error Messages
All errors returned to the client are sanitized — filesystem paths and internal details are stripped to prevent information leakage.
Testing
Tests use temporary/in-memory databases only — never the production shop.db.
# Run all tests
python -m pytest
# Run with verbose output
python -m pytest -v
# Run a specific test file
python -m pytest tests/test_security.py
Test Coverage
| Test File | Coverage |
|---|---|
tests/test_security.py |
76 tests: valid queries, destructive statement rejection, PRAGMA validation, multi-statement rejection, comment bypass prevention, string literal handling |
tests/test_db.py |
20 tests: read-only enforcement, table listing, schema description, pagination, truncation, all 8 benchmark queries |
tests/test_server.py |
9 tests: MCP tool discovery, tool calls via SDK client, destructive query rejection, pagination, 7 benchmark queries via tools, stderr/no-stdout-pollution guard |
Static Analysis
# Type checking
python -m mypy
# Linting
python -m ruff check src/ tests/
Project Structure
.
├── .env.example # Environment variable template
├── Dockerfile # Docker containerization
├── docker-compose.yml # Docker Compose config
├── pyproject.toml # Package config, deps, tool settings
├── README.md # This file
├── shop.db # The SQLite database (not included in tests)
├── src/mcp_server/
│ ├── __init__.py
│ ├── config.py # Configuration (DATABASE_PATH, limits, URI builder)
│ ├── db.py # Read-only Database class with introspection + query
│ ├── security.py # SQL validator (multi-layer defense-in-depth)
│ ├── server.py # MCP server entrypoint (stdio transport)
│ ├── tools.py # MCP tool definitions and handlers
│ └── py.typed # PEP 561 marker
└── tests/
├── __init__.py
├── test_db.py # Database layer + benchmark tests
├── test_security.py # Query validator tests
└── test_server.py # MCP server/tool tests
Benchmark Tasks
The server's tools enable an AI agent to perform these analytical tasks (validated by tests against a controlled fixture database):
- Table Discovery:
list_tables+describe_table— list all tables and describe schemas. - Filtered Count:
query_databasewithSELECT COUNT(*) FROM customers WHERE country = 'Germany'. - Country Aggregation:
SELECT country, COUNT(*) ... GROUP BY country ORDER BY ... DESC LIMIT 1. - Customer LTV: Join
customers+orders,SUM(total_amount), order by total. - Product Performance: Join
order_items+products, aggregate by quantity and revenue,LIMIT 5. - Category Aggregation: Traverse
order_items→products→category, aggregate revenue,LIMIT 3. - Date Filtering:
SUM(total_amount) WHERE substr(order_date,1,4) = '2025'. - Order Aggregation: Join
customers+orders,COUNT(o.id), order by count.
Configuration
| Environment Variable | Default | Description |
|---|---|---|
DATABASE_PATH |
./shop.db |
Path to the SQLite database file |
ROW_LIMIT |
100 |
Default row limit for query results (max 1000) |
License
This project is provided as-is for demonstration purposes.
推荐服务器
Baidu Map
百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
Playwright MCP Server
一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。
Magic Component Platform (MCP)
一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。
Audiense Insights MCP Server
通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。
VeyraX
一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。
Kagi MCP Server
一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。
graphlit-mcp-server
模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。
e2b-mcp-server
使用 MCP 通过 e2b 运行代码。
Neon MCP Server
用于与 Neon 管理 API 和数据库交互的 MCP 服务器
Exa MCP Server
模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。