# Payload MCP Server - Admin Guide

## ✅ STATUS: READY FOR DEPLOYMENT

**Created:** 2025-10-30  
**Location:** `/home/xen/docker/apps/blogcraft-mcp/servers/payload-mcp`  
**Status:** Built, tested, and ready to publish  
**Test Results:** All connection tests passed ✅

---

## Quick Summary

**What Was Created:**
- Full-featured MCP server for Payload CMS API
- 13 tools for content management (articles, sites, media, search)
- Server diagnostics tool for troubleshooting
- Comprehensive README with examples
- Connection test script
- Proper stdio transport (doesn't timeout)
- Error handling with helpful messages

**What Was Tested:**
```
✅ MCP stdio protocol: Responds correctly, stays alive
✅ Payload CMS connection: https://cms.xencolabs.com
✅ Authentication: JWT token validated successfully
✅ All 3 test endpoints: Passed (health, articles, sites)
✅ Tools registration: 13 tools properly exposed
```

---

## Publishing to Registry

### Step 1: Set NPM Auth Token

```bash
export NPM_TOKEN="your-xencolabs-registry-token"
```

### Step 2: Publish

```bash
cd /home/xen/docker/apps/blogcraft-mcp/servers/payload-mcp
npm publish --registry=https://mcpreg.xencolabs.com
```

**Expected Output:**
```
Published @xeniac/payload-mcp@1.0.0 to https://mcpreg.xencolabs.com
```

---

## Installation for Users

Once published, users can install via:

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

Or use directly in their `.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": "user-jwt-token-here"
      }
    }
  }
}
```

---

## Available Tools

### Content Management
1. **articles_list** - List articles with filtering/pagination
2. **articles_get** - Get article by ID
3. **articles_create** - Create new article
4. **articles_update** - Update existing article
5. **articles_delete** - Delete article

### Site Management
6. **sites_list** - List all sites
7. **sites_get** - Get site by ID
8. **sites_create** - Create new site

### Media Management
9. **media_list** - List media files
10. **media_upload** - Upload media
11. **media_get** - Get media details

### Search & Utilities
12. **search** - Full-text search across content
13. **server_info** - Diagnostics and health check

---

## Configuration

### Required Environment Variables

| Variable | Description | Example |
|---|---|---|
| `PAYLOAD_API_URL` | Payload CMS API endpoint | `https://cms.xencolabs.com` |
| `PAYLOAD_API_TOKEN` | JWT authentication token | `eyJhbGci...` |

### Optional Settings

- **Timeout:** 30 seconds (configurable in code)
- **Max Retries:** 2 (configurable in code)

---

## JWT Token Management

### Getting Tokens

Users can get JWT tokens by logging into Payload:

```bash
curl -X POST https://cms.xencolabs.com/api/users/login \
  -H "Content-Type: application/json" \
  -d '{"email":"user@example.com","password":"password"}'
```

**Response includes:** `{ "token": "eyJhbGci...", "user": {...} }`

### Token Expiration

- **Default:** 2 hours
- **Users must refresh** when they see auth errors
- **Server provides clear error** messages explaining how to refresh

---

## Testing & Validation

### Test Script

```bash
cd servers/payload-mcp
PAYLOAD_API_TOKEN="jwt-token-here" npm run test
```

**Output:**
```
✅ PASS      Health Check         (1354ms)
✅ PASS      Articles List        (1556ms)
✅ PASS      Sites List           (1531ms)
```

### Manual MCP Test

```bash
echo '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | \
PAYLOAD_API_URL="https://cms.xencolabs.com" \
PAYLOAD_API_TOKEN="token-here" \
node dist/index.js
```

**Expected:** JSON response with all 13 tools listed

---

## Architecture & Best Practices Implemented

### ✅ What Makes This MCP Server Robust

1. **Stdio Protocol** - Proper MCP standard, no HTTP timeouts
2. **Signal Handling** - Graceful shutdown on SIGINT/SIGTERM
3. **Keep-Alive** - Process stays running, doesn't terminate
4. **Error Handling** - Clear messages with troubleshooting guidance
5. **Type Safety** - Full TypeScript with proper types
6. **Singleton Client** - Single Payload API instance (performance)
7. **Dynamic Imports** - Flexible module loading
8. **Validation** - Required params checked before API calls
9. **Diagnostics** - server_info tool for self-troubleshooting
10. **Documentation** - Comprehensive README with examples

### Lessons from Previous MCP Servers

**From dm-mini:**
- ✅ Added server_info diagnostic tool
- ✅ Enhanced error messages with solutions
- ✅ Proper stdio transport configuration
- ✅ Package.json bin entry point
- ✅ Troubleshooting section in README

**Improvements Made:**
- ✅ Better error messages (401, 404, timeout all handled)
- ✅ Connection test script for developers
- ✅ Clear environment variable requirements
- ✅ Proper signal handling for graceful shutdown
- ✅ Type-safe dynamic imports

---

## Troubleshooting

### If Publish Fails

**Error:** `Unable to authenticate, your authentication token seems to be invalid`

**Fix:**
```bash
# Set your registry auth token
export NPM_TOKEN="your-token-here"

# Or login to registry
npm login --registry=https://mcpreg.xencolabs.com
```

### If Users Can't Connect

1. **Have them run server_info tool** first
2. **Check error message** - they're descriptive
3. **Verify environment variables** in .mcp.json
4. **Test token validity** with test script

### Common User Issues

| Issue | Cause | Fix |
|---|---|---|
| Auth failed | Expired JWT | Refresh token via login |
| Connection timeout | Network/firewall | Check connectivity to cms.xencolabs.com |
| Module not found | Not installed | Run npx with registry flag |
| Tool not working | Wrong params | Check tool schema in server_info |

---

## Maintenance

### Updating the Server

1. **Make changes** to src files
2. **Rebuild:** `npm run build`
3. **Test:** `npm run test`
4. **Bump version** in package.json
5. **Publish:** `npm publish --registry=https://mcpreg.xencolabs.com`

### Adding New Tools

1. **Create tool file** in `src/tools/`
2. **Import in index.ts**
3. **Add to tools array** (schema)
4. **Add to switch statement** (handler)
5. **Add to server_info** tools_available list
6. **Rebuild and test**

---

## Files Created

```
servers/payload-mcp/
├── package.json              # Package configuration
├── tsconfig.json             # TypeScript config
├── .npmrc                    # Registry configuration
├── README.md                 # User documentation
├── ADMIN_GUIDE.md           # This file
├── src/
│   ├── index.ts              # MCP server entry (stdio)
│   ├── client.ts             # Payload API client singleton
│   ├── types/
│   │   └── config.ts         # Configuration types
│   └── tools/
│       ├── articles.ts       # Article CRUD operations
│       ├── sites.ts          # Site management
│       ├── media.ts          # Media upload/management
│       ├── search.ts         # Content search
│       └── server-info.ts    # Diagnostics
├── scripts/
│   └── test-connection.js    # Connection test script
└── dist/                     # Compiled JavaScript (built)
```

---

## Next Steps

1. ✅ **Code:** Complete and tested
2. ⏳ **Publish:** Run `npm publish` with auth token
3. ⏳ **Announce:** Let users know it's available
4. ⏳ **Monitor:** Watch for user issues/feedback
5. ⏳ **Iterate:** Add more tools as needed (authors, categories, etc.)

---

## Support & Maintenance

**Developer:** Cluster Maestro Orchestrator  
**Date Created:** 2025-10-30  
**Test Token Used:** admin@xenco.us (expires ~2 hours from issue)  
**Payload CMS URL:** https://cms.xencolabs.com  
**Registry:** https://mcpreg.xencolabs.com  

**Questions or Issues:**
- Check server_info tool output first
- Review README troubleshooting section
- Test connection script: `npm run test`
- Verify JWT token hasn't expired

---

## Production Checklist

Before announcing to users:

- [ ] Publish to registry successfully
- [ ] Test install from registry: `npx -y --registry=https://mcpreg.xencolabs.com @xeniac/payload-mcp`
- [ ] Verify stdio mode works in Cursor
- [ ] Test with fresh JWT token
- [ ] Verify all 13 tools work
- [ ] Check server_info returns useful data
- [ ] Update any documentation/blogs about available MCP servers

**Ready to go!** Just needs npm publish with proper auth. 🚀

