Initial commit: MCP Hub Community Edition v3.0.0
Community edition generated from private repo via sync pipeline. Includes 9 plugins (WordPress, WooCommerce, WP Advanced, Gitea, n8n, Supabase, OpenPanel, Appwrite, Directus) with ~587 tools. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
23
examples/.env.example
Normal file
23
examples/.env.example
Normal file
@@ -0,0 +1,23 @@
|
||||
# Example Environment Configuration
|
||||
# Copy this file to .env and fill in your credentials
|
||||
|
||||
# Primary WordPress Site
|
||||
WORDPRESS_SITE1_URL=https://example.com
|
||||
WORDPRESS_SITE1_USERNAME=admin
|
||||
WORDPRESS_SITE1_APP_PASSWORD=xxxx xxxx xxxx xxxx xxxx xxxx
|
||||
WORDPRESS_SITE1_WC_CONSUMER_KEY=ck_xxxxxxxxxxxxxxxxxxxx
|
||||
WORDPRESS_SITE1_WC_CONSUMER_SECRET=cs_xxxxxxxxxxxxxxxxxxxx
|
||||
WORDPRESS_SITE1_ALIAS=mainsite
|
||||
|
||||
# Secondary WordPress Site (Optional)
|
||||
WORDPRESS_SITE2_URL=https://shop.example.com
|
||||
WORDPRESS_SITE2_USERNAME=admin
|
||||
WORDPRESS_SITE2_APP_PASSWORD=yyyy yyyy yyyy yyyy yyyy yyyy
|
||||
WORDPRESS_SITE2_WC_CONSUMER_KEY=ck_yyyyyyyyyyyyyyyyyyyy
|
||||
WORDPRESS_SITE2_WC_CONSUMER_SECRET=cs_yyyyyyyyyyyyyyyyyyyy
|
||||
WORDPRESS_SITE2_ALIAS=shop
|
||||
|
||||
# Rate Limiting
|
||||
RATE_LIMIT_PER_MINUTE=60
|
||||
RATE_LIMIT_PER_HOUR=1000
|
||||
RATE_LIMIT_PER_DAY=10000
|
||||
145
examples/README.md
Normal file
145
examples/README.md
Normal file
@@ -0,0 +1,145 @@
|
||||
# 📚 Examples
|
||||
|
||||
This directory contains practical examples demonstrating how to use MCP Hub tools.
|
||||
|
||||
## 📂 Files
|
||||
|
||||
- **[basic_usage.py](basic_usage.py)** - Basic WordPress operations
|
||||
- **[bulk_operations.py](bulk_operations.py)** - Batch processing and bulk updates
|
||||
- **[woocommerce_shop.py](woocommerce_shop.py)** - E-commerce management examples
|
||||
- **[content_migration.py](content_migration.py)** - Migrating content between sites
|
||||
- **[.env.example](.env.example)** - Configuration template for examples
|
||||
|
||||
## 🚀 Quick Start
|
||||
|
||||
### 1. Setup Environment
|
||||
|
||||
```bash
|
||||
# Copy environment template
|
||||
cp examples/.env.example examples/.env
|
||||
|
||||
# Edit with your WordPress credentials
|
||||
nano examples/.env
|
||||
```
|
||||
|
||||
### 2. Run Examples
|
||||
|
||||
```bash
|
||||
# Activate virtual environment
|
||||
source venv/bin/activate # Linux/Mac
|
||||
.\venv\Scripts\Activate.ps1 # Windows
|
||||
|
||||
# Run an example
|
||||
python examples/basic_usage.py
|
||||
```
|
||||
|
||||
## 📖 Example Descriptions
|
||||
|
||||
### Basic Usage
|
||||
|
||||
Demonstrates fundamental operations:
|
||||
- Listing posts
|
||||
- Creating posts
|
||||
- Updating posts
|
||||
- Deleting posts
|
||||
- Working with media
|
||||
- Managing categories
|
||||
|
||||
**Use Case**: Learning the basics, quick operations
|
||||
|
||||
### Bulk Operations
|
||||
|
||||
Shows how to handle large-scale tasks:
|
||||
- Bulk post creation
|
||||
- Batch updates
|
||||
- Mass deletion
|
||||
- Progress tracking
|
||||
- Error handling
|
||||
|
||||
**Use Case**: Content migrations, mass updates, cleanup
|
||||
|
||||
### WooCommerce Shop
|
||||
|
||||
E-commerce management examples:
|
||||
- Product CRUD operations
|
||||
- Inventory management
|
||||
- Order processing
|
||||
- Customer management
|
||||
- Sales reports
|
||||
|
||||
**Use Case**: Online store management, inventory sync
|
||||
|
||||
### Content Migration
|
||||
|
||||
Cross-site content transfer:
|
||||
- Migrating posts between sites
|
||||
- Copying pages
|
||||
- Media migration
|
||||
- Taxonomy mapping
|
||||
- URL rewriting
|
||||
|
||||
**Use Case**: Site consolidation, content backup, multi-site sync
|
||||
|
||||
## 🔧 Prerequisites
|
||||
|
||||
1. **Configured WordPress sites** in `.env`
|
||||
2. **Valid credentials** (Application Passwords)
|
||||
3. **WooCommerce** installed (for e-commerce examples)
|
||||
4. **Sufficient permissions** on WordPress sites
|
||||
|
||||
## 💡 Tips
|
||||
|
||||
### Error Handling
|
||||
|
||||
All examples include comprehensive error handling:
|
||||
|
||||
```python
|
||||
try:
|
||||
result = wordpress_create_post(...)
|
||||
print(f"Success: {result}")
|
||||
except Exception as e:
|
||||
print(f"Error: {e}")
|
||||
# Log error, retry, or handle appropriately
|
||||
```
|
||||
|
||||
### Rate Limiting
|
||||
|
||||
Examples respect rate limits:
|
||||
|
||||
```python
|
||||
import time
|
||||
|
||||
for item in items:
|
||||
process(item)
|
||||
time.sleep(0.1) # Avoid hitting rate limits
|
||||
```
|
||||
|
||||
### Progress Tracking
|
||||
|
||||
For long-running operations:
|
||||
|
||||
```python
|
||||
from tqdm import tqdm
|
||||
|
||||
for post in tqdm(posts, desc="Processing posts"):
|
||||
update_post(post)
|
||||
```
|
||||
|
||||
## 🧪 Testing Examples
|
||||
|
||||
Before running on production:
|
||||
|
||||
1. **Test on staging site first**
|
||||
2. **Backup your WordPress site**
|
||||
3. **Start with small batches**
|
||||
4. **Verify results manually**
|
||||
|
||||
## 📞 Support
|
||||
|
||||
If you encounter issues with examples:
|
||||
|
||||
- Check [Troubleshooting Guide](../docs/troubleshooting.md)
|
||||
- Review [Getting Started](../docs/getting-started.md)
|
||||
- Contact: hello@mcphub.dev
|
||||
|
||||
---
|
||||
293
examples/basic_usage.py
Normal file
293
examples/basic_usage.py
Normal file
@@ -0,0 +1,293 @@
|
||||
"""
|
||||
Basic Usage Examples for MCP Hub
|
||||
|
||||
This example demonstrates fundamental WordPress operations using MCP tools.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from datetime import datetime
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables
|
||||
load_dotenv()
|
||||
|
||||
# Example 1: List Posts
|
||||
async def list_posts_example():
|
||||
"""List published posts from a WordPress site."""
|
||||
print("\n" + "=" * 50)
|
||||
print("Example 1: List Posts")
|
||||
print("=" * 50)
|
||||
|
||||
try:
|
||||
# Using unified tools (recommended)
|
||||
from src.main import app
|
||||
|
||||
# List first 5 published posts
|
||||
result = await app.call_tool(
|
||||
"wordpress_list_posts",
|
||||
arguments={"site": "mainsite", "per_page": 5, "status": "publish"}, # Use site alias
|
||||
)
|
||||
|
||||
posts = json.loads(result)
|
||||
print(f"\nFound {len(posts)} posts:")
|
||||
for post in posts:
|
||||
print(f" - [{post['id']}] {post['title']['rendered']}")
|
||||
print(f" Status: {post['status']}, Date: {post['date']}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error: {e}")
|
||||
|
||||
# Example 2: Create a Post
|
||||
async def create_post_example():
|
||||
"""Create a new WordPress post."""
|
||||
print("\n" + "=" * 50)
|
||||
print("Example 2: Create Post")
|
||||
print("=" * 50)
|
||||
|
||||
try:
|
||||
from src.main import app
|
||||
|
||||
# Create a new post
|
||||
result = await app.call_tool(
|
||||
"wordpress_create_post",
|
||||
arguments={
|
||||
"site": "mainsite",
|
||||
"title": f"Test Post - {datetime.now().strftime('%Y-%m-%d %H:%M')}",
|
||||
"content": "<p>This is a test post created via MCP tools.</p>",
|
||||
"status": "draft", # Start as draft
|
||||
"excerpt": "A test post demonstrating MCP tool usage",
|
||||
"categories": [1], # Uncategorized
|
||||
"tags": [],
|
||||
"featured_media": None,
|
||||
"slug": None,
|
||||
},
|
||||
)
|
||||
|
||||
post = json.loads(result)
|
||||
print("\nPost created successfully!")
|
||||
print(f" ID: {post['id']}")
|
||||
print(f" Title: {post['title']['rendered']}")
|
||||
print(f" Status: {post['status']}")
|
||||
print(f" Edit URL: {post['link']}")
|
||||
|
||||
return post["id"] # Return for next examples
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error: {e}")
|
||||
return None
|
||||
|
||||
# Example 3: Update a Post
|
||||
async def update_post_example(post_id):
|
||||
"""Update an existing WordPress post."""
|
||||
print("\n" + "=" * 50)
|
||||
print("Example 3: Update Post")
|
||||
print("=" * 50)
|
||||
|
||||
if not post_id:
|
||||
print("No post ID provided. Skipping.")
|
||||
return
|
||||
|
||||
try:
|
||||
from src.main import app
|
||||
|
||||
# Update the post
|
||||
result = await app.call_tool(
|
||||
"wordpress_update_post",
|
||||
arguments={
|
||||
"site": "mainsite",
|
||||
"post_id": post_id,
|
||||
"title": f"Updated Test Post - {datetime.now().strftime('%H:%M')}",
|
||||
"content": "<p>This post has been updated!</p><p>Updated via MCP tools.</p>",
|
||||
"status": "publish", # Publish the post
|
||||
"slug": None,
|
||||
"excerpt": None,
|
||||
"categories": None,
|
||||
"tags": None,
|
||||
"featured_media": None,
|
||||
},
|
||||
)
|
||||
|
||||
post = json.loads(result)
|
||||
print("\nPost updated successfully!")
|
||||
print(f" ID: {post['id']}")
|
||||
print(f" New Title: {post['title']['rendered']}")
|
||||
print(f" Status: {post['status']}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error: {e}")
|
||||
|
||||
# Example 4: List Categories
|
||||
async def list_categories_example():
|
||||
"""List WordPress categories."""
|
||||
print("\n" + "=" * 50)
|
||||
print("Example 4: List Categories")
|
||||
print("=" * 50)
|
||||
|
||||
try:
|
||||
from src.main import app
|
||||
|
||||
result = await app.call_tool(
|
||||
"wordpress_list_categories",
|
||||
arguments={"site": "mainsite", "per_page": 10, "page": 1, "hide_empty": False},
|
||||
)
|
||||
|
||||
categories = json.loads(result)
|
||||
print(f"\nFound {len(categories)} categories:")
|
||||
for cat in categories:
|
||||
print(f" - [{cat['id']}] {cat['name']} ({cat['count']} posts)")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error: {e}")
|
||||
|
||||
# Example 5: Upload Media
|
||||
async def upload_media_example():
|
||||
"""Upload media from URL to WordPress."""
|
||||
print("\n" + "=" * 50)
|
||||
print("Example 5: Upload Media from URL")
|
||||
print("=" * 50)
|
||||
|
||||
try:
|
||||
from src.main import app
|
||||
|
||||
# Upload an image from URL
|
||||
image_url = "https://via.placeholder.com/800x600.png?text=MCP+Test+Image"
|
||||
|
||||
result = await app.call_tool(
|
||||
"wordpress_upload_media_from_url",
|
||||
arguments={
|
||||
"site": "mainsite",
|
||||
"url": image_url,
|
||||
"title": "MCP Test Image",
|
||||
"alt_text": "Test image uploaded via MCP",
|
||||
"caption": "Uploaded using MCP Hub",
|
||||
},
|
||||
)
|
||||
|
||||
media = json.loads(result)
|
||||
print("\nMedia uploaded successfully!")
|
||||
print(f" ID: {media['id']}")
|
||||
print(f" Title: {media['title']['rendered']}")
|
||||
print(f" URL: {media['source_url']}")
|
||||
print(f" Size: {media['media_details'].get('filesize', 'unknown')} bytes")
|
||||
|
||||
return media["id"]
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error: {e}")
|
||||
return None
|
||||
|
||||
# Example 6: Get Site Health
|
||||
async def site_health_example():
|
||||
"""Check WordPress site health."""
|
||||
print("\n" + "=" * 50)
|
||||
print("Example 6: Site Health Check")
|
||||
print("=" * 50)
|
||||
|
||||
try:
|
||||
from src.main import app
|
||||
|
||||
result = await app.call_tool("wordpress_get_site_health", arguments={"site": "mainsite"})
|
||||
|
||||
health = json.loads(result)
|
||||
print("\nSite Health:")
|
||||
print(f" Status: {health.get('status', 'unknown')}")
|
||||
print(f" WordPress: {health.get('wordpress_version', 'unknown')}")
|
||||
print(f" PHP: {health.get('php_version', 'unknown')}")
|
||||
print(f" Accessible: {health.get('accessible', 'unknown')}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error: {e}")
|
||||
|
||||
# Example 7: Get System Metrics
|
||||
async def system_metrics_example():
|
||||
"""Check MCP server health and metrics."""
|
||||
print("\n" + "=" * 50)
|
||||
print("Example 7: System Metrics")
|
||||
print("=" * 50)
|
||||
|
||||
try:
|
||||
from src.main import app
|
||||
|
||||
result = await app.call_tool("get_system_metrics", arguments={})
|
||||
|
||||
metrics = json.loads(result)
|
||||
print("\nSystem Metrics:")
|
||||
print(f" Uptime: {metrics['uptime_seconds']:.2f} seconds")
|
||||
print(f" Total Requests: {metrics['total_requests']}")
|
||||
print(
|
||||
f" Success Rate: {(metrics['successful_requests']/metrics['total_requests']*100):.1f}%"
|
||||
)
|
||||
print(f" Avg Response Time: {metrics['average_response_time_ms']:.2f}ms")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error: {e}")
|
||||
|
||||
# Example 8: Delete Post
|
||||
async def delete_post_example(post_id):
|
||||
"""Delete a WordPress post."""
|
||||
print("\n" + "=" * 50)
|
||||
print("Example 8: Delete Post")
|
||||
print("=" * 50)
|
||||
|
||||
if not post_id:
|
||||
print("No post ID provided. Skipping.")
|
||||
return
|
||||
|
||||
try:
|
||||
from src.main import app
|
||||
|
||||
# Move to trash (not permanent delete)
|
||||
result = await app.call_tool(
|
||||
"wordpress_delete_post",
|
||||
arguments={
|
||||
"site": "mainsite",
|
||||
"post_id": post_id,
|
||||
"force": False, # Move to trash, not permanent delete
|
||||
},
|
||||
)
|
||||
|
||||
post = json.loads(result)
|
||||
print("\nPost moved to trash!")
|
||||
print(f" ID: {post['id']}")
|
||||
print(f" Title: {post['title']['rendered']}")
|
||||
print(f" Status: {post['status']}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error: {e}")
|
||||
|
||||
# Main execution
|
||||
async def main():
|
||||
"""Run all examples in sequence."""
|
||||
print("\n" + "=" * 60)
|
||||
print("MCP Hub - Basic Usage Examples")
|
||||
print("=" * 60)
|
||||
|
||||
# Run examples
|
||||
await list_posts_example()
|
||||
post_id = await create_post_example()
|
||||
await asyncio.sleep(1) # Small delay between operations
|
||||
|
||||
if post_id:
|
||||
await update_post_example(post_id)
|
||||
await asyncio.sleep(1)
|
||||
|
||||
await list_categories_example()
|
||||
await upload_media_example()
|
||||
await site_health_example()
|
||||
await system_metrics_example()
|
||||
|
||||
# Cleanup: Delete the test post
|
||||
if post_id:
|
||||
print("\n" + "=" * 50)
|
||||
print("Cleanup: Removing test post")
|
||||
print("=" * 50)
|
||||
await delete_post_example(post_id)
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("Examples completed successfully!")
|
||||
print("=" * 60 + "\n")
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
Reference in New Issue
Block a user