npm package: @headless-commerce/mcp-server
Description: MCP server for Headless Commerce — enables AI agents to manage stores
Latest version: 0.1.4

# @headless-commerce/mcp-server

MCP (Model Context Protocol) server for [Headless Commerce](https://github.com/your-org/headless-commerce) — enables AI agents (Claude, ChatGPT, etc.) to manage your e-commerce store.

## How It Works

```
┌─────────────┐    stdio (JSON-RPC)    ┌──────────────────┐    HTTP (REST)    ┌─────────────────┐
│  AI Agent   │ ◄────────────────────► │  MCP Server      │ ───────────────► │  Headless       │
│  (Claude,   │                        │  this package     │                  │  Commerce API   │
│   Cursor)   │                        │                   │                  │                 │
└─────────────┘                        └──────────────────┘                  └─────────────────┘
       │                                       │                                     │
  User asks:                            Uses SDK internally               PostgreSQL + Redis
  "Show me today's orders"       (@headless-commerce/sdk)                  stores all data
```

1. AI agent starts the MCP server as a child process (via stdio)
2. User asks a question like "Show me today's orders"
3. AI selects the appropriate tool (`list_orders`) and calls it
4. MCP server uses `@headless-commerce/sdk` to make an HTTP request to the API
5. API authenticates the `sk_` key, queries the database, and returns JSON
6. MCP server passes the result back to the AI agent
7. AI formats the response for the user

The MCP server is **stateless** — it holds no data and acts purely as a bridge between AI agents and the Headless Commerce API.

## Installation

```bash
npm install -g @headless-commerce/mcp-server
# or
npx @headless-commerce/mcp-server
```

## Getting Your API Key

1. Log in to the Headless Commerce Dashboard
2. Go to **Settings > API Keys**
3. Click **Create API Key** and select type **Secret** (`sk_` prefix)
4. Copy the generated key — it is only shown once

> MCP server requires a **Secret Key** (`sk_`). Publishable keys (`pk_`) are for storefront use only and will be rejected by admin endpoints.

## Configuration

### Environment Variables

| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `HEADLESS_COMMERCE_API_KEY` | Yes | — | Admin API key (`sk_` prefix) |
| `HEADLESS_COMMERCE_API_URL` | No | `https://api.headlesscommerce.io/v1` | API base URL (override for local dev) |

### Claude Desktop

Add to `~/Library/Application Support/Claude/claude_desktop_config.json`:

```json
{
  "mcpServers": {
    "headless-commerce": {
      "command": "npx",
      "args": ["-y", "@headless-commerce/mcp-server"],
      "env": {
        "HEADLESS_COMMERCE_API_KEY": "sk_live_your_api_key"
      }
    }
  }
}
```

### Claude Code

Add to `.claude/settings.json`:

```json
{
  "mcpServers": {
    "headless-commerce": {
      "command": "npx",
      "args": ["-y", "@headless-commerce/mcp-server"],
      "env": {
        "HEADLESS_COMMERCE_API_KEY": "sk_live_your_api_key"
      }
    }
  }
}
```

### Cursor

Add to `.cursor/mcp.json`:

```json
{
  "mcpServers": {
    "headless-commerce": {
      "command": "npx",
      "args": ["-y", "@headless-commerce/mcp-server"],
      "env": {
        "HEADLESS_COMMERCE_API_KEY": "sk_live_your_api_key"
      }
    }
  }
}
```

### Local Development

For local development, override the API URL:

```json
{
  "env": {
    "HEADLESS_COMMERCE_API_KEY": "sk_test_your_api_key",
    "HEADLESS_COMMERCE_API_URL": "http://localhost:3000/v1"
  }
}
```

## Available Tools

### Products

| Tool | Description |
|------|-------------|
| `list_products` | List products with search, filtering, and pagination |
| `get_product` | Get a product by ID with variants, images, and options |
| `create_product` | Create a new product |
| `update_product` | Update product name, description, status, tags |

### Variants

| Tool | Description |
|------|-------------|
| `create_variant` | Create a variant with price (in smallest currency unit) |

### Orders

| Tool | Description |
|------|-------------|
| `list_orders` | List orders with status/payment/fulfillment filters |
| `get_order` | Get order details with lines, payments, fulfillments |
| `confirm_order` | Confirm a pending order |
| `cancel_order` | Cancel an order with optional reason |

### Customers

| Tool | Description |
|------|-------------|
| `list_customers` | List customers with search by name or email |
| `get_customer` | Get a customer by ID |

### Inventory

| Tool | Description |
|------|-------------|
| `list_inventory` | List inventory levels for all variants |
| `adjust_inventory` | Adjust stock quantity (+/-) with reason |

### Discounts

| Tool | Description |
|------|-------------|
| `list_discounts` | List all discount codes/promotions |
| `create_discount` | Create a discount (fixed, percentage, or free shipping) |

### Store

| Tool | Description |
|------|-------------|
| `get_store` | Get store settings and configuration |
| `update_store` | Update store name, currency, metadata |

### Dashboard

| Tool | Description |
|------|-------------|
| `get_dashboard_stats` | Get revenue, orders, customers, and recent activity |

## Resources

| Resource | URI | Description |
|----------|-----|-------------|
| API Reference | `openapi://spec` | Embedded API reference — all endpoints, auth patterns, pagination, error codes. AI agents read this automatically to understand the full API. |

## Example Prompts

Once configured, you can ask your AI agent:

- "Show me all orders from today"
- "Create a new product called 'Wireless Headphones' at $49.99"
- "What's the current inventory for our best-selling items?"
- "Cancel order ord_abc123 — customer requested refund"
- "Give me a dashboard summary of the last 30 days"
- "List all active discount codes"

## Architecture

### Internal Structure

```
packages/mcp-server/
├── src/
│   └── index.ts          # Single-file server (all tools + resource)
├── dist/
│   ├── index.js           # Built ESM bundle (runs as CLI)
│   └── index.d.ts         # TypeScript declarations
├── tsup.config.ts         # Build config (ESM, Node 20, shebang)
├── package.json
└── README.md
```

### Dependencies

| Package | Role |
|---------|------|
| `@headless-commerce/sdk` | TypeScript SDK — handles HTTP, auth, retries, types |
| `@modelcontextprotocol/sdk` | Official MCP SDK — server framework, stdio transport |
| `zod` | Input validation schemas for each tool |

### How Tools Are Registered

Each tool follows a consistent pattern:

```typescript
server.registerTool(
  'tool_name',                          // Tool ID (AI agent calls this)
  {
    description: 'What this tool does', // AI reads this to decide when to use it
    inputSchema: z.object({ ... }),     // Zod schema → validated input
  },
  async (params) => run(() => sdk.resource.method(params)),
);
```

The `run()` wrapper handles errors uniformly — any SDK exception is caught and returned as an MCP error response instead of crashing the server.

### Adding a New Tool

1. Add the SDK method to `@headless-commerce/sdk` if it doesn't exist
2. Add a `server.registerTool()` block in `src/index.ts`
3. Run `pnpm build` and test with your AI agent

## Troubleshooting

### "HEADLESS_COMMERCE_API_KEY environment variable is required"

The server exits immediately if no API key is provided. Ensure the `env` block in your MCP config has the key set.

### "Invalid API key" or "Secret key required for Admin API"

- Verify the key starts with `sk_` (not `pk_`)
- Check that the key is still active in Dashboard > Settings > API Keys
- Ensure the key hasn't expired

### Tools return empty results

- Confirm the API server is running and accessible at the configured URL
- For local dev, make sure `HEADLESS_COMMERCE_API_URL` is set to `http://localhost:3000/v1`
- Check that your store has data (products, orders, etc.)

### Server doesn't appear in Claude Desktop

- Restart Claude Desktop after editing the config file
- Verify the JSON is valid (no trailing commas, correct nesting)
- Check `~/Library/Logs/Claude/mcp*.log` for error messages

## Requirements

- Node.js 18+
- Headless Commerce API running with a valid `sk_` admin key

## License

MIT