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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
# API Reference

Complete API reference for the MCP Orchestration Platform.

## Core Classes

### MCPOrchestrator

The main orchestration engine that manages MCP servers, connections, and tool execution.

```python
from orchestration_platform.mcp_orchestrator import MCPOrchestrator
```

#### Constructor

```python
MCPOrchestrator(
    config: Optional[Dict[str, Any]] = None,
    secrets_manager: Optional[SecretsManager] = None,
    debug: bool = False
)
```

**Parameters:**
- `config`: Optional configuration dictionary
- `secrets_manager`: Optional secrets manager instance
- `debug`: Enable debug mode for verbose logging

#### Methods

##### async initialize()
Initialize the orchestrator with configuration and setup internal components.

```python
await orchestrator.initialize()
```

**Returns:** `None`

**Raises:**
- `ConfigurationError`: If configuration is invalid
- `InitializationError`: If initialization fails

##### async add_server(name: str, url: str, config: Optional[Dict] = None) -> bool
Register a new MCP server with the orchestrator.

```python
success = await orchestrator.add_server(
    "weather-server", 
    "http://localhost:8001/mcp",
    {"timeout": 30}
)
```

**Parameters:**
- `name`: Unique server identifier
- `url`: MCP server endpoint URL
- `config`: Optional server-specific configuration

**Returns:** `bool` - True if registration successful

**Raises:**
- `ServerRegistrationError`: If server registration fails
- `DuplicateServerError`: If server name already exists

##### async remove_server(name: str) -> bool
Remove a registered server from the orchestrator.

```python
success = await orchestrator.remove_server("weather-server")
```

**Parameters:**
- `name`: Server identifier to remove

**Returns:** `bool` - True if removal successful

##### async call_tool(server: str, tool: str, arguments: Dict[str, Any]) -> Dict[str, Any]
Execute a tool on a registered MCP server.

```python
result = await orchestrator.call_tool(
    "weather-server",
    "get_current_weather",
    {"location": "New York"}
)
```

**Parameters:**
- `server`: Server identifier
- `tool`: Tool name to execute
- `arguments`: Tool arguments as dictionary

**Returns:** `Dict[str, Any]` - Tool execution result

**Raises:**
- `ServerNotFoundError`: If server doesn't exist
- `ToolNotFoundError`: If tool doesn't exist
- `ToolExecutionError`: If tool execution fails
- `CircuitBreakerError`: If circuit breaker is open

##### async list_all_tools() -> Dict[str, List[Dict[str, Any]]]
Get catalog of all available tools across registered servers.

```python
tools = await orchestrator.list_all_tools()
# Returns: {"weather-server": [...], "crm-server": [...]}
```

**Returns:** `Dict[str, List[Dict[str, Any]]]` - Tool catalog by server

##### async get_server_status(server: str) -> Dict[str, Any]
Get status information for a registered server.

```python
status = await orchestrator.get_server_status("weather-server")
```

**Parameters:**
- `server`: Server identifier

**Returns:** `Dict[str, Any]` - Server status information

##### async health_check() -> Dict[str, Any]
Perform comprehensive health check of the orchestrator.

```python
health = await orchestrator.health_check()
```

**Returns:** `Dict[str, Any]` - Health status information

##### async cleanup()
Clean up resources and close connections.

```python
await orchestrator.cleanup()
```

### SecretsManager

Enterprise-grade secrets management with multiple backend support.

```python
from orchestration_platform.secrets_manager import SecretsManager
```

#### Constructor

```python
SecretsManager(
    backend: str = "local",
    config: Optional[Dict[str, Any]] = None
)
```

**Parameters:**
- `backend`: Backend type ("local", "vault", "aws", "environment")
- `config`: Backend-specific configuration

#### Methods

##### async initialize()
Initialize the secrets manager with specified backend.

```python
secrets = SecretsManager(backend="local")
await secrets.initialize()
```

**Raises:**
- `SecretsBackendError`: If backend initialization fails
- `ConfigurationError`: If configuration is invalid

##### async get_secret(key: str) -> str
Retrieve a secret value.

```python
api_key = await secrets.get_secret("WEATHER_API_KEY")
```

**Parameters:**
- `key`: Secret key identifier

**Returns:** `str` - Secret value

