# Shopify MCP Server

Model Context Protocol (MCP) server for Shopify Admin API integration.

## Features

- **Full Shopify Admin API Coverage**: Products, Orders, Customers, Inventory, Collections, and more
- **GraphQL Support**: Execute GraphQL Admin API queries
- **Automatic Rate Limiting**: Intelligent retry with exponential backoff
- **Type-Safe**: Comprehensive TypeScript types for all Shopify entities
- **Cursor-Based Pagination**: Automatic handling of paginated responses
- **MCP Resources**: UI-friendly resource endpoints for apps
- **Dual Transport**: Stdio (default) or HTTP/SSE modes

## Installation

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

## Configuration

### Environment Variables

| Variable | Required | Description | Example |
|----------|----------|-------------|---------|
| `SHOPIFY_ACCESS_TOKEN` | ✅ | Admin API access token | `shpat_xxxxxxxxxxxxx` |
| `SHOPIFY_STORE` | ✅ | Store name (without .myshopify.com) | `my-store` |
| `SHOPIFY_API_VERSION` | ❌ | API version (default: 2024-01) | `2024-01` |
| `DEBUG` | ❌ | Enable debug logging | `true` |

### Getting Your Access Token

1. Go to your Shopify admin: `https://your-store.myshopify.com/admin`
2. Navigate to **Settings** → **Apps and sales channels** → **Develop apps**
3. Click **Create an app** or select an existing one
4. Go to **API credentials** tab
5. Click **Install app** (if not already installed)
6. Copy the **Admin API access token** (starts with `shpat_`)

### Required API Scopes

Grant the following scopes to your app (based on features needed):

- `read_products`, `write_products` - Product management
- `read_orders`, `write_orders` - Order management
- `read_customers`, `write_customers` - Customer management
- `read_inventory`, `write_inventory` - Inventory tracking
- `read_content`, `write_content` - Pages, blogs, themes
- `read_discounts`, `write_discounts` - Price rules and discount codes
- `read_shipping`, `write_shipping` - Shipping zones and carriers
- `read_analytics` - Analytics and reports

## Usage

### Stdio Mode (Default)

```bash
# Copy example env file
cp .env.example .env

# Edit .env with your credentials
# SHOPIFY_ACCESS_TOKEN=shpat_xxxxxxxxxxxxx
# SHOPIFY_STORE=your-store-name

# Start the server
npm start

# Or in development mode with auto-reload
npm run dev
```

### HTTP Mode

```bash
# Start with HTTP transport
npm start -- --http --port=3000

# Health check
curl http://localhost:3000/health
```

## Available Tools

The server provides the following tool categories (lazy-loaded on demand):

### Products
- Create, read, update, delete products
- Manage variants and images
- Bulk operations

### Orders
- List and search orders
- Update order status
- Create refunds
- Manage fulfillments

### Customers
- Customer CRUD operations
- Customer search
- Manage addresses

### Inventory
- Track inventory levels
- Manage locations
- Adjust stock quantities

### Collections
- Smart and custom collections
- Add/remove products from collections

### Discounts
- Create price rules
- Generate discount codes
- Manage promotions

### Fulfillments
- Create fulfillments
- Update tracking information
- Cancel fulfillments

### Shipping
- Shipping zones
- Carrier services
- Delivery profiles

### Themes
- Theme management
- Asset upload/download

### Content
- Pages
- Blogs and articles
- Redirects

### Webhooks
- Register webhooks
- Manage subscriptions

### Analytics
- Sales reports
- Product analytics
- Customer insights

## MCP Resources

Resources are available for UI applications:

- `shopify://products` - List all products
- `shopify://orders` - List all orders
- `shopify://customers` - List all customers
- `shopify://inventory` - View inventory levels

## API Client Features

### Rate Limiting

The client automatically handles Shopify's rate limits:

- Parses `X-Shopify-Shop-Api-Call-Limit` header
- Warns when approaching limit (80%+ used)
- Automatic retry with exponential backoff (1s, 2s, 4s)

### Pagination

```typescript
// Get single page
const { data, pageInfo } = await client.list('/products.json');

// Get all pages (with safety limit)
const allProducts = await client.listAll('/products.json', {}, 10);
```

### GraphQL

```typescript
const result = await client.graphql(`
  query {
    products(first: 10) {
      edges {
        node {
          id
          title
          handle
        }
      }
    }
  }
`);
```

## Error Handling

All errors are normalized with structured responses:

```json
{
  "error": "RATE_LIMIT_EXCEEDED",
  "message": "Shopify API rate limit exceeded. Please retry after a delay."
}
```

Error codes:
- `TOOL_NOT_FOUND` - Requested tool doesn't exist
- `RESOURCE_READ_ERROR` - Failed to read resource
- `AUTHENTICATION_ERROR` - Invalid access token
- `RATE_LIMIT_EXCEEDED` - Too many requests
- `UNKNOWN_ERROR` - Unexpected error

## Development

```bash
# Install dependencies
npm install

# Run TypeScript compiler in watch mode
npx tsc --watch

# Run development server with auto-reload
npm run dev

# Type check only (no build)
npx tsc --noEmit

# Build for production
npm run build
```

## Architecture

```
src/
├── main.ts              # Entry point, env validation, transports
├── server.ts            # MCP server setup, handlers
├── clients/
│   └── shopify.ts       # Shopify API client (REST + GraphQL)
├── types/
│   └── index.ts         # TypeScript interfaces for Shopify entities
├── tools/               # Tool modules (created separately)
│   ├── products.ts
│   ├── orders.ts
│   ├── customers.ts
│   └── ...
└── apps/                # UI applications (created separately)
```

## Troubleshooting

### "Authentication failed"
- Verify `SHOPIFY_ACCESS_TOKEN` is correct
- Ensure the app is installed on your store
- Check that the token hasn't been revoked

### "Resource not found"
- Check that `SHOPIFY_STORE` is correct (without `.myshopify.com`)
- Verify the resource ID exists in your store

### "Rate limit exceeded"
- The client will automatically retry with backoff
- Consider implementing request batching for bulk operations
- Monitor rate limit info with `client.getRateLimitInfo()`

### TypeScript errors
- Run `npm install` to ensure all dependencies are installed
- Check that `@types/node` version matches your Node.js version
- Verify `tsconfig.json` settings

## License

MIT

## Support

For issues and questions:
- GitHub Issues: [mcpengine repository](https://github.com/BusyBee3333/mcpengine)
- Shopify API Docs: https://shopify.dev/docs/api/admin-rest
