claude_code_usage.py•5.87 kB
"""
Example: How Claude Code should use the Delegation MCP Server
This demonstrates the CORRECT MCP code execution pattern:
✅ Claude Code writes code that imports and uses the MCP server
❌ NOT a chat UI that directly calls MCP tools
When you ask Claude Code to delegate a task, it should write code similar to this.
"""
import asyncio
from pathlib import Path
from delegation_mcp.server import DelegationMCPServer
from delegation_mcp.config import DelegationConfig
async def example_delegation():
"""Example: Claude Code delegating a security audit to Gemini."""
print("🚀 Initializing Delegation MCP Server...")
# Initialize the server (Claude Code does this)
server = DelegationMCPServer(
config_path=Path("config/delegation_rules.yaml"),
enable_security=True,
enable_persistence=True,
)
print("✅ Server initialized\n")
# Example 1: Delegate security audit to Gemini
print("📝 Example 1: Security Audit")
print("Query: 'Audit auth.py for SQL injection vulnerabilities'")
print("Expected: Routes to Gemini (best for security analysis)\n")
# This is what Claude Code would do when you ask it to delegate:
result = await server.engine.process(
"Audit the authentication code for SQL injection vulnerabilities"
)
print(f"Orchestrator: {result.orchestrator}")
print(f"Delegated to: {result.delegated_to}")
print(f"Success: {result.success}")
print(f"Duration: {result.duration:.2f}s")
print(f"Output preview: {result.output[:200]}...\n")
print("-" * 60 + "\n")
# Example 2: Delegate refactoring to Claude
print("📝 Example 2: Code Refactoring")
print("Query: 'Refactor database connection to use connection pooling'")
print("Expected: Routes to Claude (best for architecture)\n")
result = await server.engine.process(
"Refactor the database connection code to use connection pooling"
)
print(f"Orchestrator: {result.orchestrator}")
print(f"Delegated to: {result.delegated_to}")
print(f"Success: {result.success}")
print(f"Duration: {result.duration:.2f}s")
print(f"Output preview: {result.output[:200]}...\n")
print("-" * 60 + "\n")
# Example 3: Check agent statistics
print("📊 Example 3: Get Delegation Statistics")
if server.persistence:
stats = server.persistence.get_statistics()
print(f"Total tasks: {stats.get('total_tasks', 0)}")
print(f"Success rate: {stats.get('success_rate', 0):.1%}")
print(f"Average duration: {stats.get('avg_duration', 0):.2f}s")
print(f"Agent usage: {stats.get('agent_usage', {})}\n")
print("✅ Examples complete!")
print("\n" + "=" * 60)
print("💡 Key Insight:")
print("=" * 60)
print("""
This is the CORRECT MCP pattern:
- Claude Code writes and runs this Python code
- The code imports and uses the delegation MCP server
- Tasks are routed to specialized agents automatically
- Results come back through the code
This is WRONG:
- A Gradio chat UI that directly calls MCP tools
- That violates the code execution pattern
- The UI should only monitor activity, not execute it
""")
async def example_mcp_protocol_usage():
"""
Example: How an MCP client (like Claude Code) uses the server via MCP protocol.
Note: This is pseudocode showing what happens under the hood when Claude Code
uses the MCP server through the stdio protocol.
"""
print("\n" + "=" * 60)
print("📡 MCP Protocol Usage (Pseudocode)")
print("=" * 60 + "\n")
print("""
When Claude Code is configured to use this MCP server:
1. Configuration (~/.config/claude/mcp.json):
{
"mcpServers": {
"delegation": {
"command": "delegation-mcp"
}
}
}
2. User asks Claude Code: "Audit my code for security issues"
3. Claude Code recognizes it should use the delegation server
4. Claude Code calls the MCP tool via stdio:
{
"jsonrpc": "2.0",
"method": "tools/call",
"params": {
"name": "delegate_task",
"arguments": {
"query": "Audit auth.py for SQL injection",
"orchestrator": "claude"
}
}
}
5. Delegation MCP server receives the call, routes to Gemini
6. Response comes back:
{
"orchestrator": "claude",
"delegated_to": "gemini",
"success": true,
"output": "Found 3 SQL injection vulnerabilities...",
"duration": 2.5
}
7. Claude Code presents the result to the user
✅ User works with Claude Code, but gets Gemini's security expertise!
""")
if __name__ == "__main__":
print("""
╔═══════════════════════════════════════════════════════════════╗
║ Delegation MCP Server - Correct Usage Pattern Examples ║
║ ║
║ This demonstrates how Claude Code (or other MCP clients) ║
║ should use the delegation server following Anthropic's ║
║ code execution pattern. ║
╚═══════════════════════════════════════════════════════════════╝
""")
# Run async examples
asyncio.run(example_delegation())
# Show MCP protocol usage
asyncio.run(example_mcp_protocol_usage())
print("\n" + "=" * 60)
print("🎯 Ready for Production!")
print("=" * 60)
print("""
To use in production:
1. Install: pip install -e .
2. Configure Claude Code to use delegation-mcp
3. Chat with Claude Code naturally
4. Watch tasks get routed to the best agent!
Optional: Run `delegation-monitor` to visualize activity for demos.
""")