Skip to main content
Glama
ecommerce-mcp-automation

ecommerce-mcp-automation

by petrycz

Ecommerce MCP Automation

Claude Code + MCP 連携のサンプル: Shopify と Meta Ads を MCP ツールとして公開し、さらにレポーティングエージェントが両方のデータを取得して、1 つの整形された日次 P&L + 広告パフォーマンスのスプレッドシートにまとめます — プラットフォーム間での手動コピー&ペーストは不要です。

これは、公開されている Shopify Admin API と Meta Marketing API のドキュメントに基づいて構築されたデモであり、実際のビジネスで運用されたものではありません。クリーンルームサンプルです。実際のエンドポイント、実際の認証、実際のページネーション、実際のエラーハンドリングを、この種の自動化がどのように構築されるかを正確に示すために新規に記述しています。認証情報ゼロのモックモードでエンドツーエンドに動作し(実際のレスポンスの代わりに現実的なフィクスチャデータを使用)、実際の認証情報が設定された瞬間に統合単位でライブモードに切り替わります — 実行方法 を参照してください。

Shopify クライアントは、実際の Shopify Partners 開発ストア(本番ビジネスではなくサンドボックスストア)に対してライブで実行済みです。実際の認証、実際の注文、実際の API レスポンスです。このプロセスで、モックフィクスチャだけではカバーできなかった null 許容に関する実際のエッジケースが 2 つ発見され、修正されました(既知の簡略化 を参照)。Meta Ads はこのリポジトリではデフォルトでモックトランスポートに対して実行されます。クライアントコードも同様に記述されており、META_ACCESS_TOKEN/META_AD_ACCOUNT_ID が設定された瞬間にライブへ切り替わります。

できること

  • Shopify の注文、売上、COGS を MCP ツールとして公開(get_orders、get_daily_pnl)

  • Meta Ads の広告費、インプレッション、購入、ROAS を MCP ツールとして公開(get_insights、get_daily_ad_performance)

  • レポーティングエージェント(daily_report.py)が両方を同時に取得し、整形された .xlsx — Summary、Orders、Ad Performance シート — を書き出します

  • ワークフロー全体を自然言語トリガー(「日次レポートを実行」)で起動できる Claude Code Skill を同梱

  • 何も実行しなくても結果を確認できる、コミット済みの サンプル出力 を含む

Related MCP server: Ask AI

サンプル出力

Summary タブのレンダリング済みプレビュー — 実際に生成されたワークブックを開く と、ライブファイル(Orders と Ad Performance シート、通貨/ROAS 書式、固定ヘッダー行を含む)が確認できます。

アーキテクチャ

flowchart LR
    subgraph Shopify["Shopify Admin API"]
        SO[orders.json]
        SI[inventory_items.json]
    end
    subgraph Meta["Meta Marketing API"]
        MI[act_id/insights]
    end

    SO --> SC[shopify_client.py]
    SI --> SC
    MI --> MC[meta_ads_client.py]

    SC --> SS[shopify_server.py<br/>MCP tools]
    MC --> MS[meta_ads_server.py<br/>MCP tools]

    SC --> DR[daily_report.py]
    MC --> DR
    DR --> SPX[spreadsheet.py]
    SPX --> XLSX[(sample_daily_report.xlsx)]

    Mock[["mock_api.py<br/>(ASGITransport, in-process)"]] -.mock mode.-> SC
    Mock -.mock mode.-> MC

2 つの API クライアント(clients/shopify_client.py、clients/meta_ads_client.py)は本物の統合コードです。実際のエンドポイント URL、実際の認証ヘッダー、実際のページネーションループ、実際の 429 バックオフを備えています。モックモードとライブモードの間で唯一変わるのは、HTTP トランスポート(clients/http.py)です。

  • ライブ: httpx.AsyncClient が Shopify / Meta への実際の接続を開きます。

  • モック: httpx.AsyncClient には、インプロセスの FastAPI アプリ(fixtures/mock_api.py)を指す httpx.ASGITransport が与えられます。このアプリは現実的なフィクスチャペイロードを提供します。ポートはバインドされず、サブプロセスも実行されませんが、リクエストは実際の HTTP/ASGI ルーティング、ヘッダー、JSON エンコーディングを経由します。

つまり、レビュアーが読むクライアントコードは、ライブストアに対して実行されるコードと同じものです。モックを本物に見せかけたものではありません。詳細な規約は CLAUDE.md を参照してください。

実行方法

モックモード(デフォルト — 認証情報なし)

git clone <this-repo> && cd ecommerce-mcp-automation
python -m venv .venv && source .venv/bin/activate   # or: uv sync && source .venv/bin/activate
pip install -e ".[dev]"