**Raises:**
- `SecretNotFoundError`: If secret doesn't exist
- `AccessDeniedError`: If access is denied

##### async set_secret(key: str, value: str) -> bool
Store a secret value.

```python
await secrets.set_secret("DATABASE_PASSWORD", "secure_password")
```

**Parameters:**
- `key`: Secret key identifier
- `value`: Secret value to store

**Returns:** `bool` - True if storage successful

##### async delete_secret(key: str) -> bool
Delete a secret value.

```python
await secrets.delete_secret("OLD_API_KEY")
```

**Parameters:**
- `key`: Secret key identifier

**Returns:** `bool` - True if deletion successful

##### async list_secrets(pattern: Optional[str] = None) -> List[str]
List available secret keys.

```python
keys = await secrets.list_secrets(pattern="api_*")
```

**Parameters:**
- `pattern`: Optional glob pattern to filter keys

**Returns:** `List[str]` - List of secret key names

##### async rotate_secret(key: str) -> bool
Rotate a secret value.

```python
await secrets.rotate_secret("JWT_SECRET")
```

**Parameters:**
- `key`: Secret key identifier

**Returns:** `bool` - True if rotation successful

### SessionManager

Secure session management for user isolation and rate limiting.

```python
from orchestration_platform.mcp_orchestrator import SessionManager
```

#### Constructor

```python
SessionManager(
    orchestrator: MCPOrchestrator,
    session_ttl: int = 3600,
    max_sessions: int = 1000
)
```

**Parameters:**
- `orchestrator`: Parent orchestrator instance
- `session_ttl`: Session time-to-live in seconds
- `max_sessions`: Maximum concurrent sessions

#### Methods

##### async create_session(user_id: str, permissions: List[str] = None) -> str
Create a new user session.

```python
session_id = await session_manager.create_session(
    "user123",
    permissions=["read", "execute"]
)
```

**Parameters:**
- `user_id`: Unique user identifier
- `permissions`: List of user permissions

**Returns:** `str` - Session identifier

##### async get_session(session_id: str) -> Optional[Dict[str, Any]]
Retrieve session information.

```python
session = await session_manager.get_session(session_id)
```

**Parameters:**
- `session_id`: Session identifier

**Returns:** `Optional[Dict[str, Any]]` - Session information

##### async revoke_session(session_id: str) -> bool
Revoke an active session.

```python
await session_manager.revoke_session(session_id)
```

**Parameters:**
- `session_id`: Session identifier

**Returns:** `bool` - True if revocation successful

### ConnectionPool

Advanced connection management with circuit breaker patterns.

```python
from orchestration_platform.mcp_orchestrator import ConnectionPool
```

#### Constructor

```python
ConnectionPool(
    server_url: str,
    max_connections: int = 10,
    min_connections: int = 2,
    connection_timeout: int = 30,
    health_check_interval: int = 30
)
```

**Parameters:**
- `server_url`: MCP server endpoint URL
- `max_connections`: Maximum pool size
- `min_connections`: Minimum pool size
- `connection_timeout`: Connection timeout in seconds
- `health_check_interval`: Health check interval in seconds

#### Methods

##### async acquire() -> Connection
Acquire a connection from the pool.

```python
connection = await pool.acquire()
try:
    result = await connection.execute_request(request)
finally:
    await pool.release(connection)
```

**Returns:** `Connection` - Managed connection instance

##### async release(connection: Connection)
Release a connection back to the pool.

```python
await pool.release(connection)
```

**Parameters:**
- `connection`: Connection to release

##### async health_check() -> Dict[str, Any]
Get connection pool health status.

```python
health = await pool.health_check()
```

**Returns:** `Dict[str, Any]` - Pool health information

### ToolManager

Dynamic tool discovery and introspection system.

```python
from orchestration_platform.mcp_orchestrator import ToolManager
```

#### Constructor

```python
ToolManager(orchestrator: MCPOrchestrator)
```

**Parameters:**
- `orchestrator`: Parent orchestrator instance

#### Methods

##### async discover_tools(server_name: str) -> List[Dict[str, Any]]
Discover available tools for a server.

```python
tools = await tool_manager.discover_tools("weather-server")
```

**Parameters:**
- `server_name`: Server identifier

**Returns:** `List[Dict[str, Any]]` - Discovered tools

