# Payload CMS MCP Server

Model Context Protocol server for Payload CMS content management operations.

## Features

### Content Management Tools
- **articles_list** - List and filter articles with pagination
- **articles_get** - Retrieve specific article by ID
- **articles_create** - Create new articles
- **articles_update** - Update existing articles
- **articles_delete** - Delete articles

### Site Management
- **sites_list** - List all sites
- **sites_get** - Get site details by ID
- **sites_create** - Create new sites

### Media Management
- **media_list** - List media files
- **media_upload** - Upload new media files
- **media_get** - Get media file details

### Search
- **search** - Full-text search across all content

### Diagnostics
- **server_info** - Connection status, health check, and troubleshooting

## Installation

### From XencoLabs Registry

```bash
npm install -g --registry=https://mcpreg.xencolabs.com @xeniac/payload-mcp
```

### From Source

```bash
cd servers/payload-mcp
npm install
npm run build
npm link
```

## Configuration

### Environment Variables

```bash
# Payload CMS API endpoint
PAYLOAD_API_URL=https://cms.xencolabs.com

# JWT authentication token
PAYLOAD_API_TOKEN=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
```

### Cursor Integration

Add to `.cursor/mcp.json`:

```json
{
  "mcpServers": {
    "payload": {
      "command": "npx",
      "args": [
        "-y",
        "--registry=https://mcpreg.xencolabs.com",
        "@xeniac/payload-mcp"
      ],
      "env": {
        "PAYLOAD_API_URL": "https://cms.xencolabs.com",
        "PAYLOAD_API_TOKEN": "your-jwt-token-here"
      }
    }
  }
}
```

### Claude Desktop Integration

Add to `claude_desktop_config.json`:

```json
{
  "mcpServers": {
    "payload": {
      "command": "npx",
      "args": ["-y", "--registry=https://mcpreg.xencolabs.com", "@xeniac/payload-mcp"],
      "env": {
        "PAYLOAD_API_URL": "https://cms.xencolabs.com",
        "PAYLOAD_API_TOKEN": "your-jwt-token-here"
      }
    }
  }
}
```

## Usage Examples

### List Articles

```typescript
// Get recent articles
const articles = await mcp_payload_articles_list({
  page: 1,
  limit: 10,
  sort: '-createdAt'
});

// Filter published articles
const published = await mcp_payload_articles_list({
  where: { status: { equals: 'published' } }
});
```

### Create Article

```typescript
const article = await mcp_payload_articles_create({
  title: 'Getting Started with Payload CMS',
  content: 'Payload is a headless CMS...',
  status: 'draft',
  author: 'author-id-here',
  category: 'category-id-here'
});
```

### Search Content

```typescript
const results = await mcp_payload_search({
  query: 'typescript tutorial',
  collections: ['articles', 'sites'],
  limit: 20
});
```

### Check Server Health

```typescript
const info = await mcp_payload_server_info();
// Returns: connection status, current user, available tools, config
```

## Troubleshooting

### Quick Diagnostics

Always start with the `server_info` tool:

```typescript
const status = await mcp_payload_server_info();
```

This shows:
- Connection status to Payload CMS
- Authentication status
- Current user info
- Response time
- Available tools
- Configuration details

### Common Issues

#### "Authentication failed"

**Cause**: Invalid or expired JWT token

**Solution**:
1. JWT tokens typically expire after 2 hours
2. Generate new token via Payload login endpoint
3. Update PAYLOAD_API_TOKEN in your .mcp.json
4. Restart MCP server (reload Cursor)

#### "Failed to initialize Payload client"

**Cause**: Missing environment variables or network issues

**Solution**:
1. Verify PAYLOAD_API_URL is set correctly
2. Verify PAYLOAD_API_TOKEN is set
3. Check network connectivity: `curl https://ultra-blog.xencolabs.com/api/users/me`
4. Run `server_info` tool for detailed diagnostics

#### Connection Timeout

**Cause**: Network issues or server overload

**Solution**:
1. Check internet connection
2. Verify Payload server is accessible
3. Try again in a few moments
4. Check Payload server logs if you have access

### Tool Usage Best Practices

✅ **DO:**
- Use MCP tool interface: `mcp_payload_articles_list(...)`
- Check `server_info` when experiencing issues
- Use pagination for large datasets (limit: 100 max)
- Refresh JWT tokens before they expire

❌ **DON'T:**
- Make direct HTTP requests to Payload API
- Use expired JWT tokens
- Request more than 100 items per page
- Skip error handling

### Agent-Specific Tips

If you're an AI agent using this MCP server:

1. **Start with `server_info`** - Verify connection before operations
2. **Handle auth errors gracefully** - Token may have expired
3. **Use pagination** - Don't fetch all content at once
4. **Search before listing** - More efficient for finding specific content
5. **Check response success** - All tools return `{success: true/false}`

## API Reference

### Articles

- `articles_list({ page?, limit?, sort?, where? })` - List articles
- `articles_get({ id })` - Get article by ID
- `articles_create({ title, content?, author?, category?, status? })` - Create article
- `articles_update({ id, ...fields })` - Update article
- `articles_delete({ id })` - Delete article

### Sites

- `sites_list({ page?, limit? })` - List sites
- `sites_get({ id })` - Get site by ID
- `sites_create({ name, domain?, settings? })` - Create site

### Media

- `media_list({ page?, limit? })` - List media files
- `media_upload({ file, alt?, caption? })` - Upload media
- `media_get({ id })` - Get media by ID

### Search

- `search({ query, collections?, limit? })` - Search content

### Diagnostics

- `server_info()` - Server health and diagnostics

## Development

```bash
# Watch mode for development
npm run watch

# Build for production
npm run build

# Test connection
npm run test

# Link for local testing
npm link
```

## Architecture

```
payload-mcp/
├── src/
│   ├── index.ts              # MCP server entry point (stdio transport)
│   ├── client.ts             # Payload API client singleton
│   ├── types/
│   │   └── config.ts         # Configuration types
│   └── tools/
│       ├── articles.ts       # Article management tools
│       ├── sites.ts          # Site management tools
│       ├── media.ts          # Media management tools
│       ├── search.ts         # Search functionality
│       └── server-info.ts    # Diagnostics
├── scripts/
│   └── test-connection.js    # Connection test script
├── package.json
├── tsconfig.json
└── README.md
```

## Security

- JWT tokens are sensitive - never commit them to git
- Tokens are passed via environment variables only
- MCP server runs locally - no network exposure
- All API calls are authenticated with provided token

## Token Management

### Getting a Token

```bash
# Login to Payload and get token
curl -X POST https://ultra-blog.xencolabs.com/api/users/login \
  -H "Content-Type: application/json" \
  -d '{"email":"admin@xenco.us","password":"your-password"}'

# Response includes: { "token": "eyJhbGci..." }
```

### Token Expiration

JWT tokens typically expire after 2 hours. When you see auth errors:

1. Generate new token via login
2. Update .mcp.json with new token
3. Reload Cursor or restart Claude Desktop

## Publishing

### To XencoLabs Registry

```bash
# Build the package
npm run build

# Publish to custom registry
npm publish --registry=https://mcpreg.xencolabs.com
```

## License

MIT - Xenco Labs

## Support

For issues or questions:
- Check `server_info` tool first for diagnostics
- Review troubleshooting section above
- Check Payload CMS API documentation
- Contact DevMaestro support team

