shop-mcp
shop-mcp
読み取り専用のModel Context Protocolサーバーで、インターネットショップのshop.db SQLiteデータベース(顧客、商品、注文、注文アイテム)上の分析ツールを公開します。AIエージェントに接続して、エージェントがデータを変更することなく分析的な質問に回答できるように設計されています。
このサーバーはstdio経由でMCPを話し、データベースを読み取り専用モードで開き、ドメインルール(どの注文ステータスが売上にカウントされるか、顧客の国がどのように導出されるか、収益の源泉)を説明に含む、少数の専門的でパラメータ化されたツールを公開します。汎用SQLツールも書き込みツールもなく、*「キャンセルされた注文をすべて削除」*のような破壊的なプロンプトは実行できません。
このリポジトリのMCPサーバーコードは、宿題の制約(サーバーを手書きで書いてはいけないという要件)により、AIコーディングエージェント(別名Cursor)によって作成されました。
必要要件
Python 3.11以降
shop.dbSQLiteデータベース(database/shop.dbにコミット済み)uv(推奨)— グローバルインストール不要の分離されたプロジェクト環境でサーバーを実行します。インストール方法はbrew install uv(macOS)、またはcurl -LsSf https://astral.sh/uv/install.sh | shです。
Related MCP server: mcp-data-analyst
インストール
uv(推奨)— 手動のvenvやpipは不要で、uv が初回実行時にプロジェクトとその依存関係を pyproject.toml から解決します:
uv sync # create / refresh the project's .venv from pyproject.tomluv を使わない場合 — 自分でvirtualenvを作成してパッケージをインストールします:
python3 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install -e .これにより、mcp SDKと shop-mcp パッケージ(python -m shop_mcp エントリポイントと shop-mcp コンソールスクリプトを提供します)がインストールされます。
設定
サーバーはプロセスの作業ディレクトリ(ProjectRoot)を基準にした database/shop.db を開きます。環境変数は必要ありません。
uv run --directory <project>(下記のクライアント設定を参照)で起動すると、uv がプロジェクトルートディレクトリを作業ディレクトリに設定するため、コミット済みのデータベースが自動的に見つかります。
database/shop.db が存在しない場合、サーバーは起動時に現在の作業ディレクトリを含む明確な設定エラーを表示して終了します(スタックトレースなし、黙ってフォールバックすることもなし)。MCPクライアント設定で cwd をリポジトリのルートに設定してください。
実行
uv run python -m shop_mcpまたは、アクティブなvenvにパッケージをインストールした場合:
python -m shop_mcpまたは、同等に:
shop-mcpサーバーはstdinからJSON-RPCを読み取り、stdoutに書き込みます。通常は直接実行しません — AIエージェントが起動します(下記参照)。
エージェントに接続する
すぐに使えるMCPクライアント設定が examples/mcp/ 配下にコミットされており、uv をインストールするだけでセットアップ不要で実行できます:
クライアント。 | 設定ファイル |
Cursor |
|
Claude Desktop |
|
Generic stdio |
|
Canonical/default |
|
Docker |
|
各設定は次のようになります(--directory のパスはこのリポジトリの絶対パスに置き換えてください):
{
"mcpServers": {
"shop": {
"command": "uv",
"args": ["run", "--directory", "/path/to/internet-shop-mcp", "python", "-m", "shop_mcp"]
}
}
}uv run --directory <project> は作業ディレクトリをプロジェクトルートに設定し、プロジェクトの .venv を使用するため、サーバーは自動的に database/shop.db を見つけます。同じ設定はマシン間でポータブルです(--directory のパスだけが変更されます)。
uv を使いたくない場合は、自分でパッケージをvenvにインストールし(Install を参照)、command: "python" を使用して、MCPクライアント設定で cwd をリポジトリルートに設定してください。
Cursor:Settings → MCP → Add MCP Server を開き、
examples/mcp/cursor.jsonの内容を貼り付けます(または Project MCP スコープを使用してコミットします)。Claude Desktop:
examples/mcp/claude_desktop.jsonの内容をclaude_desktop_config.jsonにコピーします(macOSの場合は~/Library/Application Support/Claude/claude_desktop_config.json)。Generic stdioクライアント: MCP over stdioを話す任意のクライアントで
examples/mcp/generic_stdio.jsonを使用します。
接続後、エージェントには list_tables、describe_table、count_customers_by_country、rank_countries_by_customers、top_customers、top_products、revenue_by_category、revenue_by_year の8つのツールが表示されます。
ツール
ツール | 回答 |
| タスク1 — テーブルとその内容を一覧表示 |
| 1つのテーブルのスキーマ |
| タスク2 — 特定の国の顧客 |
| タスク3 — 顧客が最も多い国 |
| タスク4 & 8 — トップ支出者 / 最多注文 |
| タスク5 — ベストセラー商品 |
| タスク6 — カテゴリ別売上 |
| タスク7 — 年度別売上 |
ツールの説明に組み込まれているドメインルール(完全な根拠は CONTEXT.md と docs/adr/ を参照):
国は顧客の電話番号のプレフィックス(E.164)から導出されます。
country列はありません。+49→ ドイツ、+7→ ロシア。認識されないプレフィックスはunknownにマッピングされます。ツールはフルネーム("Germany")またはISO alpha-2コード("DE")を受け付け、両方を返します。売上 / 支出は
completedとshippedの注文のみをカウントします。最も多くの注文は
cancelled以外のすべての注文ステータスをカウントします。ベストセラーは販売個数でランク付けされます・収益は二次的なフィールドです。
金銭は、注文/顧客/年集計では
orders.total_amountから、商品/カテゴリ集計ではSUM(order_items.quantity * order_items.unit_price)から取得されます(実際の販売価格であり、現在のproducts.priceではありません)。制限のデフォルトは100で、最大1000に制限されます。
offsetでページネーションされます。エラー- は短いプレーンテキストメッセージ(例:
Invalid year: must be a 4-digit integer)でエージェントに返されます。スタックトレースはstderrのみに出力されます。
セキュリティ
データベースは設計上読み取り専用です:
SQLite は
file:<path>?mode=ro(uri=True)で開かれるため、書き込み試行はすべてsqlite3.OperationalError: attempt to write a readonly databaseを発生させます。PRAGMA query_only = 1が多層防御として設定されています。書き込みツールや汎用SQLツールは公開されていません。使用できるツールは上記の8つの読み取り専用分析ツールのみです。
テスト(tests/test_safety.py)では、書き込み試行が例外を発生すること、書き込みツールが宣伝されていないこと、すべてのツール実行後にデータベースファイルがバイト単位でバイト単位で変更されていないことを検証します。
エンドツーエンドの検証
8つの宿題タスクは、接続されたAIエージェントに対して検証されました。コミットされたデータの期待される結果(150人の顧客(全員+7)、750件の注文(すべて2026年)):
全テーブルの一覧表示 —
list_tablesはcustomers、products、orders、order_itemsをそれぞれの説明付きで返します。ドイツからの顧客は何人? —
count_customers_by_country("Germany")→0(誠実なゼロ。どの顧客も+49番号を持っていません)。どの国が最も顧客が多いですか? —
rank_countries_by_customers→ ロシア(RU)、150人の顧客。最もお金を使ったのは誰ですか? —
top_customers(by="spend", limit=1)→polina.kozlov340@icloud.com、総支出531810.0。トップ5のベストセラー商品 —
top_products(limit=5)→ 販売個数でランク付け(Эспандер плечевой、Планшет Tab 10、…)され、売上も並行して表示されます。カテゴリ別売上トップ3 —
revenue_by_category(limit=3)→Электроника、Бытовая техника、Одежда и обувь。2025年の売上 —
revenue_by_year(2025)→0というメモno orders in 2025(年の置換はなし。すべての注文は2026です)。最も多くの注文 —
top_customers(by="order_count", limit=1)→sofiya.yakovlev284@yandex.ru、15件の注文。
破壊的なプロンプト 「キャンセルされた注文をすべて削除する」 は拒否されます。それを受け入れるツールは存在せず、読み取り専用接続はSQLiteレベルで書き込みを拒否します。
テスト
uv run --extra dev pytest
# or, with the package installed in an active venv:
pip install -e ".[dev]"
python -m pytestスイートは以下をカバーします: スモークテスト(サーバーがstdioで起動し、ハンドシェイク/list_tools に応答する)、各ツールのハッピーパス、ドメインルール(売上は非獲得ステータスを除く、注文数はキャンセルを除外、商品は個数でランク付け)、エッジケース(ドイツ→0、2025→0(注メモ付き)、未知の国、無効な年/メトリック/by、limitクランプ、ページネーション)、および安全性の保証(書き込み試行は例外を発生、書き込みツールなし、データベースファイルは不変)。
Docker(ボーナス)
コンテナ化された実行については、下記の「Docker」セクションを参照してください。
プロジェクトレイアウト
internet-shop-mcp/
├── database/
│ └── shop.db # the read-only database
├── pyproject.toml # package + dependency declaration
├── README.md
├── CONTEXT.md # domain glossary
├── docs/adr/ # ADR-0001..0005
├── src/shop_mcp/
│ ├── __main__.py # `python -m shop_mcp`
│ ├── main.py # server wiring + tool registration
│ ├── config.py # database/shop.db resolution
│ ├── db.py # read-only SQLite connection
│ ├── country.py # phone-prefix → country mapping
│ └── tools.py # tool implementations
├── tests/ # pytest suite mirroring src
├── examples/mcp/ # agent connection configs
├── Dockerfile
└── .dockerignoreDocker
コンテナでサーバーをビルドして実行します。データベースは /app/database/shop.db にあるイメージにコピーされます(ローカル開発と同じ規約)。
docker build -t shop-mcp .
docker run --rm -i shop-mcpDockerを使用した(対応するMCPクライアント設定:
{
"mcpServers": {
"shop": {
"command": "docker",
"args": ["run", "--rm", "-i", "shop-mcp"]
}
}
}バンドルされたデータベースの代わりに独自のデータベースをマウントする場合:
docker run --rm -i -v "$PWD/database:/app/database:ro" shop-mcp読み取り専用の保証はコンテナ内でも維持されます: 接続は mode=ro と query_only=1 で行われ、破壊的なプロンプトも拒否されます。
Available Tools
8 toolscount_customers_by_countryA
Count customers by country. The country is NOT a column — it is derived from the customer's phone-number prefix (E.164), so do not look for a country column. With no argument, returns counts per country as a list of {country_code, country_name, customer_count}. With a country argument (either a full name like 'Germany' or an ISO alpha-2 code like 'DE'), returns the count for that country only — an honest 0 if there are no customers there. An unknown country name returns an error.
Inputs: country.
describe_tableA
Describe the schema of one table: columns (name, type, not_null, default, primary_key) and foreign keys. Use this before building any mental model of how tables relate. Returns {table, columns, foreign_keys}. Pass the table name (one of: customers, products, orders, order_items).
Inputs: table (required).
list_tablesA
List every table in the shop database with a short description of what each table holds. Use this first to understand what entities are available. Returns a list of {name, description}.
Inputs: no named parameters.
rank_countries_by_customersA
Rank countries by number of customers, highest first. The country is derived from each customer's phone-number prefix (there is no country column). Returns a list of {country_code, country_name, customer_count}. limit defaults to 100 and is clamped to a maximum of 1000.
Inputs: limit.
revenue_by_categoryA
Rank product categories by revenue, joining orders -> order_items -> products. Only 'completed' and 'shipped' orders count. Revenue is SUM(order_items.quantity * order_items.unit_price) using the actual sale price. Returns a list of {category, revenue}. limit defaults to 100 (max 1000); offset paginates.
Inputs: limit, offset.
revenue_by_yearA
Return total revenue for a single year (a 4-digit integer, e.g. 2025). Revenue is SUM(orders.total_amount) over orders whose order_date falls in that year and whose status is 'completed' or 'shipped'. A year with no qualifying orders returns revenue 0 with a 'no orders in ' note — it does not substitute a different year. An invalid year returns an error.
Inputs: year (required).
top_customersA
Rank customers either by total spend or by number of placed orders.
by='spend': sums orders.total_amount over orders with status 'completed' or 'shipped' only (new, processing, cancelled do not count as earned). Returns first_name, last_name, email, total_spend.
by='order_count': counts orders whose status is NOT 'cancelled'. Returns first_name, last_name, email, order_count. Customer names are returned as separate first_name and last_name fields.
limitdefaults to 100 (max 1000);offsetpaginates.
Inputs: by, limit, offset.
top_productsA
Rank products by units sold (metric='units', default) or by revenue (metric='revenue'). Only 'completed' and 'shipped' orders count. Money is computed from order_items.unit_price (the actual sale price), not the current products.price. Returns a list of {name, units_sold, revenue}. When metric='units', ranking is by units_sold and revenue is a secondary field. limit defaults to 100 (max 1000); offset paginates.
Inputs: limit, metric, offset.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 8 tools
Most tools are clearly distinct, but count_customers_by_country and rank_countries_by_customers return the same country-level customer counts with only ordering/filtering differences. The other tools, such as top_customers and top_products, are well separated by their selection criteria.
Namess are mostly predictable and use snake_case with clear intent, like list_tables and describe_table. The main inconsistency is that some tools follow imperative verb names while others use noun phrases like top_customers or revenue_by_category, but the pattern remains readable.
Eight tools is well-suited for a read-only analytics server covering schema inspection and common shop metrics. Each tool has a clear role, and the count does not feel excessive or thin.
The toolset covers the main analytics surface: customer geography, top customers, top products, category revenue, and annual revenue. It lacks order-level or product-level detail queries and finer time-based filters, but the visible analytical workflows are complete enough for most shop insight requests.
Maintenance
Related MCP Connectors
Text-to-SQL MCP server: read-only queries on PostgreSQL, MySQL and SQL Server with your real schema
MerchantFlow is a hosted, read-only ecommerce analytics MCP server for Shopify and WooCommerce. It gives AI assistants tenant-scoped access to revenue, profit and loss, product and SKU profitability, COGS coverage, fulfillment costs, advertising spend, ROAS, marketing performance, cohorts, LTV, and business valuation across connected commerce and marketing platforms. Connect with OAuth over Streamable HTTP. No local server installation is required.
Read-only Google Analytics 4 MCP server for AI assistants.
PostgreSQL, MySQL, and SQL Server in one session. 26 read-only MCP tools for AI agents.
Related MCP Servers
- FlicenseNot gradedqualityDmaintenanceA secure MCP server that exposes a SQLite database to AI agents with Role-Based Access Control, supporting authentication, customer/order/user management, and audit logging.-
- AlicenseNot gradedqualityDmaintenanceA natural-language data analyst MCP server that lets users query SQLite sales datasets via MCP tools (list_tables, aggregate, time_series, run_sql) with read-only SQL safety guards, returning results through a FastAPI dashboard.MIT
- FlicenseNot gradedqualityDmaintenanceEnables safe, read-only analysis of an online store's SQLite database, providing schema introspection, restricted SELECT queries, and specialized analytics tools through MCP.-
- FlicenseNot gradedqualityDmaintenanceThis MCP server lets an AI agent securely connect to a read-only SQLite store database, inspect its tables and schema, and run analytical SQL queries without modifying any data.-