python -m ecommerce_mcp.reporting.daily_report
# -> Wrote examples/sample_daily_report.xlsx

テストスイートも同じ方法で実行できます。セットアップは不要です。

pytest

ライブモード

.env.example を .env にコピーし、お持ちの認証情報を記入してください — 各統合は、自身の認証情報が存在する瞬間に独立してライブに切り替わります。つまり、Meta をモックのまま Shopify をライブで実行できます(逆も同様です)。

cp .env.example .env
# SHOPIFY_STORE_DOMAIN=your-dev-store.myshopify.com
# SHOPIFY_ACCESS_TOKEN=shpat_...          (Partners dev store -> custom app -> Admin API token)
# META_ACCESS_TOKEN=EAA...                (System User token, ads_read scope)
# META_AD_ACCOUNT_ID=act_1234567890

MCP サーバーとして(Claude Code / Claude Desktop)

MCP 設定(Claude Code の場合は .mcp.json、Claude Desktop の場合は設定ファイル)に追加します。command はプロジェクトの venv インタープリターを直接指すように設定してください。MCP クライアントはシェルプロファイルを読み込まないため、素の python では有効化された venv を認識できません。

{
  "mcpServers": {
    "shopify": {
      "command": "/path/to/ecommerce-mcp-automation/.venv/bin/python",
      "args": ["-m", "ecommerce_mcp.mcp_servers.shopify_server"],
      "cwd": "/path/to/ecommerce-mcp-automation"
    },
    "meta-ads": {
      "command": "/path/to/ecommerce-mcp-automation/.venv/bin/python",
      "args": ["-m", "ecommerce_mcp.mcp_servers.meta_ads_server"],
      "cwd": "/path/to/ecommerce-mcp-automation"
    }
  }
}

その後、Claude に「今日の Shopify P&L は?」や「昨日の Meta 広告パフォーマンスを取得して」などと尋ねてください。デフォルトではモックモードで、ツールを直接呼び出します。

スキルとして

skills/daily-report/SKILL.md はレポート生成ワークフローをラップしており、正確な CLI コマンドを必要とせず、自然言語トリガー(「日次レポートを実行」)で Claude Code が実行できます。フルレポートのパスでは、上記の MCP 設定は一切不要です — daily_report.py を直接実行し、クライアントをプレーンな Python として呼び出すだけなので、MCP は関与しません。MCP 設定が必要なのは、スキルのもう 1 つのパス、つまりレポート全体を実行する代わりに get_daily_pnl / get_daily_ad_performance を MCP ツールとして呼び出して、単発の単一メトリクスの質問(「今日の ROAS は?」)に答える場合だけです。

プロジェクト構成

src/ecommerce_mcp/
  clients/         Typed, async API clients (Shopify + Meta), transport-swappable
  mcp_servers/      MCP tool servers wrapping the clients
  reporting/        daily_report.py (orchestration) + spreadsheet.py (openpyxl)
  fixtures/         Realistic mock payloads + the in-process mock API app
skills/daily-report/ Claude Code Skill for the reporting workflow
tests/              pytest suite (all run against mock mode)
examples/           Committed sample .xlsx + README preview image

既知の簡略化

このようなサンプルでは、体裁よりも正確さが重要であるため、隠すのではなくここに文書化します。

  • COGS は、実際の 2 ホップルックアップ(variant → inventory_item_id → バッチ取得した inventory_items)を介して Shopify の InventoryItem.cost フィールドを使用します — Shopify は注文のラインアイテムにコストを直接公開していません。ライブストアでは、cost とラインアイテムの sku はどちらも null 許容です(マーチャントが設定していない可能性があります)。これはドキュメントだけでなく、実際の開発ストアに対するライブテストで発見されました。どちらもエラーにするのではなく、コストゼロ / SKU なしとして処理されます。

  • 返金済みの注文 は、daily_pnl() の売上 / COGS / 注文数から完全に除外されます。部分返金・返品の会計処理には Refund リソースが必要になります — ここでは対象外です。

  • Meta の購入アトリビューション は、広告アカウントで設定されているアトリビューションウィンドウに基づき、actions/action_values 配列の purchase アクションタイプを使用します — このクライアントはそれを上書きしません。

  • レポーティングエージェントは現在、日付範囲でフィルタリングせず、利用可能な注文 / インサイトをすべて取得します。本番の日次 cron では、対象日の created_at_min/time_range を渡すことになるでしょう。

ライセンス

MIT — LICENSE を参照してください。

Available Tools

2 tools
get_daily_pnlA

Revenue, COGS, and gross profit across the current order set.

COGS is resolved per line item via the Shopify inventory item cost field. Refunded orders are excluded.

NameRequiredDescriptionDefault

No parameters

