Skip to main content
Glama
petrycz

ecommerce-mcp-automation

by petrycz

Ecommerce MCP Automation

A sample Claude Code + MCP integration: Shopify and Meta Ads exposed as MCP tools, plus a reporting agent that pulls both into one formatted daily P&L + ad-performance spreadsheet — no manual copy-paste between platforms.

Это демонстрация, собранная по публичной документации Shopify Admin API и Meta Marketing API — не то, что работало на реальном бизнесе. Это clean-room пример: реальные эндпоинты, реальная аутентификация, реальная пагинация, реальная обработка ошибок, написанные с нуля, чтобы показать, как именно строится такая автоматизация. Он работает end-to-end в mock-режиме без учётных данных (реалистичные фикстурные данные вместо живых ответов) и переключается в live-режим для каждой интеграции, как только задаются реальные учётные данные — см. Как запустить.

Клиент Shopify запускался в live-режиме против реального магазина для разработки Shopify Partners (песочницы, а не производственного бизнеса) — реальная аутентификация, реальный заказ, реальные ответы API. В ходе этого процесса всплыли и были исправлены два реальных крайних случая с nullable-значениями (см. Известные упрощения), которые одни только mock-фикстуры не покрывали. Meta Ads в этом репозитории по умолчанию работает через mock-транспорт; код клиента написан так же и переключается на live, как только заданы 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, который оборачивает весь рабочий процесс в триггер на естественном языке («запусти ежедневный отчёт»)

  • Включает готовый пример вывода, так что результат виден без запуска чего-либо

Related MCP server: Presso MCP Server

Пример вывода

Предварительный рендер вкладки 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

Два API-клиента (clients/shopify_client.py, clients/meta_ads_client.py) — это настоящий интеграционный код: реальные URL эндпоинтов, реальные заголовки аутентификации, реальные циклы пагинации, реальный backoff для 429. Единственное, что меняется между mock- и live-режимом, — это HTTP-транспорт (clients/http.py):

  • Live: httpx.AsyncClient открывает реальное соединение с Shopify / Meta.

  • Mock: httpx.AsyncClient получает httpx.ASGITransport, указывающий на внутрипроцессное FastAPI-приложение (fixtures/mock_api.py), отдающее реалистичные фикстурные данные. Порт не занимается, подпроцесс не запускается — но запросы по-прежнему проходят через настоящую HTTP/ASGI-маршрутизацию, заголовки и JSON-кодирование.

Это означает, что код клиента, который читает ревьюер, — это тот же код, который выполнялся бы против живого магазина, а не mock, наряженный, чтобы выглядеть как настоящий. Полные правила см. в CLAUDE.md.

Как запустить

Mock-режим (по умолчанию — без учётных данных)

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

Live-режим

Скопируйте .env.example в .env и заполните то, что у вас есть, — каждая интеграция переключается в live-режим независимо, как только появляются её собственные учётные данные, так что вы можете запустить Shopify в live, а Meta оставить в mock-режиме (или наоборот):

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-конфиг (.mcp.json для Claude Code или файл конфигурации Claude Desktop). Укажите command напрямую на интерпретатор venv проекта — MCP-клиенты не подгружают ваш профиль оболочки, поэтому голый python не увидит активированное виртуальное окружение:

{
  "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"
    }
  }
}

Затем спрашивайте Клода что-то вроде «какой сегодня P&L у Shopify?» или «покажи мне вчерашнюю эффективность Meta Ads» — он вызовет инструменты напрямую, по умолчанию в mock-режиме.

Как навык

skills/daily-report/SKILL.md оборачивает процесс генерации отчёта, чтобы Claude Code запускал его по триггеру на естественном языке («запусти ежедневный отчёт»), а не по точной команде CLI. Путь полного отчёта вообще не нуждается в MCP-конфиге выше — он напрямую запускает daily_report.py, который вызывает клиенты как обычный Python, без участия MCP. MCP-конфиг нужен только для другого пути навыка: ответа на разовый вопрос по одной метрике («какой сегодня ROAS?») через вызов get_daily_pnl / get_daily_ad_performance как MCP-инструментов вместо запуска полного отчёта.

Структура проекта

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 использует поле InventoryItem.cost в Shopify через настоящий двухэтапный поиск (вариант → inventory_item_id → пакетное получение inventory_items) — Shopify не отдаёт себестоимость напрямую в позиции заказа. И cost, и sku позиции заказа могут быть nullable в живом магазине (торговец мог их никогда не задавать) — это обнаружено при live-тестировании на реальном dev-магазине, а не только по документации. Оба случая обрабатываются как нулевая себестоимость / отсутствующий SKU, а не как ошибка.

  • Возвращённые заказы полностью исключаются из выручки/COGS/количества заказов в daily_pnl(). Учёт частичных возвратов и возвратов товаров потребовал бы ресурса Refund — это вне рамок данного примера.

  • Атрибуция покупок в Meta использует тип действия purchase из массивов actions/action_values в том окне атрибуции, которое настроено для рекламного аккаунта, — этот клиент его не переопределяет.

  • Агент отчётности в настоящее время забирает все доступные заказы/инсайты, а не фильтрует по диапазону дат; в продакшене ежедневный 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

ActivitySlowing
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • A
    license
    A
    quality
    F
    maintenance
    Free, open-source MCP server that connects Claude to the Shopify Partner API. 25 tools for revenue analytics, churn analysis, retention cohorts, merchant health scoring, conversion funnels, revenue forecasting, and growth velocity.
    25
    24 PyPI
    14
    MIT
  • 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