agent-mcp-gateway 0.1.5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of agent-mcp-gateway might be problematic. Click here for more details.

src/main.py ADDED
@@ -0,0 +1,556 @@
1
+ """Main entry point for Agent MCP Gateway."""
2
+
3
+ import argparse
4
+ import asyncio
5
+ import logging
6
+ import logging.handlers
7
+ import os
8
+ import sys
9
+ import threading
10
+ from datetime import datetime
11
+ from typing import Optional
12
+ from .gateway import gateway, initialize_gateway
13
+ from .config import load_mcp_config, load_gateway_rules, get_mcp_config_path, get_gateway_rules_path, validate_rules_against_servers, reload_configs
14
+ from .policy import PolicyEngine
15
+ from .audit import AuditLogger
16
+ from .proxy import ProxyManager
17
+ from .metrics import MetricsCollector
18
+ from .middleware import AgentAccessControl
19
+ from .config_watcher import ConfigWatcher
20
+
21
+ # Configure logging
22
+ logging.basicConfig(
23
+ level=logging.INFO,
24
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
25
+ stream=sys.stderr
26
+ )
27
+
28
+ # Add file-based debug logging for MCP Inspector scenarios
29
+ # (Inspector captures stdout/stderr, so we need a separate log file)
30
+ debug_log_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'gateway-debug.log')
31
+ debug_handler = logging.FileHandler(debug_log_path, mode='w') # Overwrite on each start
32
+ debug_handler.setLevel(logging.DEBUG)
33
+ debug_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
34
+ debug_handler.setFormatter(debug_formatter)
35
+
36
+ # Add to root logger
37
+ root_logger = logging.getLogger()
38
+ root_logger.addHandler(debug_handler)
39
+ root_logger.setLevel(logging.DEBUG)
40
+
41
+ logger = logging.getLogger(__name__)
42
+ logger.debug(f"Debug logging initialized - writing to: {debug_log_path}")
43
+
44
+ # Module-level storage for components (needed by reload callbacks)
45
+ _mcp_config_path: str = ""
46
+ _gateway_rules_path: str = ""
47
+ _policy_engine: PolicyEngine | None = None
48
+ _proxy_manager: ProxyManager | None = None
49
+ _config_watcher: ConfigWatcher | None = None
50
+
51
+ # Track last modification times for fallback reload checking
52
+ _last_mcp_config_mtime: float = 0.0
53
+ _last_gateway_rules_mtime: float = 0.0
54
+
55
+ # Hot reload status tracking
56
+ _reload_status_lock = threading.Lock()
57
+ _mcp_config_reload_status = {
58
+ "last_attempt": None, # datetime
59
+ "last_success": None, # datetime
60
+ "last_error": None, # str or None
61
+ "attempt_count": 0,
62
+ "success_count": 0,
63
+ }
64
+ _gateway_rules_reload_status = {
65
+ "last_attempt": None, # datetime
66
+ "last_success": None, # datetime
67
+ "last_error": None, # str or None
68
+ "attempt_count": 0,
69
+ "success_count": 0,
70
+ "last_warnings": [], # list[str]
71
+ }
72
+
73
+
74
+ def check_config_changes() -> None:
75
+ """Check if config files have changed and trigger reload if needed.
76
+
77
+ This is a fallback mechanism in case file watching doesn't work (e.g., when
78
+ running through MCP Inspector). It checks file modification times and triggers
79
+ reload callbacks if files have changed since last check.
80
+ """
81
+ global _last_mcp_config_mtime, _last_gateway_rules_mtime
82
+
83
+ try:
84
+ # Check MCP config
85
+ if os.path.exists(_mcp_config_path):
86
+ current_mtime = os.path.getmtime(_mcp_config_path)
87
+ if _last_mcp_config_mtime > 0 and current_mtime > _last_mcp_config_mtime:
88
+ logger.debug(f"Detected MCP config change via mtime check: {current_mtime} > {_last_mcp_config_mtime}")
89
+ on_mcp_config_changed(_mcp_config_path)
90
+ _last_mcp_config_mtime = current_mtime
91
+
92
+ # Check gateway rules
93
+ if os.path.exists(_gateway_rules_path):
94
+ current_mtime = os.path.getmtime(_gateway_rules_path)
95
+ if _last_gateway_rules_mtime > 0 and current_mtime > _last_gateway_rules_mtime:
96
+ logger.debug(f"Detected gateway rules change via mtime check: {current_mtime} > {_last_gateway_rules_mtime}")
97
+ on_gateway_rules_changed(_gateway_rules_path)
98
+ _last_gateway_rules_mtime = current_mtime
99
+ except Exception as e:
100
+ logger.debug(f"Error checking config changes: {e}")
101
+
102
+
103
+ def on_mcp_config_changed(config_path: str) -> None:
104
+ """Handle MCP server configuration file changes.
105
+
106
+ This callback is invoked by ConfigWatcher when .mcp.json changes.
107
+ It reloads and validates both configs (since they cross-reference each other),
108
+ then reloads the ProxyManager if validation succeeds.
109
+
110
+ Args:
111
+ config_path: Absolute path to the changed MCP config file
112
+ """
113
+ import time
114
+
115
+ # Record reload attempt
116
+ with _reload_status_lock:
117
+ _mcp_config_reload_status["last_attempt"] = datetime.now()
118
+ _mcp_config_reload_status["attempt_count"] += 1
119
+
120
+ logger.debug(f"!!! CALLBACK TRIGGERED !!! on_mcp_config_changed called")
121
+ logger.debug(f" - config_path: {config_path}")
122
+ logger.debug(f" - current time: {time.time()}")
123
+ logger.debug(f" - thread: {threading.current_thread().name}")
124
+
125
+ logger.info(f"MCP server configuration file changed: {config_path}")
126
+ # Also print to stderr so user definitely sees it
127
+ print(f"\n[HOT RELOAD] Detected change in MCP server config file: {config_path}", file=sys.stderr)
128
+ print(f"[HOT RELOAD] Timestamp: {datetime.now().isoformat()}", file=sys.stderr)
129
+ print(f"[HOT RELOAD] Reloading and validating new configuration...", file=sys.stderr)
130
+
131
+ try:
132
+ # Get the proxy_manager and gateway_rules_path from module globals
133
+ if not _proxy_manager or not _gateway_rules_path:
134
+ error_msg = "Cannot reload: components not initialized"
135
+ logger.error(error_msg)
136
+ with _reload_status_lock:
137
+ _mcp_config_reload_status["last_error"] = error_msg
138
+ return
139
+
140
+ # Load and validate both configs (reload_configs validates cross-references)
141
+ mcp_config, gateway_rules, error = reload_configs(
142
+ config_path,
143
+ _gateway_rules_path
144
+ )
145
+
146
+ if error:
147
+ logger.error(f"Failed to reload MCP server configuration: {error}")
148
+ logger.info("Keeping existing MCP server configuration")
149
+ with _reload_status_lock:
150
+ _mcp_config_reload_status["last_error"] = error
151
+ return
152
+
153
+ logger.info("MCP server configuration validated successfully")
154
+
155
+ # Reload ProxyManager (async operation - need to handle from sync callback)
156
+ # Since this callback runs in a watchdog thread and the gateway uses anyio,
157
+ # we create a new asyncio event loop to run the async reload operation
158
+ try:
159
+ # Create a new event loop for this thread
160
+ reload_loop = asyncio.new_event_loop()
161
+ asyncio.set_event_loop(reload_loop)
162
+
163
+ try:
164
+ # Run the async reload in this loop
165
+ success, reload_error = reload_loop.run_until_complete(
166
+ _proxy_manager.reload(mcp_config)
167
+ )
168
+
169
+ if success:
170
+ logger.info("ProxyManager reloaded successfully")
171
+ print(f"[HOT RELOAD] MCP server configuration reloaded successfully", file=sys.stderr)
172
+ print(f"[HOT RELOAD] Proxy connections updated", file=sys.stderr)
173
+
174
+ # Record success
175
+ with _reload_status_lock:
176
+ _mcp_config_reload_status["last_success"] = datetime.now()
177
+ _mcp_config_reload_status["last_error"] = None
178
+ _mcp_config_reload_status["success_count"] += 1
179
+ else:
180
+ logger.error(f"ProxyManager reload failed: {reload_error}")
181
+ logger.info("Keeping existing proxy connections")
182
+ print(f"[HOT RELOAD] ERROR: Failed to reload proxy manager: {reload_error}", file=sys.stderr)
183
+
184
+ # Record error
185
+ with _reload_status_lock:
186
+ _mcp_config_reload_status["last_error"] = f"ProxyManager reload failed: {reload_error}"
187
+ finally:
188
+ # Clean up the event loop
189
+ reload_loop.close()
190
+ except Exception as e:
191
+ error_msg = f"Error running ProxyManager reload: {e}"
192
+ logger.error(error_msg)
193
+ with _reload_status_lock:
194
+ _mcp_config_reload_status["last_error"] = error_msg
195
+
196
+ except Exception as e:
197
+ error_msg = f"Unexpected error reloading MCP server configuration: {e}"
198
+ logger.error(error_msg, exc_info=True)
199
+ logger.info("Keeping existing MCP server configuration")
200
+ with _reload_status_lock:
201
+ _mcp_config_reload_status["last_error"] = error_msg
202
+
203
+
204
+ def on_gateway_rules_changed(rules_path: str) -> None:
205
+ """Handle gateway rules configuration file changes.
206
+
207
+ This callback is invoked by ConfigWatcher when .mcp-gateway-rules.json changes.
208
+ It reloads and validates both configs (since they cross-reference each other),
209
+ then reloads the PolicyEngine if validation succeeds.
210
+
211
+ Args:
212
+ rules_path: Absolute path to the changed gateway rules file
213
+ """
214
+ import time
215
+
216
+ # Record reload attempt
217
+ with _reload_status_lock:
218
+ _gateway_rules_reload_status["last_attempt"] = datetime.now()
219
+ _gateway_rules_reload_status["attempt_count"] += 1
220
+
221
+ logger.debug(f"!!! CALLBACK TRIGGERED !!! on_gateway_rules_changed called")
222
+ logger.debug(f" - rules_path: {rules_path}")
223
+ logger.debug(f" - current time: {time.time()}")
224
+ logger.debug(f" - thread: {threading.current_thread().name}")
225
+
226
+ logger.info(f"Gateway rules configuration file changed: {rules_path}")
227
+ # Also print to stderr so user definitely sees it
228
+ print(f"\n[HOT RELOAD] Detected change in gateway rules file: {rules_path}", file=sys.stderr)
229
+ print(f"[HOT RELOAD] Timestamp: {datetime.now().isoformat()}", file=sys.stderr)
230
+ print(f"[HOT RELOAD] Reloading and validating new rules...", file=sys.stderr)
231
+
232
+ try:
233
+ # Get the policy_engine and mcp_config_path from module globals
234
+ if not _policy_engine or not _mcp_config_path:
235
+ error_msg = "Cannot reload: components not initialized"
236
+ logger.error(error_msg)
237
+ with _reload_status_lock:
238
+ _gateway_rules_reload_status["last_error"] = error_msg
239
+ return
240
+
241
+ # Load and validate both configs (reload_configs validates cross-references)
242
+ mcp_config, gateway_rules, error = reload_configs(
243
+ _mcp_config_path,
244
+ rules_path
245
+ )
246
+
247
+ if error:
248
+ logger.error(f"Failed to reload gateway rules: {error}")
249
+ logger.info("Keeping existing gateway rules")
250
+ with _reload_status_lock:
251
+ _gateway_rules_reload_status["last_error"] = error
252
+ return
253
+
254
+ logger.info("Gateway rules validated successfully")
255
+
256
+ # Check for validation warnings
257
+ warnings = validate_rules_against_servers(gateway_rules, mcp_config)
258
+
259
+ # Reload PolicyEngine (synchronous operation)
260
+ success, reload_error = _policy_engine.reload(gateway_rules)
261
+ if success:
262
+ logger.info("PolicyEngine reloaded successfully")
263
+ # Also print to stderr so user definitely sees it
264
+ print(f"\n[HOT RELOAD] Gateway rules reloaded successfully at {rules_path}", file=sys.stderr)
265
+ print(f"[HOT RELOAD] Policy changes are now active", file=sys.stderr)
266
+
267
+ # If we got warnings, show them prominently
268
+ if warnings:
269
+ print(f"\n[HOT RELOAD WARNING] Configuration references undefined servers:", file=sys.stderr)
270
+ for warning in warnings:
271
+ print(f" - {warning}", file=sys.stderr)
272
+ print(f"[HOT RELOAD WARNING] These rules will be ignored until servers are added", file=sys.stderr)
273
+
274
+ # Record success
275
+ with _reload_status_lock:
276
+ _gateway_rules_reload_status["last_success"] = datetime.now()
277
+ _gateway_rules_reload_status["last_error"] = None
278
+ _gateway_rules_reload_status["success_count"] += 1
279
+ _gateway_rules_reload_status["last_warnings"] = warnings
280
+ else:
281
+ logger.error(f"PolicyEngine reload failed: {reload_error}")
282
+ logger.info("Keeping existing policy rules")
283
+ print(f"\n[HOT RELOAD] ERROR: Failed to reload gateway rules: {reload_error}", file=sys.stderr)
284
+
285
+ # Record error
286
+ with _reload_status_lock:
287
+ _gateway_rules_reload_status["last_error"] = f"PolicyEngine reload failed: {reload_error}"
288
+
289
+ except Exception as e:
290
+ error_msg = f"Unexpected error reloading gateway rules: {e}"
291
+ logger.error(error_msg, exc_info=True)
292
+ logger.info("Keeping existing gateway rules")
293
+ with _reload_status_lock:
294
+ _gateway_rules_reload_status["last_error"] = error_msg
295
+
296
+
297
+ def get_reload_status() -> dict:
298
+ """Get current hot reload status for diagnostics.
299
+
300
+ Returns:
301
+ Dictionary containing reload status for both config files,
302
+ including attempt/success timestamps, error messages, and warnings.
303
+ """
304
+ with _reload_status_lock:
305
+ return {
306
+ "mcp_config": _mcp_config_reload_status.copy(),
307
+ "gateway_rules": _gateway_rules_reload_status.copy(),
308
+ }
309
+
310
+
311
+ def parse_args() -> argparse.Namespace:
312
+ """Parse command line arguments.
313
+
314
+ Returns:
315
+ Parsed command line arguments including debug flag
316
+ """
317
+ parser = argparse.ArgumentParser(
318
+ description="Agent MCP Gateway - Policy-based proxy for MCP servers",
319
+ formatter_class=argparse.RawDescriptionHelpFormatter,
320
+ )
321
+ parser.add_argument(
322
+ "--debug",
323
+ action="store_true",
324
+ help="Enable debug mode (exposes get_gateway_status tool for diagnostics)",
325
+ )
326
+ parser.add_argument(
327
+ "--version",
328
+ action="version",
329
+ version="agent-mcp-gateway 0.1.0"
330
+ )
331
+ parser.add_argument(
332
+ "--init",
333
+ action="store_true",
334
+ help="Create config directory at ~/.config/agent-mcp-gateway/ with example files"
335
+ )
336
+ return parser.parse_args()
337
+
338
+
339
+ def init_config_directory() -> None:
340
+ """Create config directory with example configuration files."""
341
+ from pathlib import Path
342
+ import shutil
343
+
344
+ config_dir = Path.home() / ".config" / "agent-mcp-gateway"
345
+
346
+ # Check if directory already exists
347
+ if config_dir.exists():
348
+ response = input(f"Config directory already exists at {config_dir}. Overwrite? (y/N): ")
349
+ if response.lower() != 'y':
350
+ print("Initialization cancelled.")
351
+ return
352
+
353
+ # Create directory
354
+ config_dir.mkdir(parents=True, exist_ok=True)
355
+ print(f"Created config directory: {config_dir}")
356
+
357
+ # Copy example configs from src/config/ directory
358
+ # When installed, they're in site-packages/src/config/
359
+ # When running from source, they're in src/config/
360
+ config_dir_path = Path(__file__).parent / "config"
361
+ source_mcp = config_dir_path / ".mcp.json.example"
362
+ source_rules = config_dir_path / ".mcp-gateway-rules.json.example"
363
+
364
+ dest_mcp = config_dir / "mcp.json"
365
+ dest_rules = config_dir / "mcp-gateway-rules.json"
366
+
367
+ if source_mcp.exists():
368
+ shutil.copy(source_mcp, dest_mcp)
369
+ print(f"Created: {dest_mcp}")
370
+ else:
371
+ print(f"Warning: Example config not found at {source_mcp}")
372
+
373
+ if source_rules.exists():
374
+ shutil.copy(source_rules, dest_rules)
375
+ print(f"Created: {dest_rules}")
376
+ else:
377
+ print(f"Warning: Example rules not found at {source_rules}")
378
+
379
+ print(f"\nConfiguration initialized!")
380
+ print(f"Edit configs at: {config_dir}")
381
+ print(f"\nTo use these configs, run:")
382
+ print(f" GATEWAY_MCP_CONFIG={dest_mcp} \\")
383
+ print(f" GATEWAY_RULES={dest_rules} \\")
384
+ print(f" agent-mcp-gateway")
385
+
386
+
387
+ def main():
388
+ """Initialize and run the Agent MCP Gateway."""
389
+ global _mcp_config_path, _gateway_rules_path, _policy_engine, _proxy_manager, _config_watcher
390
+ global _last_mcp_config_mtime, _last_gateway_rules_mtime
391
+
392
+ # Parse command line arguments
393
+ args = parse_args()
394
+
395
+ # Handle --init command
396
+ if args.init:
397
+ init_config_directory()
398
+ sys.exit(0)
399
+
400
+ # Check for debug mode from environment variable or CLI argument
401
+ # CLI argument takes precedence over environment variable
402
+ debug_mode = args.debug or os.getenv("GATEWAY_DEBUG", "").lower() in ("true", "1", "yes")
403
+
404
+ try:
405
+ # Get configuration file paths from environment or use defaults
406
+ _mcp_config_path = get_mcp_config_path()
407
+ _gateway_rules_path = get_gateway_rules_path()
408
+ audit_log_path = os.environ.get("GATEWAY_AUDIT_LOG", "~/.cache/agent-mcp-gateway/logs/audit.jsonl")
409
+
410
+ # Get default agent ID for fallback chain (optional)
411
+ default_agent_id = os.getenv("GATEWAY_DEFAULT_AGENT")
412
+
413
+ # Initialize modification times for fallback reload checking
414
+ if os.path.exists(_mcp_config_path):
415
+ _last_mcp_config_mtime = os.path.getmtime(_mcp_config_path)
416
+ if os.path.exists(_gateway_rules_path):
417
+ _last_gateway_rules_mtime = os.path.getmtime(_gateway_rules_path)
418
+
419
+ print(f"Loading MCP server configuration from: {_mcp_config_path}", file=sys.stderr)
420
+ print(f"Loading gateway rules from: {_gateway_rules_path}", file=sys.stderr)
421
+ print(f"Audit log will be written to: {audit_log_path}", file=sys.stderr)
422
+ if default_agent_id:
423
+ print(f"Default agent for fallback chain: {default_agent_id}", file=sys.stderr)
424
+ if debug_mode:
425
+ print(f"Debug mode: ENABLED (get_gateway_status tool available)", file=sys.stderr)
426
+ else:
427
+ print(f"Debug mode: DISABLED (use --debug or GATEWAY_DEBUG=true to enable)", file=sys.stderr)
428
+
429
+ # Load configurations
430
+ mcp_config = load_mcp_config(_mcp_config_path)
431
+ gateway_rules = load_gateway_rules(_gateway_rules_path)
432
+
433
+ # Validate that all servers referenced in rules exist
434
+ warnings = validate_rules_against_servers(gateway_rules, mcp_config)
435
+ if warnings:
436
+ print("\nConfiguration warnings:", file=sys.stderr)
437
+ for warning in warnings:
438
+ print(f" - {warning}", file=sys.stderr)
439
+ print(file=sys.stderr)
440
+
441
+ # Initialize policy engine
442
+ _policy_engine = PolicyEngine(gateway_rules)
443
+
444
+ # Initialize audit logger
445
+ audit_logger = AuditLogger(audit_log_path)
446
+
447
+ # Initialize proxy manager
448
+ print("\nInitializing proxy connections to downstream servers...", file=sys.stderr)
449
+ _proxy_manager = ProxyManager()
450
+
451
+ try:
452
+ _proxy_manager.initialize_connections(mcp_config)
453
+
454
+ # Log proxy status
455
+ all_servers = _proxy_manager.get_all_servers()
456
+ print(f" - {len(all_servers)} proxy client(s) initialized", file=sys.stderr)
457
+ for server_name in all_servers:
458
+ # get_all_servers() returns list of server names (strings), not dicts
459
+ status = "ready" # If it's in the list, it was initialized
460
+ print(f" * {server_name}: {status}", file=sys.stderr)
461
+ except Exception as e:
462
+ print(f" - Warning: Proxy initialization encountered errors: {e}", file=sys.stderr)
463
+ print(f" - Gateway will continue, but downstream tools may be unavailable", file=sys.stderr)
464
+
465
+ # Initialize metrics collector
466
+ metrics_collector = MetricsCollector()
467
+ print(f" - Metrics collector initialized", file=sys.stderr)
468
+
469
+ # Create and register middleware
470
+ access_control = AgentAccessControl(_policy_engine)
471
+ gateway.add_middleware(access_control)
472
+ print(f" - Access control middleware registered", file=sys.stderr)
473
+
474
+ # Initialize gateway with all components
475
+ initialize_gateway(
476
+ _policy_engine,
477
+ mcp_config,
478
+ _proxy_manager,
479
+ check_config_changes,
480
+ get_reload_status,
481
+ default_agent_id,
482
+ debug_mode
483
+ )
484
+
485
+ # Initialize ConfigWatcher for hot reloading
486
+ logger.debug("=== ConfigWatcher Initialization Starting ===")
487
+ logger.debug(f"MCP config path: {_mcp_config_path}")
488
+ logger.debug(f"MCP config path (absolute): {os.path.abspath(_mcp_config_path)}")
489
+ logger.debug(f"MCP config exists: {os.path.exists(_mcp_config_path)}")
490
+ logger.debug(f"Gateway rules path: {_gateway_rules_path}")
491
+ logger.debug(f"Gateway rules path (absolute): {os.path.abspath(_gateway_rules_path)}")
492
+ logger.debug(f"Gateway rules exists: {os.path.exists(_gateway_rules_path)}")
493
+ logger.debug(f"on_mcp_config_changed callback: {on_mcp_config_changed}")
494
+ logger.debug(f"on_gateway_rules_changed callback: {on_gateway_rules_changed}")
495
+
496
+ try:
497
+ _config_watcher = ConfigWatcher(
498
+ mcp_config_path=_mcp_config_path,
499
+ gateway_rules_path=_gateway_rules_path,
500
+ on_mcp_config_changed=on_mcp_config_changed,
501
+ on_gateway_rules_changed=on_gateway_rules_changed,
502
+ debounce_seconds=0.3
503
+ )
504
+ logger.debug("ConfigWatcher instance created successfully")
505
+
506
+ _config_watcher.start()
507
+ logger.debug("ConfigWatcher.start() called successfully")
508
+
509
+ # Check if observer is running
510
+ if hasattr(_config_watcher, 'observer') and _config_watcher.observer:
511
+ logger.debug(f"Observer is alive: {_config_watcher.observer.is_alive()}")
512
+ logger.debug(f"Observer thread: {_config_watcher.observer}")
513
+ else:
514
+ logger.warning("Observer not initialized or None")
515
+
516
+ print(f" - Configuration file watching enabled (hot reload)", file=sys.stderr)
517
+ logger.debug("=== ConfigWatcher Initialization Complete ===")
518
+
519
+ except Exception as e:
520
+ logger.error(f"FAILED to initialize ConfigWatcher: {e}", exc_info=True)
521
+ print(f" - Warning: Could not start config file watcher: {e}", file=sys.stderr)
522
+ print(f" - Hot reload disabled, but gateway will continue normally", file=sys.stderr)
523
+
524
+ # Log successful initialization
525
+ print(f"\nAgent MCP Gateway initialized successfully", file=sys.stderr)
526
+ print(f" - {len(mcp_config.get('mcpServers', {}))} MCP server(s) configured", file=sys.stderr)
527
+ print(f" - {len(gateway_rules.get('agents', {}))} agent(s) configured", file=sys.stderr)
528
+ print(f" - Default policy: {'deny' if gateway_rules.get('defaults', {}).get('deny_on_missing_agent', True) else 'allow'} unknown agents", file=sys.stderr)
529
+ if debug_mode:
530
+ print(f" - 4 gateway tools available: list_servers, get_server_tools, execute_tool, get_gateway_status", file=sys.stderr)
531
+ else:
532
+ print(f" - 3 gateway tools available: list_servers, get_server_tools, execute_tool", file=sys.stderr)
533
+ print("\nGateway is ready. Running with stdio transport...\n", file=sys.stderr)
534
+
535
+ # Run gateway with stdio transport (default)
536
+ try:
537
+ gateway.run()
538
+ finally:
539
+ # Clean up ConfigWatcher on shutdown
540
+ if _config_watcher:
541
+ logger.info("Stopping configuration file watcher...")
542
+ _config_watcher.stop()
543
+
544
+ except FileNotFoundError as e:
545
+ print(f"\nERROR: Configuration file not found: {e}", file=sys.stderr)
546
+ sys.exit(1)
547
+ except ValueError as e:
548
+ print(f"\nERROR: Invalid configuration: {e}", file=sys.stderr)
549
+ sys.exit(1)
550
+ except Exception as e:
551
+ print(f"\nERROR: Failed to start gateway: {e}", file=sys.stderr)
552
+ sys.exit(1)
553
+
554
+
555
+ if __name__ == "__main__":
556
+ main()