shop-mcp
shop-mcp — 読み取り専用SQLite MCPサーバー
Python製のMCPサーバーで、AIエージェント(例: Pi)に、stdioを通じてSQLiteデータベース shop.db への安全な 読み取り専用 アクセスを提供します。
エージェントはDBスキーマを自ら探索し、SQLクエリを書き、分析タスクを解決します。サーバーには既製の回答はありません。探索と読み取り専用クエリを実行するためのツールのみを提供します。
AI Agent (Pi)
│ stdio
▼
┌────────────────────┐
│ MCP Server │ list_tables / describe_table / read_query
└─────────┬──────────┘
▼
SQL validation ← только один SELECT / WITH ... SELECT
▼
read-only guard ← connection authorizer
▼
SQLite (mode=ro) ← файл физически невозможно изменить1. 要件
Python 3.13+
データベースファイル
shop.db(プロジェクトのルートに置いてある)
Related MCP server: sqlite-analyst
2. インストール
uv syncuv が仮想環境を作成し、依存関係をインストールします。venv を手動で作成する必要はありません。
3. データベース設定
データベースへのパスはハードコードされておらず、環境変数で設定します。
方法 A — 環境変数(絶対パス):
export SHOP_DB_PATH=/absolute/path/to/shop.db
export MAX_RESULT_ROWS=1000 # опционально, default 1000方法 B — 設定なし(フォールバック): SHOP_DB_PATH が指定されていない場合、サーバーはプロジェクトルートの shop.db を使用します。
.env.example を .env にコピーして値をそこに指定することもできます(サーバーはプロジェクトルートの .env を読み取ります。環境変数の方が優先されます):
cp .env.example .env4. MCPをローカルで実行する
uv run python -m shop_mcp.serverサーバーは stdio 経由で動作し、stdin/stdout で MCPプロトコルを待ち受けます。単独で起動する必要はありません。クライアント(Pi)が起動します。上記の手動起動はデバッグにのみ有用です。
設定が正しくない場合(例: DBファイルが存在しない)は、プロセスが stderr に分かりやすいメッセージを出力して終了します。
5. MCPをPiに接続する
Pi は pi-mcp-adapter パッケージを介して MCPサーバーを接続し、プロジェクトルートの .mcp.json から設定を読み取ります。このファイルはリポジトリにすでに含まれています:
{
"mcpServers": {
"shop": {
"command": "uv",
"args": ["run", "python", "-m", "shop_mcp.server"],
"cwd": "/Users/stalexsm/projects/shop-mcp"
}
}
}別のマシンでは、cwd をプロジェクトディレクトリの絶対パスに修正してください(または、SHOP_DB_PATH を設定した env に置き換えても構いません):
{
"mcpServers": {
"shop": {
"command": "uv",
"args": ["run", "python", "-m", "shop_mcp.server"],
"cwd": "/absolute/path/to/shop-mcp",
"env": {
"SHOP_DB_PATH": "/absolute/path/to/shop.db",
"MAX_RESULT_ROWS": "1000"
}
}
}
}別のHTTPサーバーを起動したり、ターミナルで手動で python server.py を動かし続ける必要はありません。Pi が stdio でプロセスを起動します(ツールへの最初のアクセス時に遅延起動します)。
アダプタがまだインストールされていない場合:
pi install npm:pi-mcp-adapterその後、プロジェクトディレクトリで Pi を再起動してください。サーバーのツールは /mcp パネルに表示されます。
6. 利用可能なツール
list_tables
DBのテーブル一覧を、簡単な説明と行数付きで返します。スキーマ探索の出発点です。SQLは不要です。
describe_table
1つのテーブルの構造を返します。カラム(name、type、nullable、primary_key、default) と外部キーを orders.customer_id -> customers.id の形式で返します。存在しないテーブルの場合は、利用可能なテーブルの一覧付きの分かりやすいエラーが返ります。
read_query
読み取り専用のSQLクエリ(SELECT または WITH ... SELECT)を1つ実行します。
パラメータ:
sql(必須) — クエリのテキスト;max_rows(任意) — 要求する行数の上限。サーバー側のハードリミットMAX_RESULT_ROWS(デフォルト1000)を超えることはできません。
通常のSQLite分析をサポートしています:JOIN、LEFT JOIN、GROUP BY、HAVING、ORDER BY、LIMIT/OFFSET、COUNT/SUM/AVG/MIN/MAX、DISTINCT、CASE、CTE。
結果は構造化JSONです:
{
"columns": ["name", "revenue"],
"rows": [["Ноутбук UltraBook 15", 6569270.0]],
"row_count": 1,
"truncated": false,
"execution_time_ms": 0.716
}truncated: true は、リミットによりデータの一部のみが返されたことを意味します。データが完全であると見なさず、クエリ(LIMIT、WHERE、集計など)で絞り込んでください。
7. セキュリティモデル
3つの独立した防御層があります:
SQL validation(SQL検証) — 許可されるのは
SELECT/WITHで始まるちょうど1つのステートメントだけです。INSERT、UPDATE、DELETE、REPLACE INTO、DROP、ALTER、CREATE、ATTACH、DETACH、VACUUM、REINDEX、PRAGMAなど、変更を伴う操作は禁止されています。複数ステートメントを含むクエリ(SELECT ...; DELETE ...)はすべて拒否されます。検証器は文字列リテラル、コメント、引用符付き識別子を理解するため、文字列内の'DELETE'は違反になりません。接続オーソライザー(Connection authorizer) — 読み取り(SELECT/テーブル読み取り/関数呼び出し)以外はすべて、クエリの準備段階で拒否されます。
mode=ro— SQLiteファイルは読み取り専用モードで開かれます。先の2層を迂回しても、物理的に書き込むことはできません。
エラーは把握しやすい形で返されます(例: Database query failed: no such column: foo)。traceback、ファイルシステムのパス、実装の詳細は含まれません。
shop.db は読み取り専用の正本です。サーバーはファイルの内容も構造も変更しません。これは、破壊操作のすべての試みの前後でチェックサムと行数を比較する整合性テストによって保証されています。
8. 質問の例
これらの質問をPiエージェントに与えてください。自分で list_tables、describe_table、read_query を呼び出します:
利用可能なすべてのテーブルを表示して、各テーブルがどのような情報を含むか説明してください。
一番お金を使った顧客は誰ですか?
売れ筋トップ5商品は何ですか?
収益トップ3の商品カテゴリは何ですか?
2025年の売上はいくらですか?
最も多くの注文をした顧客は誰ですか?
ビジネスロジックの参考(エージェントはツールの説明から導き出します。サーバーは回答をハードコードしません):
商品・カテゴリの売上は
SUM(order_items.quantity * order_items.unit_price)で計算されます。ステータスが
cancelledの注文は含みません。年別の売上は
orders.order_dateに基づきます。注文がない場合、正しい応答は0です。
国の質問について
How many customers are from Germany? — この質問には確実に答えることはできません。customers テーブルには country 列がないからです(first_name、last_name、email、phone、created_at のみです)。サーバーは正確なスキーマ情報をエージェントに提供し、エージェントはメールアドレスや電話から国を推測したり推測したりせず、DBに必要なデータがないことを報告する義務があります。
9. テスト
uv run pytestテストスイート(66テスト):
tests/test_database.py— 読み取り専用接続、スキーマの検出、外部キー、接続のクローズ;tests/test_security.py— 禁止操作の全種(仕様の第24節)、複数ステートメント、DB整合性テスト;tests/test_tools.py— 実際のクライアントセッション(インメモリトランスポート)を通じたMCPツールの統合テスト(エラーハンドリング含む);tests/test_analytics.py— 分析シナリオ(仕様の第27節)を独立したSQLiteソースと照合し、結果サイズの上限を検証。
テストは shop.db を変更しません(整合性テストはファイルのチェックサムを比較します)。
10. トラブルシューティング
症状 | 原因と解決策 |
|
|
Pi にツールが表示されない |
|
|
|
| クエリが |
結果が不完全( | 行数の上限に達しました。 |
行数の上限を変更したい | 環境変数 |
プロジェクトレイアウト
shop-mcp/
├── README.md
├── pyproject.toml
├── uv.lock
├── .env.example
├── .gitignore
├── .mcp.json # конфигурация MCP для Pi
├── shop.db # read-only source of truth
├── scripts/
│ └── smoke_stdio.py # ручной smoke-тест через реальный stdio
├── src/shop_mcp/
│ ├── __init__.py
│ ├── server.py # MCP-инструменты (stdio)
│ ├── database.py # read-only слой доступа к SQLite
│ ├── security.py # SQL validation + single-statement guard
│ ├── models.py # структуры результатов
│ └── config.py # SHOP_DB_PATH / MAX_RESULT_ROWS
└── tests/
├── test_database.py
├── test_security.py
├── test_tools.py
└── test_analytics.pyAvailable Tools
3 toolsdescribe_tableA
Describe the structure of one table: columns with name, type, nullable and primary_key flags, plus foreign-key relationships such as 'orders.customer_id -> customers.id'. Use this after list_tables to understand the schema before writing SQL. Pass a table name that was returned by list_tables; unknown names produce a clear error.
Inputs: table_name (required).
list_tablesA
List all tables available in the database, with a short description and the number of rows of each table. Use this first when you do not know the schema, before writing any SQL. No SQL is required.
Inputs: no named parameters.
read_queryA
Execute a single read-only SQL statement (SELECT or WITH ... SELECT) against the shop database. JOIN, LEFT JOIN, GROUP BY, HAVING, ORDER BY, LIMIT/OFFSET, DISTINCT, CASE and CTE are supported. If you do not know the schema yet, call list_tables and describe_table first. Rules enforced by the server: exactly one statement per call (multi-statement SQL is rejected), and no data or schema modification (INSERT, UPDATE, DELETE, CREATE, DROP, ALTER, ATTACH, DETACH, VACUUM, REINDEX, PRAGMA are rejected). The database is opened read-only, so writes are impossible. The result is structured: {columns, rows, row_count, truncated, execution_time_ms}. If truncated is true, only the first row_count rows were returned due to the server-side limit (max_rows, default 1000): refine the query, e.g. add LIMIT, WHERE or aggregation, instead of assuming the data is complete.
Inputs: sql (required), max_rows.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 3 tools
Each tool serves a distinct, non-overlapping purpose: listing tables, describing a single table's schema, and executing read-only SQL queries. No ambiguity in selecting between them.
All tool names follow a consistent verb_noun snake_case pattern: list_tables, describe_table, read_query. This is uniform and predictable.
Three tools are exactly right for this focused read-only database exploration server. Each tool earns its place with no redundancy, and the count falls within the typical well-scoped range.
The tool surface covers the full workflow for safe database discovery: discover schema (list_tables), inspect structure (describe_table), and query data (read_query). No obvious gaps for the stated purpose, and write operations are intentionally excluded.
Related MCP Connectors
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…
Query 40 databases from Claude, ChatGPT, or Cursor — on any device. Read-only, encrypted, audited.
PostgreSQL, MySQL, and SQL Server in one session. 26 read-only MCP tools for AI agents.
Related MCP Servers
- AlicenseAqualityDmaintenanceEnables safe, read-only SQL access to SQLite databases for AI agents, allowing schema exploration and SELECT queries with defense-in-depth protections.3MIT
- AlicenseNot gradedqualityDmaintenanceEnables AI assistants to explore and query SQLite databases through read-only tools, with defense-in-depth sandboxing preventing any data modifications.MIT
- AlicenseNot gradedqualityCmaintenanceEnables 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
- AlicenseBqualityCmaintenanceEnables AI assistants to safely run read-only SQL against SQLite databases through whitelist-validated queries, capped result sets, and confined file paths. It also exposes schema inspection so models can discover tables and columns before querying.2MIT