File size: 5,866 Bytes
8b02e7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
"""
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.
""")