TDQS

A4/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 of behavioral disclosure. It usefully explains that COGS is resolved per line item and that refunded orders are excluded. However, it does not define what 'current order set' means or how the 'daily' period is determined, leaving ambiguity in the tool's scope.

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 description is compact and front-loaded, with the core metrics stated in the first sentence. Every subsequent line adds distinct value: cost-resolution method and refund exclusion. There is no redundancy or filler.

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?

There is no output schema or annotations, so the description must communicate both the result metric and behavioral caveats, which it does adequately for a zero-parameter tool. The main gap is that the exact time period of 'current order set' is left undefined.

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 and the schema covers everything about parameters, so the description does not need to explain parameter semantics. It still adds meaning by describing what the computed values represent, which is sufficient given no parameters exist.

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 the specific metrics 'Revenue, COGS, and gross profit' and names the resource 'current order set.' This clearly distinguishes the tool from its sibling get_orders, which would return orders rather than a financial summary.

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?

The description gives helpful context such as 'across the current order set' and 'Refunded orders are excluded,' but it does not explicitly state when to use this tool versus get_orders or when not to use it. Usage guidance is implied rather than clearly articulated.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

get_ordersA

Fetch Shopify orders (paginated automatically).

Args: status: Order status filter — "any", "open", "closed", or "cancelled".

NameRequiredDescriptionDefault
statusNoany

Output Schema

NameRequiredDescription
resultYes

TDQS

A4.4/5.0
Behavior4/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 usefully discloses that pagination is handled automatically, which is a non-obvious behavior an agent needs to know. It does not mention auth or rate limits, but for a simple fetch operation the pagination disclosure is meaningful.

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?

Two concise sentences cover purpose, pagination behavior, and the parameter's allowed values. Every sentence earns its place, and the most important information is front-loaded.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a one-parameter fetch tool with an output schema, this description is complete. It covers what the tool does, the parameter semantics, and a key behavioral detail (automatic pagination). The sibling tool is clearly distinct, so no additional routing context is necessary.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/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. It fully defines the only parameter, status, and lists all allowed values: 'any', 'open', 'closed', or 'cancelled'. This adds clear meaning beyond the schema, which only shows type and default.

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?

Description states a specific action and resource: 'Fetch Shopify orders'. The automatic pagination note adds scope, and the sibling get_daily_pnl is clearly a different resource, so an agent can distinguish them without opening schemas.

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?

The description implies usage when order data is needed and offers a status filter, but it does not explicitly say when to use this tool versus get_daily_pnl or any other alternative. There are no exclusions or conditional routing cues.

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. 2 tool updatesv0.1.0
    • First observedget_daily_pnl
    • First observedget_orders

TDQS

A3.9/5.0

Scored across 2 tools

Disambiguation5/5

get_orders returns raw order data, while get_daily_pnl computes financial metrics. Their purposes are entirely distinct with no overlap, making tool selection unambiguous.

Naming Consistency5/5

Both tools follow the consistent get_<noun> pattern, which is clear and predictable. There is no mixing of styles or ambiguous verbs.

Tool Count3/5

With only two tools, the set feels thin for a server labeled 'ecommerce automation'. However, it is not a single trivial tool, so borderline is appropriate.

Completeness1/5

The server provides only read-only order access and a PnL report. There are no create/update/delete operations, product or customer tools, refund handling, or broader automation workflows, making the surface severely incomplete for ecommerce automation.

Maintenance

ActivityStale
ResponsivenessNo recent community issues

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    D
    maintenance
    Connects e-commerce and marketing data sources like Shopify, GA4, Google Ads, and Meta Ads to AI assistants, enabling natural language queries about store performance, ad campaigns, and customer behavior.
    11 npm
    2
    MIT
  • F
    license
    Not graded
    quality
    D
    maintenance
    Hosted MCP server connecting Shopify, Klaviyo, GA4, Meta Ads, Google Ads, Xero, Gorgias and 20+ e-commerce data sources so AI assistants can answer merchant questions that span every source at once.
    -
  • A
    license
    Not graded
    quality
    B
    maintenance
    Connects Amazon Seller Central and Amazon Advertising to any MCP client, with a settlement-accurate P&L underneath: every fee, refund and reimbursement as Amazon actually posted it, so contribution margin and breakeven are per product, per marketplace, per day. 107 tools spanning P&L, full Sponsored Products/Brands/Display management, Search Query Performance and Brand Analytics, inventory and for
    1
    MIT
  • A
    license
    Not graded
    quality
    C
    maintenance
    Enables AI agents to fetch Xiaohongshu advertising data from Chengfeng, Juguang, and Dandelion platforms via MCP, and supports syncing daily ad reports to Feishu.
    1
    MIT