ecommerce-mcp-automation
Ecommerce MCP Automation
Una integración de ejemplo con Claude Code + MCP: Shopify y Meta Ads expuestos como herramientas MCP, además de un agente de informes que reúne ambos en una hoja de cálculo diaria formateada P&L + rendimiento publicitario — sin copiar y pegar manualmente entre plataformas.
Esta es una demostración construida a partir de la documentación pública de la API de Shopify Admin y la API de Meta Marketing — no es algo que haya operado un negocio real. Es una muestra de sala limpia: endpoints reales, autenticación real, paginación real, manejo de errores real, escrita desde cero para mostrar exactamente cómo se construye este tipo de automatización. Se ejecuta de principio a fin en modo simulado sin credenciales (datos de fixture realistas que sustituyen a las respuestas en vivo), y cambia a modo en vivo por integración en cuanto se establecen credenciales reales — consulte Cómo ejecutar.
El cliente de Shopify se ha ejecutado en vivo contra una tienda de desarrollo real de Shopify Partners (una tienda sandbox, no un negocio de producción) — autenticación real, un pedido real, respuestas reales de la API. Ese proceso sacó a la luz y corrigió dos casos límite reales de nulabilidad (consulte Simplificaciones conocidas) que los fixtures mock por sí solos no habían cubierto. Meta Ads se ejecuta contra el transporte mock por defecto en este repositorio; el código del cliente está escrito igual y cambia a en vivo en cuanto se establecen
META_ACCESS_TOKEN/META_AD_ACCOUNT_ID.
Qué hace
Expone pedidos, ingresos y COGS de Shopify como herramientas MCP (
get_orders,get_daily_pnl)Expone el gasto, las impresiones, las compras y el ROAS de Meta Ads como herramientas MCP (
get_insights,get_daily_ad_performance)Ejecuta un agente de informes (
daily_report.py) que obtiene ambos simultáneamente y escribe un.xlsxcon formato — hojas de Summary, Orders y Ad PerformanceIncluye una habilidad de Claude Code que envuelve todo el flujo de trabajo en un disparador en lenguaje natural ("ejecuta el informe diario")
Incluye una salida de ejemplo ya confirmada en el repositorio para que el resultado sea visible sin ejecutar nada
Related MCP server: Ask AI
Salida de ejemplo
Vista previa renderizada de la pestaña Summary — abre el libro de trabajo generado real para ver el archivo en vivo (con las hojas Orders y Ad Performance, formato de moneda/ROAS y filas de cabecera congeladas).
Arquitectura
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.-> MCLos dos clientes de API (clients/shopify_client.py, clients/meta_ads_client.py)
son código de integración genuino: URLs de endpoints reales, cabeceras de autenticación reales,
bucles de paginación reales, backoff real de 429. Lo único que cambia entre el
modo simulado y el modo en vivo es el transporte HTTP (clients/http.py):
Live:
httpx.AsyncClientabre una conexión real con Shopify / Meta.Mock: a
httpx.AsyncClientse le da unhttpx.ASGITransportapuntando a una aplicación FastAPI en proceso (fixtures/mock_api.py) que sirve payloads de fixture realistas. No se vincula ningún puerto, no se ejecuta ningún subproceso — pero las peticiones aún viajan mediante enrutamiento HTTP/ASGI genuino, cabeceras y codificación JSON.
Eso significa que el código de cliente que un revisor lee es el mismo código que se ejecutaría contra una tienda en vivo — no un mock disfrazado para parecerlo. Consulte CLAUDE.md para conocer todas las convenciones.
Cómo ejecutar
Modo simulado (por defecto — cero credenciales)
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.xlsxEjecute la suite de pruebas de la misma manera, sin necesidad de configuración:
pytestModo en vivo
Copie .env.example a .env y rellene lo que tenga — cada integración
pasa a en vivo de forma independiente en cuanto están presentes sus propias credenciales,
de modo que puede ejecutar Shopify en vivo con Meta aún en modo simulado (o viceversa):
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_1234567890Como servidores MCP (Claude Code / Claude Desktop)
Añádalo a su configuración de MCP (.mcp.json para Claude Code, o el archivo de
configuración de Claude Desktop). Apunte command directamente al intérprete del venv del proyecto —
los clientes MCP no cargan su perfil de shell, por lo que un python a secas no verá un
venv activado:
{
"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"
}
}
}Luego pregúntele a Claude cosas como "¿cuál es el P&L de Shopify hoy?" o "déme el rendimiento publicitario de Meta de ayer" — llamará a las herramientas directamente, en modo simulado por defecto.
Como habilidad
skills/daily-report/SKILL.md envuelve el flujo de trabajo de generación de informes para que
Claude Code lo ejecute mediante un disparador en lenguaje natural ("ejecuta el informe diario")
en lugar de necesitar el comando CLI exacto. La ruta del informe completo no necesita
la configuración de MCP anterior en absoluto — ejecuta daily_report.py directamente,
que llama a los clientes como Python puro, sin MCP involucrado. La configuración de MCP solo se
necesita para la otra ruta del Skill: responder a una pregunta puntual de una sola métrica
("¿cuál es el ROAS de hoy?") llamando a get_daily_pnl /
get_daily_ad_performance como herramientas MCP en lugar de ejecutar el informe completo.
Estructura del proyecto
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 imageSimplificaciones conocidas
Documentadas aquí en lugar de ocultas, ya que la precisión importa más que el pulido en una muestra como esta:
COGS utiliza el campo
InventoryItem.costde Shopify mediante la búsqueda real de dos saltos (variant →inventory_item_id→ obtención por lotes deinventory_items) — Shopify no expone el coste directamente en la línea de pedido. Tantocostcomo elskude la línea de pedido son anulables en una tienda en vivo (un comercio puede no haberlos establecido nunca) — detectado mediante pruebas en vivo contra una tienda de desarrollo real, no a partir de la documentación únicamente. Ambos se manejan como coste cero / SKU ausente en lugar de dar error.Los pedidos reembolsados se excluyen por completo del recuento de ingresos/COGS/pedidos en
daily_pnl(). La contabilización de reembolsos/devoluciones parciales requeriría el recurso Refund — fuera del alcance aquí.La atribución de compras de Meta utiliza el tipo de acción
purchasede los arraysactions/action_valuesen cualquier ventana de atribución con la que la cuenta publicitaria esté configurada — este cliente no la anula.El agente de informes actualmente obtiene todos los pedidos/insights disponibles en lugar de filtrar por rango de fechas; un cron diario de producción pasaría
created_at_min/time_rangepara el día objetivo.
Licencia
MIT — consulte LICENSE.
Available Tools
2 toolsget_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.
| Name | Required | Description | Default |
|---|---|---|---|
No parameters | |||
TDQS
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.
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.
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.
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.
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.
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".
| Name | Required | Description | Default |
|---|---|---|---|
| status | No | any |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
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.
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.
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.
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.
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.
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.
2 tool updates
v0.1.0- First observed
get_daily_pnl - First observed
get_orders
TDQS
Scored across 2 tools
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.
Both tools follow the consistent get_<noun> pattern, which is clear and predictable. There is no mixing of styles or ambiguous verbs.
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.
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.
Related MCP Connectors
Remote MCP for Shopify, Meta Ads, Google Ads and TikTok Ads with human approval for writes
Connects Amazon Seller Central and Amazon Advertising to any MCP client. Settlement-accurate P&L - every fee, refund and reimbursement as Amazon posted it - plus contribution margin and breakeven per product, per marketplace, per day. Full Sponsored Products, Brands and Display management: search terms, placements, keyword and competitor research, dayparting, automation rules. 110 tools: 78 read-only (P&L, PPC at every grain, SQP/Brand Analytics, inventory, forecasting), 28 staged writes (every change is a proposal you review and confirm before it reaches Amazon - there is no autonomous-write mode), and 4 confirmation & support tools. 4 additional AI Workforce tools appear once a client is connected.
Run Meta Ads and Google Ads for your Shopify store from Claude, ChatGPT or Cursor, with the store's own Shopify, Stripe or Klaviyo revenue next to ad spend. New campaigns are created paused.
Meta Ads MCP (Facebook + Instagram) - analyze performance, manage budgets, pause campaigns.
Related MCP Servers
AlicenseNot gradedqualityDmaintenanceConnects 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 npm2MIT- FlicenseNot gradedqualityDmaintenanceHosted 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.-
- AlicenseNot gradedqualityBmaintenanceConnects 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 for1MIT
- AlicenseNot gradedqualityCmaintenanceEnables AI agents to fetch Xiaohongshu advertising data from Chengfeng, Juguang, and Dandelion platforms via MCP, and supports syncing daily ad reports to Feishu.1MIT