Command Palette

Search for a command to run...

UnylyUnyly
Весь каталог

CommerceOps Server

БесплатноНе проверен

CommerceOps MCP Server is an AI-native Model Context Protocol server for e-commerce operations, enabling AI agents to autonomously diagnose and resolve operatio

GitHubEmbed

Описание

CommerceOps MCP Server is an AI-native Model Context Protocol server for e-commerce operations, enabling AI agents to autonomously diagnose and resolve operational exceptions such as stuck orders, missed payment webhooks, warehouse delays, and oversold inventory, with built-in safety guardrails and audit logging.

README

An AI-native, production-grade Model Context Protocol (MCP) server written in TypeScript, designed to enable AI Operations Agents to autonomously investigate and resolve complex e-commerce operational exceptions (stuck orders, missed payment webhooks, warehouse fulfillment delays, and oversold inventory).


🎯 Key Architectural Pillars

  1. Raw Operational Signals (No Pre-Baked Diagnostic Labels): Seed orders store only realistic backend fields (order_status, payment, inventory, fulfillment). diagnose() computes root-cause explanations and evidence dynamically at runtime.

  2. Strict Bounded Action Enum & Safety Policy: All state mutations are restricted to a closed enum of actions (refund_duplicate_charge, requeue_to_warehouse, release_reserved_stock, resync_shipping_address). Every resolution call structurally enforces a pre-execution safety check (evaluate_safety).

  3. Universal Risk-Score Pre-Gate & Central Policy Config:

    • Payment Risk Gate: Orders with risk_score > 60 are blocked and escalated immediately.
    • Autonomous Refund Cap: Auto-refunds capped at ₹1,000 INR. Over-limit refunds are escalated.
    • Fulfillment Staleness Threshold: Warehouse requeue requires days_since_last_update >= 3.
    • Oversold Stock Protection: Stock release blocked if stock_on_hand === 0.
  4. Neon PostgreSQL Database & Dual Store Architecture:

    • Cloud Persistence: Uses @neondatabase/serverless to store all 6 normalized order tables, audit_log, and order_analysis_log in a Neon DB instance when DATABASE_URL is set.
    • Local Dev Fallback: Gracefully falls back to an in-memory store when running locally without a database connection.
  5. Durable Auditing & Order Analysis Activity Logging:

    • Audit Log: Durably records every resolution attempt (executed vs escalated), policy reason, and actor.
    • Analysis Log: Records diagnostic runs, evidence snapshots, and safety check evaluations for full operational auditability.
    • Exposed via MCP resources (commerce://audit/log, commerce://analysis/log) and REST API (/api/audit, /api/analysis).

🏗️ Technical Architecture & Step-by-Step Call Flow

1. Vertical Sequential Call & Policy Execution Flow

[ Ops User Inquiry ]
  │  "Investigate operational exception or order status"
  ▼
[ Client LLM (MCP Consumer) ]
  │
  ├─► STEP 1: Discovery & Telemetry Retrieval
  │   Tool Call: search_orders(order_id)
  │   └──► [ CommerceOps MCP Server ]
  │        Returns: Raw Telemetry Record (order_status, payment, inventory, fulfillment, risk_score)
  │
  ├─► STEP 2: Root-Cause Reasoning & Evidence Synthesis
  │   Tool Call: diagnose(order_id)
  │   └──► [ CommerceOps MCP Server ]
  │        Returns: Dynamic root_cause, evidence snapshot & recommended resolution action
  │
  ├─► STEP 3: Agentic Decision Node
  │   Evaluate Resolution Pathway:
  │   ├── Autonomous Resolution  ──► (Proceed to Pre-Execution Safety Evaluation)
  │   └── Escalation Required    ──► (Flag for Supervisor / Procurement / Fraud Review)
  │
  ├─► STEP 4: Pre-Execution Safety & Policy Guardrails
  │   Tool Call: evaluate_safety(order_id, action)
  │   └──► [ CommerceOps MCP Server Policy Engine ]
  │        Evaluates Central Rules:
  │        ├── 1. Fraud Risk Pre-Gate  : (risk_score <= 60)
  │        ├── 2. Auto-Refund Cap      : (amount <= ₹1,000 INR)
  │        ├── 3. Fulfillment Staleness : (days_inactive >= 3)
  │        └── 4. Oversold Stock Gate  : (stock_on_hand > 0)
  │        Returns: { allowed: boolean, reason: string }
  │
  ├─► STEP 5: State Mutation & Durable Audit Logging
  │   Tool Call: execute_resolution(order_id, action)
  │   └──► [ CommerceOps MCP Server Data Engine ]
  │        ├── Mutates Order State (refunded / requeued_picking / escalated)
  │        └── Appends Audit Entry to commerce://audit/log & Neon PostgreSQL
  │        Returns: Execution outcome & durable audit ID
  │
  ▼
[ Ops User Response ]
  Transparent report: Root cause + Guardrail status + Execution result + Audit trace

2. High-Level Component Architecture

+-----------------------------------------------------------------------------------+
|                            MCP AI CONSUMER CLIENT                                 |
|            (Claude Desktop / Cursor / Custom Agent / Antigravity IDE)             |
+-----------------------------------------------------------------------------------+
                                         │
                   Remote SSE (/sse) OR Stdio Transport (--stdio)
                                         ▼
+-----------------------------------------------------------------------------------+
|                           COMMERCE OPS MCP SERVER                                 |
|                                                                                   |
|  +------------------------+  +------------------------+  +---------------------+  |
|  |     BOUNDED TOOLS      |  |     MCP RESOURCES      |  |     MCP PROMPTS     |  |
|  | - list_orders          |  | - orders/seed          |  | - investigate_stuck |  |
|  | - search_orders        |  | - audit/log            |  +---------------------+  |
|  | - diagnose             |  | - analysis/log         |                           |
|  | - evaluate_safety      |  +------------------------+                           |
|  | - execute_resolution   |                                                       |
|  +------------------------+                                                       |
|                                        │                                          |
|                                        ▼                                          |
|                  +------------------------------------------+                     |
|                  |     SAFETY & ESCALATION POLICY ENGINE    |                     |
|                  | - Risk Gate (risk_score <= 60)          |                     |
|                  | - MAX_AUTO_REFUND_LIMIT_INR (₹1,000)     |                     |
|                  | - Staleness Threshold (3 days)           |                     |
|                  | - Oversold Stock Protection (OnHand > 0) |                     |
|                  +------------------------------------------+                     |
|                                        │                                          |
|                                        ▼                                          |
|                  +------------------------------------------+                     |
|                  |      COMMERCE STORE & DATA ENGINE        |                     |
|                  |   (OMS, WMS, Payment Gateway, Audit Log) |                     |
|                  +------------------------------------------+                     |
|                                        │                                          |
|                                        ▼                                          |
|                  +------------------------------------------+                     |
|                  |     DURABLE FILE & NEON DB PERSISTENCE   |                     |
|                  |         (./data/audit_log.json)          |                     |
|                  +------------------------------------------+                     |
+-----------------------------------------------------------------------------------+

3. Detailed Step-by-Step Execution Lifecycle

  1. Discovery & Data Fetch (list_orders / search_orders):

    • The Client LLM searches or fetches raw order signals (payment.payment_status, payment.risk_score, fulfillment.picking_status, inventory.stock_on_hand).
    • Signal data contains zero pre-baked diagnostic answers.
  2. Dynamic Root Cause Diagnosis (diagnose):

    • The server inspects raw telemetry dynamically and infers root cause (e.g., missed payment webhook, warehouse bottleneck, oversold flash-sale, fraud risk).
    • Returns diagnostic evidence snapshot and recommended resolution action.
  3. Pre-Execution Safety & Escalation Gate (evaluate_safety):

    • Before executing any mutation, safety policies are evaluated in strict order:
      1. Fraud Risk Gate: payment.risk_score > 60 immediately short-circuits execution and marks order as ESCALATED to human fraud team.
      2. Autonomous Refund Cap: Refunds > ₹1,000 INR require human manager escalation.
      3. Fulfillment Staleness Threshold: Warehouse requeue requires elapsed staleness >= 3 days.
      4. Oversold Inventory Gate: Stock release blocked if physical inventory on hand is 0.
  4. Bounded State Mutation & Durable Auditing (execute_resolution):

    • Allowed Actions: Bounded enum (mark_order_paid_reconcile, refund_duplicate_charge, refund_over_cap, requeue_to_warehouse, release_reserved_stock, resync_shipping_address).
    • If safety passes, state is updated (paid, requeued, refunded, etc.) and an executed entry is logged.
    • If safety fails or human review is required, status becomes escalated and an escalated entry is logged.
    • All events append to both commerce://audit/log and commerce://analysis/log (or Neon DB tables).

📊 Seed Dataset & Policy Matrix (6 Core Scenarios)

Order ID Customer Amount Raw Signals Diagnostic Root Cause Policy / Safety Evaluation Expected Outcome
ORD-1001 Aarav Sharma ₹300 captured, pending, webhook: false, risk: 10 Missed gateway webhook Reconcile missed webhook (no money movement) EXECUTED: Status set to paid, webhook flag set true
ORD-1002 Priya Patel ₹4,999 reserved, picked: false, stale: 4 days Fulfillment stalled at warehouse Stale 4 days >= 3 threshold EXECUTED: Requeued for picking
ORD-1003 Vikramaditya Roy ₹4,000 status: refund_requested, risk: 20 Refund requested above cap Amount ₹4,000 > ₹1,000 cap ESCALATED: Requires supervisor approval
ORD-1004 Sneha Kulkarni ₹12,999 captured, reserved, stock_on_hand: 0 Inventory oversold (flash-sale) Stock on hand is 0 ESCALATED: Requires procurement review
ORD-1005 Rohan Verma ₹1,499 captured, picked: true, stock_on_hand: 31 No issue found (control case) N/A (normal processing) NO ACTION: Progressing normally (recommended_action: null)
ORD-1006 Meera Nair ₹500 captured, pending, webhook: false, risk: 85 Missed gateway webhook Risk score 85 > 60 threshold ESCALATED: Blocked by Fraud Risk Gate

🛠️ MCP Tools, Resources & Prompts

1. Bounded MCP Tools (src/mcp/tools.ts)

Tool Name Description Key Arguments
list_orders Returns triage-level list of orders with computed flagged_for_review boolean. status (optional filter)
search_orders Returns full raw order record (nested payment, inventory, fulfillment, items). order_id (required), status, customer
diagnose Computes root-cause reasoning, evidence snapshot, and recommended action. order_id (required)
evaluate_safety Pre-execution safety check against centralized policy thresholds. order_id (required), action (required)
execute_resolution Executes bounded action after safety check. Writes to audit & analysis logs. order_id (required), action (required), actor
reset_store_to_defaults TRUNCATEs DB/memory store and re-seeds original 6 seed orders. None

2. MCP Resources (src/mcp/resources.ts)

  • commerce://orders/seed: Live JSON list of all seed orders.
  • commerce://audit/log: Immutable audit log of all resolution attempts (executed / escalated).
  • commerce://analysis/log: Full agent activity trace (diagnostic runs, evidence, safety evaluations).

3. MCP Prompts (src/mcp/prompts.ts)

  • investigate_stuck_order: Step-by-step guided prompt instructing an AI Operations Agent to search order, run diagnosis, evaluate safety guardrails, execute resolution, and draft transparent customer updates.

🚀 Deployment & Environment Setup

1. Environment Variables (.env)

Copy .env.example to .env:

DATABASE_URL=postgresql://neondb_owner:[email protected]/neondb?sslmode=require
PORT=3000

2. Build & Run locally

# Install dependencies
npm install

# Build TypeScript to dist/
npm run build

# Start production SSE server
npm start

3. Deploying to Render

  • Environment: Node.js Web Service
  • Build Command: npm run build
  • Start Command: npm start
  • Environment Variables: Add DATABASE_URL pointing to your Neon database URL.

🧪 Testing & MCP Inspector CLI Verification

Run Unit Test Suite (Vitest)

npm test

Output:

 ✓ tests/workflow.test.ts (1 test)
 ✓ tests/guardrails.test.ts (6 tests)
 ✓ tests/mcp-tools.test.ts (5 tests)

 Test Files  3 passed (3)
      Tests  12 passed (12)

Test via MCP Inspector CLI (dist/stdio.js)

# 1. Test ORD-1006 risk score escalation
npx @modelcontextprotocol/inspector --cli node dist/stdio.js \
  --method tools/call --tool-name execute_resolution \
  --tool-arg order_id=ORD-1006 --tool-arg action=mark_order_paid_reconcile

# 2. Test ORD-1001 reconciliation execution
npx @modelcontextprotocol/inspector --cli node dist/stdio.js \
  --method tools/call --tool-name execute_resolution \
  --tool-arg order_id=ORD-1001 --tool-arg action=mark_order_paid_reconcile

# 3. Read Analysis Activity Logs Resource
npx @modelcontextprotocol/inspector --cli node dist/stdio.js \
  --method resources/read --uri commerce://analysis/log

🧠 Design Rationale & Production Limitations

Deterministic Rule-Based Diagnostic Engine vs. Free-Form LLM Reasoning

The diagnose() tool is implemented as a deterministic, rule-based engine rather than having the LLM reason freely over raw order data each time:

  • How it works: The tool evaluates a fixed set of priority rules against raw telemetry fields (payment gateway status, webhook receipt, inventory reservation, staleness, stock levels) and returns the first matching root cause alongside structured evidence. Nothing is pre-labeled in the seed data itself — the conclusion is computed fresh on every call.
  • Why this design: Root-causing whether an order is stuck and why has one correct answer given the data. Externalizing this into a deterministic engine ensures diagnostic accuracy is reliable, repeatable, and unit-testable, rather than left to non-deterministic LLM judgment each time.
  • LLM's Role: The Client LLM's role is to decide what to do with the diagnosis (call evaluate_safety, execute_resolution, or report back), not to re-derive the root cause itself.
  • Scenarios Covered:
    1. Missed/Dropped Payment Webhook (mark_order_paid_reconcile)
    2. Stalled Warehouse Fulfillment (requeue_to_warehouse)
    3. Over-Cap Refund Request (refund_over_cap)
    4. Oversold Flash-Sale Inventory (release_reserved_stock)
    5. Healthy Control Case (recommended_action: null)

Production Trade-offs & Limitations

  • Rule Scalability: This hardcoded rule-based approach covers the 5 seeded e-commerce scenarios well, but would not scale cleanly to hundreds of complex edge cases as-is.
  • Production Architecture Next Steps: A full enterprise production version would:
    1. Externalize rules into a data-driven rule engine table (e.g. JSON-Logic / Drools).
    2. Incorporate an LLM-assisted fallback mechanism for unmapped operational anomalies rather than defaulting strictly to "healthy", allowing novel edge cases to be dynamically flagged for human triage.

📁 Repository Structure

commerce-ops-mcp/
├── src/
│   ├── index.ts                # Remote SSE/HTTP Express Server (/sse, /message, /health, /api/*)
│   ├── stdio.ts                # Stdio Entrypoint for local MCP Inspector testing
│   ├── server.ts               # MCP Server instantiation & tool/resource registration
│   ├── chat.ts                 # Interactive Ops AI Chat handler
│   ├── config.ts               # Centralized Policy Config thresholds (caps, risk limit, staleness)
│   ├── db/
│   │   └── client.ts           # Singleton Neon Serverless PostgreSQL SQL client
│   ├── domain/
│   │   ├── types.ts            # Core Interfaces (Order, Payment, Inventory, AuditLog, AnalysisLog)
│   │   ├── mockData.ts         # Raw 6 Seed Orders (no diagnostic labels)
│   │   ├── store.ts            # In-Memory Store Implementation (ICommerceStore)
│   │   └── dbStore.ts          # Neon PostgreSQL Store Implementation (DatabaseCommerceStore)
│   └── mcp/
│       ├── tools.ts            # 5 Bounded MCP Tools + reset tool
│       ├── resources.ts        # MCP Resources (orders, audit log, analysis activity log)
│       ├── prompts.ts          # MCP Prompts (guided investigation workflow)
│       └── guardrails.ts       # Safety Guardrail Engine wrapper
├── tests/
│   ├── guardrails.test.ts      # Policy thresholds & Risk-score pre-gate tests
│   ├── mcp-tools.test.ts       # Bounded tool execution & audit log tests
│   └── workflow.test.ts        # Full 6-seed scenario integration tests
├── .env.example                # Template environment file
├── .gitignore                  # Git ignore rules (.env, dist/, node_modules/, draft files)
├── AI_WORKLOG.md               # AI Worklog, Prompts & Correction Audit
├── package.json
└── tsconfig.json

from github.com/Krishcode264/commerce-ops-mcp

Установка CommerceOps Server

У этого сервера нет опубликованного пакета — он собирается из исходников. Открой репозиторий и следуй инструкции в README.

▸ github.com/Krishcode264/commerce-ops-mcp

FAQ

CommerceOps Server MCP бесплатный?

Да, CommerceOps Server MCP бесплатный — установка в пару кликов через Unyly без оплаты.

Нужен ли API-ключ для CommerceOps Server?

Нет, CommerceOps Server работает без API-ключей и переменных окружения.

CommerceOps Server — hosted или self-hosted?

Self-hosted: сервер запускается локально на твоей машине командой из раздела установки.

Как установить CommerceOps Server в Claude Desktop, Claude Code или Cursor?

Открой CommerceOps Server на unyly.org, выбери вкладку своего клиента (Claude Desktop, Claude Code, Cursor) и нажми Install — конфиг сгенерируется автоматически, без правки JSON.

Похожие MCP

Compare CommerceOps Server with

Не уверен что выбрать?

Найди свой стек за 60 секунд

Автор?

Embed-бейдж для README

Похожее

Все в категории finance