Skip to main content
Glama
maheshsingh20

Commerce Operations MCP Server

README.md
# Commerce Operations MCP Server

AI-native solution for commerce operations teams to independently investigate and resolve order issues, particularly refund processing.

## Problem Statement

Operations teams in e-commerce businesses frequently depend on engineers to:
- Investigate order issues across multiple systems
- Determine refund eligibility
- Process refunds safely without risking duplicate refunds or fraud

This MCP server makes ops teams more independent by providing AI agents with safe, structured access to commerce operations.

## Solution Overview

An MCP server that exposes commerce operations tools for AI agents:

1. **Order Investigation**: Search and retrieve order details
2. **Refund Eligibility**: Check if orders qualify for refunds based on business rules
3. **Safe Refund Processing**: Execute refunds with built-in safety checks
4. **Audit Trail**: Track all refund operations

## Architecture

```
AI Agent (Claude/Gemini)
    ↓
MCP Protocol (stdio/SSE)
    ↓
TypeScript MCP Server
    ↓
SQLite Database (mock commerce data)
```

### Key Design Decisions

**MCP as Core Architecture**: The MCP server is the primary interface for all operations. It's not a wrapper - it implements:
- Business logic for refund eligibility
- Safety checks and validation
- Audit logging
- Transactional integrity

**Tool Design**: Five focused tools that map to real operations workflows:
- `search_orders` - Find orders by various criteria
- `get_order_details` - Retrieve complete order information
- `check_refund_eligibility` - Validate refund eligibility before processing
- `process_refund` - Execute refund with safety checks
- `get_refund_history` - Audit trail for refunds

**Safety First**:
- Prevents duplicate refunds
- Validates refund amounts don't exceed order total
- Enforces 90-day refund window
- Requires detailed reasons (audit trail)
- Read-only tools for investigation, single destructive tool with guards

## Setup

### Prerequisites
- Node.js 18+
- npm or yarn

### Installation

```bash
npm install
npm run build
```

### Running Locally

```bash
npm run dev
```

The server runs on stdio and communicates via MCP protocol.

### Running Tests

```bash
npm run build
node dist/test.js
```

Tests verify:
- Order search and retrieval
- Refund eligibility rules
- Refund processing safety checks
- Multiple partial refunds
- Audit logging

## MCP Tools

### 1. search_orders

Search for orders with filters:
- `email`: Customer email
- `orderId`: Specific order ID
- `status`: Order status (pending, confirmed, shipped, delivered, cancelled)
- `paymentStatus`: Payment status (pending, paid, failed, refunded, partially_refunded)

### 2. get_order_details

Retrieve complete order information including items, shipping, payment, and refund history.

**Input**: `orderId`

### 3. check_refund_eligibility

Validate if an order qualifies for refund.

**Business Rules**:
- Payment must be completed (paid status)
- Not already fully refunded
- Within 90 days of purchase
- Returns max refundable amount

**Input**: `orderId`

### 4. process_refund

Execute a refund with safety checks.

**Safety Checks**:
- Validates eligibility first
- Prevents duplicate full refunds
- Prevents excess refunds
- Requires detailed reason (min 10 characters)
- Creates audit log

**Input**: 
- `orderId`: Order to refund
- `amount`: Refund amount (supports partial refunds)
- `reason`: Detailed reason for audit trail

### 5. get_refund_history

Retrieve all refund transactions for an order.

**Input**: `orderId`

## Example Workflow

**Scenario**: Customer reports they received a damaged laptop

1. **Search for customer orders**:
   ```
   search_orders({ email: "alice@example.com" })
   ```

2. **Get order details**:
   ```
   get_order_details({ orderId: "ORD-2024-001" })
   ```

3. **Check refund eligibility**:
   ```
   check_refund_eligibility({ orderId: "ORD-2024-001" })
   ```

4. **Process refund** (if eligible):
   ```
   process_refund({ 
     orderId: "ORD-2024-001",
     amount: 1299.99,
     reason: "Customer received damaged laptop, verified with photos"
   })
   ```

5. **Verify refund**:
   ```
   get_refund_history({ orderId: "ORD-2024-001" })
   ```

## Deployment

### Railway Deployment

1. Create Railway project:
   ```bash
   railway init
   ```

2. Add start command to Procfile or use npm start

3. Deploy:
   ```bash
   railway up
   ```

4. Expose via SSE transport for remote access

### Environment Variables

For production deployment:
- `NODE_ENV=production`
- `PORT` - Railway will set automatically

## Sample Data

The system includes 6 sample orders with various states:
- Delivered paid orders (eligible for refund)
- Already refunded order (not eligible)
- Pending payment order (not eligible)
- Shipped orders
- Various payment methods

## Safety Considerations

### Implemented
- ✅ No duplicate full refunds
- ✅ Amount validation (positive, <= remaining)
- ✅ Eligibility checks before processing
- ✅ Audit logging for all refunds
- ✅ Transaction atomicity
- ✅ Required refund reasons

### Production Requirements (Out of Scope)
- Authentication/authorization
- Rate limiting
- Fraud detection
- Payment gateway integration
- Multi-currency support
- Role-based access control

## Assumptions

1. **Data**: Using synthetic SQLite data; real systems would connect to production databases via read replicas
2. **Payments**: Mock refund processing; real systems integrate with Stripe/PayPal/etc.
3. **Authentication**: Assumes trusted environment; production needs auth
4. **Single-tenant**: One database; real system would be multi-tenant
5. **Business Rules**: 90-day refund window is configurable; simplified from real-world policies

## Limitations & Future Work

### Current Limitations
- No actual payment gateway integration
- No email notifications
- No approval workflows
- Single database (no scaling)
- No fraud detection

### Next Steps (Priority Order)
1. **Add SSE transport** for remote hosting
2. **Implement authentication** using API keys or OAuth
3. **Add approval workflows** for refunds over threshold
4. **Integrate payment gateway** (Stripe API)
5. **Add notification system** (email customers)
6. **Implement rate limiting** and fraud detection
7. **Add analytics tools** (refund metrics, trends)
8. **Multi-tenant support** with organization isolation

## Trade-offs

**Why SQLite?** Fast to set up, no external dependencies, perfect for demo. Production would use PostgreSQL with read replicas.

**Why stdio transport?** Simplest MCP transport for initial development. SSE transport needed for remote hosting.

**Why synchronous processing?** Simpler to implement and test. Production would use async job queues for refunds.

**Why embedded business logic?** Keeps MCP server as single source of truth. Alternative would be separate service layer.

## Tech Stack

- **TypeScript** - Type safety and better developer experience
- **@modelcontextprotocol/sdk** - MCP protocol implementation
- **better-sqlite3** - Fast embedded database
- **zod** - Runtime type validation for tool inputs
- **Railway/Render** - Hosting platform

## License

MIT

Maintenance

ActivitySlowing
ResponsivenessNo issues