##### async validate_tool_call(server: str, tool: str, arguments: Dict[str, Any]) -> bool
Validate tool call arguments against schema.

```python
valid = await tool_manager.validate_tool_call(
    "weather-server",
    "get_current_weather",
    {"location": "New York"}
)
```

**Parameters:**
- `server`: Server identifier
- `tool`: Tool name
- `arguments`: Arguments to validate

**Returns:** `bool` - True if validation passes

##### async get_tool_schema(server: str, tool: str) -> Optional[Dict[str, Any]]
Get tool input/output schema.

```python
schema = await tool_manager.get_tool_schema("weather-server", "get_current_weather")
```

**Parameters:**
- `server`: Server identifier
- `tool`: Tool name

**Returns:** `Optional[Dict[str, Any]]` - Tool schema

### MultiLayerCache

High-performance caching with multiple storage layers.

```python
from orchestration_platform.mcp_orchestrator import MultiLayerCache
```

#### Constructor

```python
MultiLayerCache(
    layers: List[CacheLayer],
    default_ttl: int = 3600,
    max_size: int = 10000
)
```

**Parameters:**
- `layers`: List of cache layer configurations
- `default_ttl`: Default time-to-live in seconds
- `max_size`: Maximum cache size

#### Methods

##### async get(key: str) -> Optional[Any]
Get value from cache.

```python
value = await cache.get("weather:new_york")
```

**Parameters:**
- `key`: Cache key

**Returns:** `Optional[Any]` - Cached value

##### async set(key: str, value: Any, ttl: Optional[int] = None) -> bool
Set value in cache.

```python
await cache.set("weather:new_york", weather_data, ttl=1800)
```

**Parameters:**
- `key`: Cache key
- `value`: Value to cache
- `ttl`: Optional time-to-live in seconds

**Returns:** `bool` - True if caching successful

##### async delete(key: str) -> bool
Delete value from cache.

```python
await cache.delete("weather:new_york")
```

**Parameters:**
- `key`: Cache key

**Returns:** `bool` - True if deletion successful

##### async clear() -> bool
Clear all cached values.

```python
await cache.clear()
```

**Returns:** `bool` - True if clear successful

## Event System

### Event Types

```python
from orchestration_platform.mcp_orchestrator import EventType

# Available event types
EventType.SERVER_CONNECTED
EventType.SERVER_DISCONNECTED
EventType.TOOL_CALLED
EventType.TOOL_COMPLETED
EventType.TOOL_FAILED
EventType.CIRCUIT_BREAKER_TRIPPED
EventType.CACHE_HIT
EventType.CACHE_MISS
EventType.SESSION_CREATED
EventType.SESSION_EXPIRED
```

### Event Handlers

```python
from orchestration_platform.mcp_orchestrator import EventHandler

async def handle_tool_event(event):
    print(f"Tool called: {event.tool} on {event.server}")

handler = EventHandler(handle_tool_event)
orchestrator.add_event_handler(EventType.TOOL_CALLED, handler)
```

## Data Models

### ServerStatus

```python
@dataclass
class ServerStatus:
    name: str
    url: str
    status: str  # "healthy", "degraded", "unhealthy"
    last_health_check: str
    connection_count: int
    error_rate: float
    average_response_time: float
```

### ToolInfo

```python
@dataclass
class ToolInfo:
    name: str
    description: str
    input_schema: Dict[str, Any]
    output_schema: Optional[Dict[str, Any]]
    examples: List[Dict[str, Any]]
    tags: List[str]
    server_name: str
```

### SessionInfo

```python
@dataclass
class SessionInfo:
    session_id: str
    user_id: str
    created_at: str
    expires_at: str
    permissions: List[str]
    last_activity: str
    request_count: int
```

## Error Classes

### OrchestratorError

Base exception for all orchestrator errors.

```python
class OrchestratorError(Exception):
    def __init__(self, message: str, details: Optional[Dict] = None):
        self.message = message
        self.details = details or {}
        super().__init__(self.message)
```

### ConfigurationError

Raised when configuration is invalid.

```python
class ConfigurationError(OrchestratorError):
    pass
```

### ServerRegistrationError

Raised when server registration fails.

```python
class ServerRegistrationError(OrchestratorError):
    pass
```

### ToolExecutionError

