@myea/wordpress-mcp-handler
Version:
Advanced WordPress MCP request handler with intelligent search, multi-locale support, and comprehensive content management capabilities
399 lines (311 loc) • 12.4 kB
Markdown
# WordPress MCP Handler
Advanced WordPress Model Context Protocol (MCP) server with intelligent search, multi-locale support, and comprehensive content management capabilities.
## Features
- **Complete WordPress REST API Integration**: Full support for posts, pages, media, users, categories, tags, and comments
- **Enhanced Search Capabilities**: Multi-strategy search with fuzzy matching and comprehensive content discovery
- **Authentication Support**: Application passwords, JWT, and basic authentication
- **Error Handling & Retry Logic**: Robust error handling with automatic retries for recoverable errors
- **TypeScript Support**: Fully typed interfaces for all WordPress operations
- **MCP Protocol Compliance**: Standard JSON-RPC interface for AI agent integration
## Quick Start
### 1. Installation
```bash
cd wordpress-mcp
npm install
```
### 2. Environment Setup
Copy the example environment file and configure your WordPress site:
```bash
cp .env.example .env
```
Edit `.env` with your WordPress site details:
```env
WP_HOST=https://your-wordpress-site.com
WP_USERNAME=admin
WP_APPLICATION_PASSWORD=xxxx-xxxx-xxxx-xxxx
```
### 3. Generate WordPress Application Password
1. Go to your WordPress admin: **Users → Profile**
2. Scroll down to **Application Passwords**
3. Add a new application password for "MCP Handler"
4. Copy the generated password to your `.env` file
### 4. Build and Run
```bash
npm run build
npm start
```
## Available MCP Methods
### Connection & Info
- `testConnection()` - Test WordPress connectivity
- `getSiteInfo()` - Get site information and settings
- `getContentStats()` - Get content statistics
### Posts Management
- `getPosts(params)` - Get posts with search/filter options
- `getPost(id)` - Get specific post
- `createPost(data)` - Create new post
- `updatePost(id, data)` - Update existing post
- `deletePost(id, force?)` - Delete post
### Pages Management
- `getPages(params)` - Get pages with search/filter options
- `getPage(id)` - Get specific page
- `createPage(data)` - Create new page
- `updatePage(id, data)` - Update existing page
- `deletePage(id, force?)` - Delete page
### Media Management
- `getMedia(params)` - Get media items
- `getMediaItem(id)` - Get specific media item
- `uploadMedia(file, metadata)` - Upload media file
### Taxonomies
- `getCategories(params)` - Get categories
- `getTags(params)` - Get tags
- `createCategory(name, description?, parent?)` - Create category
- `createTag(name, description?)` - Create tag
### Users
- `getUsers(params)` - Get users
- `getCurrentUser()` - Get current authenticated user
### Comments
- `getComments(params)` - Get comments
- `createComment(post, content, author?)` - Create comment
### Search Operations
- `searchContent(query, params?)` - Basic WordPress search
- `enhancedSearch(query, options?)` - Multi-content-type search
- `comprehensiveSearch(term, options?)` - Advanced search with fuzzy matching
### Utilities
- `getContentBySlug(slug, type?)` - Get content by slug
- `listMethods()` - List all available methods
## Usage Examples
### Creating a Blog Post
```javascript
const result = await mcpHandler.handleRequest('createPost', {
title: 'My New Blog Post',
content: 'This is the content of my blog post.',
status: 'publish',
categories: [1, 3],
tags: [5, 7],
meta: {
custom_field: 'custom_value'
}
});
```
### Searching Content
```javascript
// Basic search
const searchResult = await mcpHandler.handleRequest('searchContent', {
query: 'artificial intelligence',
per_page: 10
});
// Enhanced search across multiple content types
const enhancedResult = await mcpHandler.handleRequest('enhancedSearch', {
query: 'AI technology',
options: {
includePosts: true,
includePages: true,
includeMedia: false
}
});
// Comprehensive search with fuzzy matching
const comprehensiveResult = await mcpHandler.handleRequest('comprehensiveSearch', {
searchTerm: 'machine learning',
options: {
fuzzyMatching: true,
includeMeta: true
}
});
```
### Uploading Media
```javascript
const uploadResult = await mcpHandler.handleRequest('uploadMedia', {
file: fileBuffer,
filename: 'image.jpg',
mimeType: 'image/jpeg',
title: 'My Image',
alt_text: 'Description of the image',
caption: 'Image caption'
});
```
## Configuration
### Authentication Types
#### Application Passwords (Recommended)
```env
WP_AUTH_TYPE=application_password
WP_USERNAME=admin
WP_APPLICATION_PASSWORD=xxxx-xxxx-xxxx-xxxx
```
#### Basic Authentication
```env
WP_AUTH_TYPE=basic
WP_USERNAME=admin
WP_PASSWORD=your-password
```
#### JWT Authentication
```env
WP_AUTH_TYPE=jwt
WP_JWT_SECRET=your-secret
WP_JWT_TOKEN=your-token
```
### Content Configuration
```env
# Allowed post types
WP_ALLOWED_POST_TYPES=post,page,attachment,custom_type
# Allowed post statuses
WP_ALLOWED_STATUSES=publish,draft,private,pending
# Upload settings
WP_MAX_UPLOAD_SIZE=10485760
WP_ALLOWED_MIME_TYPES=image/jpeg,image/png,application/pdf
```
## Architecture
The WordPress MCP follows a layered architecture:
```
┌─────────────────────────────────────────────────────────────────┐
│ MCP Server │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │ STDIO MCP │ │ HTTP MCP │ │ WebSocket │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
├─────────────────────────────────────────────────────────────────┤
│ Request Handler │
│ ┌─────────────────────────────────────────────────────────────┤
│ │ • Method routing • Parameter validation │
│ │ • Error handling • Response formatting │
│ └─────────────────────────────────────────────────────────────┤
├─────────────────────────────────────────────────────────────────┤
│ WordPress Connector │
│ ┌─────────────────────────────────────────────────────────────┤
│ │ • REST API client • Authentication │
│ │ • Retry logic • Request/response handling │
│ │ └────────────────────────────────────────────────────────────┤
├─────────────────────────────────────────────────────────────────┤
│ WordPress REST API │
└─────────────────────────────────────────────────────────────────┘
```
## Error Handling
The WordPress MCP includes comprehensive error handling:
- **Connection Errors**: Automatic retry with exponential backoff
- **Authentication Errors**: Clear error messages with troubleshooting hints
- **Rate Limiting**: Automatic retry with proper delays
- **Validation Errors**: Parameter validation with detailed error messages
- **WordPress Errors**: WordPress-specific error code mapping
## Testing
```bash
# Run all tests
npm test
# Run specific test suites
npm run test:unit
npm run test:integration
# Run tests with coverage
npm run test:coverage
```
## Development
### Project Structure
```
wordpress-mcp/
├── src/
│ ├── wordpress-config.ts # Configuration management
│ ├── error-handler.ts # Error handling utilities
│ ├── wordpress-connector.ts # WordPress REST API client
│ ├── mcp-handler.ts # MCP request handler
│ ├── mcp-server.ts # Main MCP server
│ └── index.ts # Package exports
├── tests/ # Test files
├── package.json
├── tsconfig.json
└── README.md
```
### Building
```bash
npm run build
```
### Development Mode
```bash
npm run dev
```
## Docker Support
### Using Docker Compose
```yaml
version: '3.8'
services:
wordpress:
image: wordpress:latest
ports:
- "8080:80"
environment:
WORDPRESS_DB_HOST: db
WORDPRESS_DB_USER: wordpress
WORDPRESS_DB_PASSWORD: wordpress
WORDPRESS_DB_NAME: wordpress
wordpress-mcp:
build: .
ports:
- "3000:3000"
environment:
WP_HOST: http://wordpress:80
WP_USERNAME: admin
WP_APPLICATION_PASSWORD: your-app-password
depends_on:
- wordpress
db:
image: mysql:8.0
environment:
MYSQL_DATABASE: wordpress
MYSQL_USER: wordpress
MYSQL_PASSWORD: wordpress
MYSQL_ROOT_PASSWORD: rootpassword
```
## Integration with AI Agents
### Claude Desktop
Add to your Claude Desktop configuration:
```json
{
"mcpServers": {
"wordpress": {
"command": "node",
"args": ["/path/to/wordpress-mcp/build/mcp-server.js"],
"env": {
"WP_HOST": "https://your-wordpress-site.com",
"WP_USERNAME": "admin",
"WP_APPLICATION_PASSWORD": "xxxx-xxxx-xxxx-xxxx"
}
}
}
}
```
### Custom Integration
```javascript
import { WordPressConnector, WordPressMCPRequestHandler } from '@myea/wordpress-mcp-handler';
const connector = new WordPressConnector();
const handler = new WordPressMCPRequestHandler(connector);
// Use the handler in your application
const result = await handler.handleRequest('getPosts', { per_page: 5 });
```
## Security Considerations
- **Use Application Passwords**: More secure than basic authentication
- **HTTPS Only**: Always use HTTPS for production
- **Rate Limiting**: Built-in rate limiting and retry logic
- **Input Validation**: All inputs are validated and sanitized
- **Error Sanitization**: Sensitive information is not exposed in errors
## Troubleshooting
### Connection Issues
1. **Check WordPress REST API**: Visit `https://your-site.com/wp-json/` to verify the API is accessible
2. **Verify Credentials**: Ensure your username and application password are correct
3. **Check Permissions**: Make sure your user has appropriate permissions for the operations you're trying to perform
### Authentication Issues
1. **Application Passwords**: Ensure application passwords are enabled on your WordPress site
2. **User Permissions**: Verify the user has the necessary capabilities
3. **Plugin Conflicts**: Some security plugins may block REST API access
### Common Error Codes
- `CONNECTION_FAILED`: Cannot connect to WordPress - check host and network
- `AUTHENTICATION_FAILED`: Invalid credentials - check username/password
- `INSUFFICIENT_PERMISSIONS`: User lacks required permissions
- `POST_NOT_FOUND`: Requested content doesn't exist
- `RATE_LIMITED`: Too many requests - automatic retry will occur
## Contributing
1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests for new functionality
5. Submit a pull request
## License
MIT License. See LICENSE file for details.
## Support
For issues and questions:
- GitHub Issues: [Report bugs and request features](https://github.com/venky7799/wordpress-mcp-handler/issues)
- Documentation: [View full documentation](https://github.com/venky7799/wordpress-mcp-handler#readme)