retail-order-sync-hub
Syncs orders between Odoo ERP and multiple marketplaces, with traceability and incident resolution capabilities.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@retail-order-sync-hub trace order 12345 to see why it failed to sync to MercadoLibre"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
Retail Order Sync Hub — ERP ↔ Marketplaces
Sistema de sincronización de órdenes entre Odoo ERP y múltiples marketplaces (MercadoLibre sandbox + paris-mock), construido con outbox pattern, DLQ, observabilidad end-to-end y un MCP server que permite a un agente IA trazar y operar incidentes de sincronización.
"¿Por qué la orden ML-98345 no apareció en MELI?" → El agente responde con el trace completo y puede reintentar el envío con los permisos correctos.
El escenario
Un lunes con el equipo de Comercio Exterior:
Las órdenes en Odoo no aparecen en los marketplaces.
Los webhooks llegan pero nadie sabe si se procesaron.
El equipo de soporte no tiene visibilidad — necesita abrir un ticket a IT.
Este repo resuelve ese escenario end-to-end:
Odoo como fuente de verdad de órdenes.
Sync confiable a MercadoLibre y Paris con retry exponencial y DLQ.
Webhooks idempotentes con deduplicación y firma HMAC.
Bronze/Silver/Gold en BigQuery para analytics (dbt).
Observabilidad con OpenTelemetry, Grafana y alertas.
MCP server con IAM por scope y audit log — el agente puede responder y actuar.
Related MCP server: yt-mcp-server-odoo
Arquitectura
┌─────────────────────────────────────────────────────────────────────────────┐
│ Retail Order Sync Hub │
│ │
│ ┌─────────┐ outbox ┌──────────────┐ ┌────────────┐ │
│ │ Odoo │──pattern──▶│ Outbox Worker│───▶│ Adapters │──▶ MercadoLibre│
│ │ (ERP) │ │ retry/DLQ │ │ ML · Paris │──▶ paris-mock │
│ └─────────┘ └──────────────┘ └────────────┘ │
│ ▲ │ │ │
│ │ sync.dlq webhooks │
│ reconcile (Pub/Sub) (signed · idempotent) │
│ │ │ │
│ ┌────┴────────────┐ ┌─────────▼──────┐ │
│ │ Subscriber + │◀── marketplace ────│ Webhook │ │
│ │ Reconciler │ .events │ Receiver │ │
│ │ (silver orders) │ (Pub/Sub) │ (bronze · dedup)│ │
│ └────────┬────────┘ └────────┬────────┘ │
│ │ │ │
│ ┌─────▼──────────────────────────────────────▼──────┐ │
│ │ BigQuery │ │
│ │ bronze (raw) → silver (clean) → gold (SLA/KPIs) │ │
│ │ dbt models · contracts · singular tests │ │
│ └─────────────────────────┬──────────────────────────┘ │
│ │ │
│ ┌────────────────────────────▼──────────────────────────┐ │
│ │ MCP Server │ │
│ │ get_order_status · trace_order · get_dlq_depth │ │
│ │ get_sla_metrics · find_failed_orders │ │
│ │ replay_dlq_message · retry_failed_sync · drain_dlq │ │
│ │ IAM (scopes: orders.read / dlq.replay / dlq.admin) │ │
│ │ Audit log (mcp_audit_log, transacción separada) │ │
│ └────────────────────────────▲──────────────────────────┘ │
│ │ MCP protocol (stdio) │
│ Claude Code / Desktop │
│ │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ Observabilidad: OTel Collector → Prometheus + Tempo │ │
│ │ Grafana: Comex Ops dashboard · Pipeline Health │ │
│ └──────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────┘Diagrama Mermaid completo: docs/diagrams/architecture.mmd
Stack
Capa | Tecnología |
Runtime | Python 3.11, uv, ruff, mypy strict |
API | FastAPI + Pydantic v2 |
DB | PostgreSQL (psycopg3) + SQLAlchemy 2.x + Alembic |
Broker | Google Cloud Pub/Sub (emulator local, real en GCP) |
Outbox | Patrón outbox con |
DLQ | Pub/Sub topic |
Analytics | BigQuery + dbt (bronze/silver/gold, contratos, tests singulares) |
AI | FastMCP 2.x, stdio transport, MCP_STATIC_TOKENS IAM |
Observabilidad | OpenTelemetry SDK + Collector → Prometheus + Tempo → Grafana |
Infra local | Docker Compose (stack + obs stack separados) |
CI | GitHub Actions (ruff + mypy + pytest, coverage ≥ 85%) |
Panel de control (la forma más simple)
Para demos sin tocar la terminal: un panel Streamlit local con botones para levantar el stack, ver el estado de cada contenedor en vivo y abrir Grafana/Prometheus.
make console # abre http://localhost:8501Botones para up / migrate / seed / chaos / obs-up, badges de estado por
servicio, accesos directos a los dashboards y health checks. Corre local (ejecuta
make/docker en tu máquina) — no exponer públicamente.
Quickstart (10 minutos)
Prerequisitos
Docker Desktop
Python 3.11 (
uvlo gestiona automáticamente)uvinstalado:curl -LsSf https://astral.sh/uv/install.sh | sh
1. Clonar e instalar
git clone https://github.com/JulioPradenas/retail-order-sync-hub.git
cd retail-order-sync-hub
uv sync --dev2. Levantar el stack
make up # Odoo, Postgres, Pub/Sub emulator, paris-mock
make migrate # aplica migraciones Alembic
make seed # carga órdenes demo en OdooEl primer make up descarga ~2 GB de imágenes. Odoo tarda ~60 s en iniciar.
3. Verificar
# Check de código + tests (85%+ cobertura)
make check
# Odoo disponible en
open http://localhost:8069 # admin / admin
# Paris-mock en
curl http://localhost:9100/orders -H "X-API-Key: change-me"
# Webhook receiver
curl http://localhost:8000/health4. Observabilidad (opcional)
make obs-up # Grafana + Prometheus + Tempo + OTel Collector
open http://localhost:3000 # Grafana — admin / adminDashboards disponibles:
Comex Ops — webhook throughput, sync outcomes, DLQ depth, latencia p95
Pipeline Health — OTel spans, FastAPI requests, Prometheus targets
5. Tests de integración
make up && make migrate
ROSH_INTEGRATION=1 uv run pytest -m integration -v6. BigQuery + dbt (requiere GCP)
cp dbt/profiles.yml.template ~/.dbt/profiles.yml
# Edita con tu project_id y credenciales
cd dbt && uv run dbt run && uv run dbt testMCP Server — Claude como operador de turno
El MCP server expone 8 herramientas a Claude Code o Claude Desktop para trazar y operar incidentes de sincronización.
Configuración (Claude Desktop)
{
"mcpServers": {
"retail-order-sync-hub": {
"command": "uv",
"args": ["run", "python", "-m", "src.mcp_server"],
"cwd": "/ruta/al/retail-order-sync-hub",
"env": {
"MCP_STATIC_TOKENS": "mi-token:orders.read,metrics.read,outbox.retry,dlq.replay",
"APP_DB_HOST": "localhost",
"APP_DB_PORT": "5433"
}
}
}
}Guía completa: docs/mcp-setup.md
Herramientas disponibles
Herramienta | Scope requerido | Descripción |
|
| Estado actual de una orden en Postgres silver |
|
| Timeline completa: webhooks → outbox → silver |
|
| Cantidad de órdenes en DLQ |
|
| p50/p95 de latencia de sync desde BigQuery gold |
|
| Órdenes sin sync en un período |
|
| Resetea una entrada DLQ a pending (auditado) |
|
| Re-encola todas las entradas DLQ de una orden (auditado) |
|
| Lista o limpia en bulk el DLQ (dry_run por default, auditado) |
Demo prompts
¿Por qué la orden ML-12345 no llegó a MercadoLibre?
trace_order("ML-12345")¿Cuántas órdenes están bloqueadas en DLQ en este momento?
get_dlq_depth()Hay 3 órdenes atascadas — reintentar todas con retry
retry_failed_sync("12345")IAM y scopes
Tres roles predefinidos para configurar tokens:
Rol | Scopes |
viewer |
|
operator | + |
admin | + |
Cada operación write queda registrada en mcp_audit_log con user_id, scope, params, resultado y latencia. Referencia completa: docs/iam.md
Documentación
Documento | Contenido |
Scopes, roles, tokens, audit log | |
Configuración Claude Desktop, demo prompts | |
Stack OTel, catálogo de métricas, dashboards | |
Contratos de adapters, retry policy | |
Narrativa FDE: decisiones, trade-offs, contexto | |
Deploy a GCP (Cloud Run, Pub/Sub, BigQuery Sandbox) | |
Análisis de costos GCP (objetivo <$10/mes) | |
Security review checklist | |
Outbox vs CDC, idempotencia, IAM del MCP | |
Architecture Decision Records (5 ADRs) | |
Modelos dbt, contratos de schema, tests singulares |
Estructura del repo
src/
adapters/ # Paris + MercadoLibre adapters (Protocol-based)
bq_sync/ # BigQuery watermark sync (bronze)
common/ # Config, DB, models, logging, OTel, signing
mcp_server/ # FastMCP server (read + write tools, IAM, audit)
outbox_worker/ # Outbox processor con retry exponencial + DLQ
paris_mock/ # Mock del marketplace Paris (FastAPI)
reconciler/ # Reconciliación silver → Odoo
subscriber/ # Pub/Sub subscriber → normalize → silver
webhook_receiver/ # Inbound webhooks (HMAC, dedupe, bronze)
infra/
docker-compose.yml # Stack operacional
docker-compose.obs.yml # Stack de observabilidad
grafana/ # Dashboards y datasources
dbt/ # Modelos bronze/silver/gold + contratos
migrations/ # Alembic migrations
tests/
unit/ # 141 tests unitarios (85%+ cobertura)
integration/ # Tests contra el stack real (ROSH_INTEGRATION=1)
docs/
adr/Fases completadas
Fase | Descripción | PR |
0 | Setup repo, ADRs, CI | #1 |
1 | Odoo + Postgres + OTel collector | #2 |
2 | MercadoLibre OAuth + paris-mock | #3 |
3 | Webhook receiver + idempotencia + bronze | #4 |
4 | Adapter + outbox + outbound sync | #5 |
5 | Subscriber + reconciliación + silver | #6 |
6 | Observabilidad (OTel + Grafana) | #7 |
7 | BigQuery + dbt + gold | #8 |
8 | MCP read tools + IAM estático | #9 |
9 | MCP write tools + audit log | #10 |
10 | Tests unitarios + chaos (85% coverage) | #11 |
11 | Docs + narrativa FDE | #12 |
V2 — GCP productivo (deploy-ready)
Artefactos de despliegue listos y verificados localmente. El deploy en vivo es un
comando con cuenta GCP autenticada (ver docs/deploy-gcp.md).
Sub-fase | Descripción | PR | Verificación local |
V2.1 | Cloud Run: Dockerfile productivo + Secret Manager | #15 |
|
V2.2 | Pub/Sub real + IAM least-privilege (Terraform) | #16 |
|
V2.3 | dbt scheduled (cron) + switch a Cloud Trace | #17 | YAML válido, |
V2.4 | Cost analysis + security review + blog técnico | #18 | docs |
BigQuery Sandbox corre sin tarjeta; Cloud Run / Pub/Sub / Secret Manager requieren billing activo.
Licencia
MIT
Available Tools
8 tools_drain_dlqA
List (dry_run=True) or bulk-reset (dry_run=False) all DLQ outbox entries. Scope: dlq.admin. Audited.
Inputs: dry_run, api_token. Returns: Generic wrapper for non-object return types.
_find_failed_ordersC
Find orders that were created but never successfully synced to a marketplace.
Inputs: since, api_token, marketplace. Returns: Generic wrapper for non-object return types.
_get_dlq_depthC
Return the number of orders currently stuck in the DLQ.
Inputs: api_token. Returns: Generic wrapper for non-object return types.
_get_order_statusC
Return the current status of an order from the silver layer.
Inputs: order_id (required), api_token. Returns: Generic wrapper for non-object return types.
_get_sla_metricsA
Return SLA metrics (avg, p50, p95 sync time in seconds) for a marketplace from the BigQuery gold layer.
Inputs: marketplace (required), window, api_token. Returns: Generic wrapper for non-object return types.
_replay_dlq_messageB
Reset a DLQ outbox entry back to pending so the worker retries it. Scope: dlq.replay. Audited.
Inputs: outbox_id (required), api_token. Returns: Generic wrapper for non-object return types.
_retry_failed_syncC
Force re-enqueue of an order into the outbox for all active adapters. Scope: outbox.retry. Audited.
Inputs: order_id (required), api_token. Returns: Generic wrapper for non-object return types.
_trace_orderB
Return a cross-source timeline for an order: inbound webhooks → outbox pushes → silver state.
Inputs: order_id (required), api_token. Returns: Generic wrapper for non-object return types.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 8 tools
Each tool has a distinct and clear purpose, from draining the DLQ to tracing an order's timeline. There is no overlap or ambiguity between tools.
All tools use snake_case with a leading underscore, but the verb-noun structure varies (e.g., 'drain_dlq' vs 'get_dlq_depth' vs 'retry_failed_sync'). Still, the pattern is largely consistent and readable.
With 8 tools, the server covers essential admin operations for order sync—DLQ management, order status, retries, and traces—without being bloated or insufficient.
The tool set focuses on debugging and manual intervention but lacks general monitoring or management tools (e.g., listing all orders, viewing sync history). Some functionality for updating or deleting orders is missing.
Maintenance
Related MCP Connectors
MCP server unifying ERPs, CRMs, APIs and knowledge base for Claude, ChatGPT and Gemini.
Hosted MCP server for OTTO Market, Kaufland and Mirakl sellers: orders, stock, listings and ads.
MCP server enabling AI agents to manage Bitrix24 features via standardized protocol
Hosted MCP for e-commerce: live product catalog, stock, and pricing for AI agents.
Related MCP Servers
- AlicenseBqualityDmaintenanceAn MCP server that enables AI assistants to interact with Odoo ERP apps like Inventory, CRM, Sales, and Manufacturing. It allows users to read, create, and manage Odoo records and workflows using natural language commands.2515 npm1ISC
- AlicenseNot gradedqualityDmaintenanceAn MCP server that enables AI assistants to interact with Odoo ERP, allowing natural language queries, record creation, updates, and deletions.LGPL 3.0
- AlicenseNot gradedqualityCmaintenanceAn MCP server that enables AI assistants to interact with Odoo ERP systems, allowing natural language access to business data, CRUD operations, and instance management without requiring Odoo module installation.1MIT
- AlicenseNot gradedqualityDmaintenanceMCP server integrating with Odoo ERP systems, enabling AI assistants to interact with Odoo data and functionality through tools and resources.MIT