Raised when tool execution fails.

```python
class ToolExecutionError(OrchestratorError):
    def __init__(self, message: str, server: str, tool: str, details: Optional[Dict] = None):
        super().__init__(message, details)
        self.server = server
        self.tool = tool
```

### CircuitBreakerError

Raised when circuit breaker is open.

```python
class CircuitBreakerError(OrchestratorError):
    def __init__(self, message: str, server: str):
        super().__init__(message)
        self.server = server
```

## Configuration Options

### Orchestrator Configuration

```python
config = {
    "orchestrator": {
        "host": "localhost",
        "port": 7860,
        "max_connections": 100,
        "connection_timeout": 30,
        "request_timeout": 60,
        "max_retries": 3,
        "retry_delay": 1.0,
        "circuit_breaker": {
            "failure_threshold": 5,
            "recovery_timeout": 60,
            "half_open_max_calls": 3
        }
    },
    "cache": {
        "layers": [
            {"type": "memory", "max_size": 1000},
            {"type": "redis", "url": "redis://localhost:6379"}
        ],
        "default_ttl": 3600,
        "enable_compression": True
    },
    "session": {
        "ttl": 3600,
        "max_sessions": 1000,
        "cleanup_interval": 300
    },
    "monitoring": {
        "prometheus": {
            "enabled": True,
            "port": 9090
        },
        "logging": {
            "level": "INFO",
            "format": "json",
            "file": "/var/log/orchestrator.log"
        }
    }
}
```

## Usage Examples

### Basic Server Registration

```python
import asyncio
from orchestration_platform.mcp_orchestrator import MCPOrchestrator

async def main():
    orchestrator = MCPOrchestrator()
    await orchestrator.initialize()
    
    # Register servers
    await orchestrator.add_server("weather", "http://localhost:8001/mcp")
    await orchestrator.add_server("crm", "http://localhost:8002/mcp")
    
    # Call tools
    result = await orchestrator.call_tool("weather", "get_current_weather", {
        "location": "New York"
    })
    
    print(result)
    
    await orchestrator.cleanup()

asyncio.run(main())
```

### With Secrets Management

```python
import asyncio
from orchestration_platform.mcp_orchestrator import MCPOrchestrator, SecretsManager

async def main():
    # Setup secrets manager
    secrets = SecretsManager(backend="local")
    await secrets.initialize()
    await secrets.set_secret("WEATHER_API_KEY", "your-api-key")
    
    # Setup orchestrator with secrets
    orchestrator = MCPOrchestrator(secrets_manager=secrets)
    await orchestrator.initialize()
    
    # Use secret in server config
    await orchestrator.add_server("weather", "http://localhost:8001/mcp", {
        "auth": {
            "type": "api_key",
            "key": await secrets.get_secret("WEATHER_API_KEY")
        }
    })
    
    await orchestrator.cleanup()

asyncio.run(main())
```

### With Session Management

```python
import asyncio
from orchestration_platform.mcp_orchestrator import MCPOrchestrator, SessionManager

async def main():
    orchestrator = MCPOrchestrator()
    await orchestrator.initialize()
    
    session_manager = SessionManager(orchestrator)
    
    # Create session
    session_id = await session_manager.create_session("user123", ["read", "execute"])
    
    # Use session for tool calls
    result = await orchestrator.call_tool("weather", "get_current_weather", {
        "location": "New York"
    })
    
    await orchestrator.cleanup()

asyncio.run(main())
```

### Event Handling

```python
import asyncio
from orchestration_platform.mcp_orchestrator import MCPOrchestrator, EventType, EventHandler

async def handle_events(event):
    if event.type == EventType.TOOL_CALLED:
        print(f"Tool called: {event.tool} on {event.server}")
    elif event.type == EventType.CIRCUIT_BREAKER_TRIPPED:
        print(f"Circuit breaker tripped: {event.server}")

async def main():
    orchestrator = MCPOrchestrator()
    await orchestrator.initialize()
    
    # Add event handler
    handler = EventHandler(handle_events)
    orchestrator.add_event_handler(EventType.TOOL_CALLED, handler)
    orchestrator.add_event_handler(EventType.CIRCUIT_BREAKER_TRIPPED, handler)
    
    await orchestrator.cleanup()

asyncio.run(main())