agent-mcp-gateway 0.2.1__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.
- agent_mcp_gateway-0.2.1.dist-info/METADATA +1330 -0
- agent_mcp_gateway-0.2.1.dist-info/RECORD +18 -0
- agent_mcp_gateway-0.2.1.dist-info/WHEEL +4 -0
- agent_mcp_gateway-0.2.1.dist-info/entry_points.txt +2 -0
- agent_mcp_gateway-0.2.1.dist-info/licenses/LICENSE +21 -0
- src/CONFIG_README.md +351 -0
- src/__init__.py +1 -0
- src/audit.py +94 -0
- src/config/.mcp-gateway-rules.json.example +59 -0
- src/config/.mcp.json.example +30 -0
- src/config.py +849 -0
- src/config_watcher.py +296 -0
- src/gateway.py +547 -0
- src/main.py +570 -0
- src/metrics.py +299 -0
- src/middleware.py +166 -0
- src/policy.py +500 -0
- src/proxy.py +649 -0
src/main.py
ADDED
|
@@ -0,0 +1,570 @@
|
|
|
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"\nNext steps:")
|
|
382
|
+
print(f"\n1. Configure your downstream MCP servers:")
|
|
383
|
+
print(f" ~/.config/agent-mcp-gateway/.mcp.json")
|
|
384
|
+
print(f"\n2. Configure gateway rules for agent access control:")
|
|
385
|
+
print(f" ~/.config/agent-mcp-gateway/.mcp-gateway-rules.json")
|
|
386
|
+
print(f"\n3. Add to your MCP client configuration:")
|
|
387
|
+
print(f' {{')
|
|
388
|
+
print(f' "mcpServers": {{')
|
|
389
|
+
print(f' "agent-mcp-gateway": {{')
|
|
390
|
+
print(f' "command": "uvx",')
|
|
391
|
+
print(f' "args": ["agent-mcp-gateway"]')
|
|
392
|
+
print(f' }}')
|
|
393
|
+
print(f' }}')
|
|
394
|
+
print(f' }}')
|
|
395
|
+
print(f"\n Or with Claude Code:")
|
|
396
|
+
print(f" claude mcp add agent-mcp-gateway uvx agent-mcp-gateway")
|
|
397
|
+
print(f"\nNote: Configs at ~/.config/agent-mcp-gateway/ are auto-discovered.")
|
|
398
|
+
print(f" For custom paths, see: https://github.com/roddutra/agent-mcp-gateway#4-environment-variables-reference")
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def main():
|
|
402
|
+
"""Initialize and run the Agent MCP Gateway."""
|
|
403
|
+
global _mcp_config_path, _gateway_rules_path, _policy_engine, _proxy_manager, _config_watcher
|
|
404
|
+
global _last_mcp_config_mtime, _last_gateway_rules_mtime
|
|
405
|
+
|
|
406
|
+
# Parse command line arguments
|
|
407
|
+
args = parse_args()
|
|
408
|
+
|
|
409
|
+
# Handle --init command
|
|
410
|
+
if args.init:
|
|
411
|
+
init_config_directory()
|
|
412
|
+
sys.exit(0)
|
|
413
|
+
|
|
414
|
+
# Check for debug mode from environment variable or CLI argument
|
|
415
|
+
# CLI argument takes precedence over environment variable
|
|
416
|
+
debug_mode = args.debug or os.getenv("GATEWAY_DEBUG", "").lower() in ("true", "1", "yes")
|
|
417
|
+
|
|
418
|
+
try:
|
|
419
|
+
# Get configuration file paths from environment or use defaults
|
|
420
|
+
_mcp_config_path = get_mcp_config_path()
|
|
421
|
+
_gateway_rules_path = get_gateway_rules_path()
|
|
422
|
+
audit_log_path = os.environ.get("GATEWAY_AUDIT_LOG", "~/.cache/agent-mcp-gateway/logs/audit.jsonl")
|
|
423
|
+
|
|
424
|
+
# Get default agent ID for fallback chain (optional)
|
|
425
|
+
default_agent_id = os.getenv("GATEWAY_DEFAULT_AGENT")
|
|
426
|
+
|
|
427
|
+
# Initialize modification times for fallback reload checking
|
|
428
|
+
if os.path.exists(_mcp_config_path):
|
|
429
|
+
_last_mcp_config_mtime = os.path.getmtime(_mcp_config_path)
|
|
430
|
+
if os.path.exists(_gateway_rules_path):
|
|
431
|
+
_last_gateway_rules_mtime = os.path.getmtime(_gateway_rules_path)
|
|
432
|
+
|
|
433
|
+
print(f"Loading MCP server configuration from: {_mcp_config_path}", file=sys.stderr)
|
|
434
|
+
print(f"Loading gateway rules from: {_gateway_rules_path}", file=sys.stderr)
|
|
435
|
+
print(f"Audit log will be written to: {audit_log_path}", file=sys.stderr)
|
|
436
|
+
if default_agent_id:
|
|
437
|
+
print(f"Default agent for fallback chain: {default_agent_id}", file=sys.stderr)
|
|
438
|
+
if debug_mode:
|
|
439
|
+
print(f"Debug mode: ENABLED (get_gateway_status tool available)", file=sys.stderr)
|
|
440
|
+
else:
|
|
441
|
+
print(f"Debug mode: DISABLED (use --debug or GATEWAY_DEBUG=true to enable)", file=sys.stderr)
|
|
442
|
+
|
|
443
|
+
# Load configurations
|
|
444
|
+
mcp_config = load_mcp_config(_mcp_config_path)
|
|
445
|
+
gateway_rules = load_gateway_rules(_gateway_rules_path)
|
|
446
|
+
|
|
447
|
+
# Validate that all servers referenced in rules exist
|
|
448
|
+
warnings = validate_rules_against_servers(gateway_rules, mcp_config)
|
|
449
|
+
if warnings:
|
|
450
|
+
print("\nConfiguration warnings:", file=sys.stderr)
|
|
451
|
+
for warning in warnings:
|
|
452
|
+
print(f" - {warning}", file=sys.stderr)
|
|
453
|
+
print(file=sys.stderr)
|
|
454
|
+
|
|
455
|
+
# Initialize policy engine
|
|
456
|
+
_policy_engine = PolicyEngine(gateway_rules)
|
|
457
|
+
|
|
458
|
+
# Initialize audit logger
|
|
459
|
+
audit_logger = AuditLogger(audit_log_path)
|
|
460
|
+
|
|
461
|
+
# Initialize proxy manager
|
|
462
|
+
print("\nInitializing proxy connections to downstream servers...", file=sys.stderr)
|
|
463
|
+
_proxy_manager = ProxyManager()
|
|
464
|
+
|
|
465
|
+
try:
|
|
466
|
+
_proxy_manager.initialize_connections(mcp_config)
|
|
467
|
+
|
|
468
|
+
# Log proxy status
|
|
469
|
+
all_servers = _proxy_manager.get_all_servers()
|
|
470
|
+
print(f" - {len(all_servers)} proxy client(s) initialized", file=sys.stderr)
|
|
471
|
+
for server_name in all_servers:
|
|
472
|
+
# get_all_servers() returns list of server names (strings), not dicts
|
|
473
|
+
status = "ready" # If it's in the list, it was initialized
|
|
474
|
+
print(f" * {server_name}: {status}", file=sys.stderr)
|
|
475
|
+
except Exception as e:
|
|
476
|
+
print(f" - Warning: Proxy initialization encountered errors: {e}", file=sys.stderr)
|
|
477
|
+
print(f" - Gateway will continue, but downstream tools may be unavailable", file=sys.stderr)
|
|
478
|
+
|
|
479
|
+
# Initialize metrics collector
|
|
480
|
+
metrics_collector = MetricsCollector()
|
|
481
|
+
print(f" - Metrics collector initialized", file=sys.stderr)
|
|
482
|
+
|
|
483
|
+
# Create and register middleware
|
|
484
|
+
access_control = AgentAccessControl(_policy_engine)
|
|
485
|
+
gateway.add_middleware(access_control)
|
|
486
|
+
print(f" - Access control middleware registered", file=sys.stderr)
|
|
487
|
+
|
|
488
|
+
# Initialize gateway with all components
|
|
489
|
+
initialize_gateway(
|
|
490
|
+
_policy_engine,
|
|
491
|
+
mcp_config,
|
|
492
|
+
_proxy_manager,
|
|
493
|
+
check_config_changes,
|
|
494
|
+
get_reload_status,
|
|
495
|
+
default_agent_id,
|
|
496
|
+
debug_mode
|
|
497
|
+
)
|
|
498
|
+
|
|
499
|
+
# Initialize ConfigWatcher for hot reloading
|
|
500
|
+
logger.debug("=== ConfigWatcher Initialization Starting ===")
|
|
501
|
+
logger.debug(f"MCP config path: {_mcp_config_path}")
|
|
502
|
+
logger.debug(f"MCP config path (absolute): {os.path.abspath(_mcp_config_path)}")
|
|
503
|
+
logger.debug(f"MCP config exists: {os.path.exists(_mcp_config_path)}")
|
|
504
|
+
logger.debug(f"Gateway rules path: {_gateway_rules_path}")
|
|
505
|
+
logger.debug(f"Gateway rules path (absolute): {os.path.abspath(_gateway_rules_path)}")
|
|
506
|
+
logger.debug(f"Gateway rules exists: {os.path.exists(_gateway_rules_path)}")
|
|
507
|
+
logger.debug(f"on_mcp_config_changed callback: {on_mcp_config_changed}")
|
|
508
|
+
logger.debug(f"on_gateway_rules_changed callback: {on_gateway_rules_changed}")
|
|
509
|
+
|
|
510
|
+
try:
|
|
511
|
+
_config_watcher = ConfigWatcher(
|
|
512
|
+
mcp_config_path=_mcp_config_path,
|
|
513
|
+
gateway_rules_path=_gateway_rules_path,
|
|
514
|
+
on_mcp_config_changed=on_mcp_config_changed,
|
|
515
|
+
on_gateway_rules_changed=on_gateway_rules_changed,
|
|
516
|
+
debounce_seconds=0.3
|
|
517
|
+
)
|
|
518
|
+
logger.debug("ConfigWatcher instance created successfully")
|
|
519
|
+
|
|
520
|
+
_config_watcher.start()
|
|
521
|
+
logger.debug("ConfigWatcher.start() called successfully")
|
|
522
|
+
|
|
523
|
+
# Check if observer is running
|
|
524
|
+
if hasattr(_config_watcher, 'observer') and _config_watcher.observer:
|
|
525
|
+
logger.debug(f"Observer is alive: {_config_watcher.observer.is_alive()}")
|
|
526
|
+
logger.debug(f"Observer thread: {_config_watcher.observer}")
|
|
527
|
+
else:
|
|
528
|
+
logger.warning("Observer not initialized or None")
|
|
529
|
+
|
|
530
|
+
print(f" - Configuration file watching enabled (hot reload)", file=sys.stderr)
|
|
531
|
+
logger.debug("=== ConfigWatcher Initialization Complete ===")
|
|
532
|
+
|
|
533
|
+
except Exception as e:
|
|
534
|
+
logger.error(f"FAILED to initialize ConfigWatcher: {e}", exc_info=True)
|
|
535
|
+
print(f" - Warning: Could not start config file watcher: {e}", file=sys.stderr)
|
|
536
|
+
print(f" - Hot reload disabled, but gateway will continue normally", file=sys.stderr)
|
|
537
|
+
|
|
538
|
+
# Log successful initialization
|
|
539
|
+
print(f"\nAgent MCP Gateway initialized successfully", file=sys.stderr)
|
|
540
|
+
print(f" - {len(mcp_config.get('mcpServers', {}))} MCP server(s) configured", file=sys.stderr)
|
|
541
|
+
print(f" - {len(gateway_rules.get('agents', {}))} agent(s) configured", file=sys.stderr)
|
|
542
|
+
print(f" - Default policy: {'deny' if gateway_rules.get('defaults', {}).get('deny_on_missing_agent', True) else 'allow'} unknown agents", file=sys.stderr)
|
|
543
|
+
if debug_mode:
|
|
544
|
+
print(f" - 4 gateway tools available: list_servers, get_server_tools, execute_tool, get_gateway_status", file=sys.stderr)
|
|
545
|
+
else:
|
|
546
|
+
print(f" - 3 gateway tools available: list_servers, get_server_tools, execute_tool", file=sys.stderr)
|
|
547
|
+
print("\nGateway is ready. Running with stdio transport...\n", file=sys.stderr)
|
|
548
|
+
|
|
549
|
+
# Run gateway with stdio transport (default)
|
|
550
|
+
try:
|
|
551
|
+
gateway.run()
|
|
552
|
+
finally:
|
|
553
|
+
# Clean up ConfigWatcher on shutdown
|
|
554
|
+
if _config_watcher:
|
|
555
|
+
logger.info("Stopping configuration file watcher...")
|
|
556
|
+
_config_watcher.stop()
|
|
557
|
+
|
|
558
|
+
except FileNotFoundError as e:
|
|
559
|
+
print(f"\nERROR: Configuration file not found: {e}", file=sys.stderr)
|
|
560
|
+
sys.exit(1)
|
|
561
|
+
except ValueError as e:
|
|
562
|
+
print(f"\nERROR: Invalid configuration: {e}", file=sys.stderr)
|
|
563
|
+
sys.exit(1)
|
|
564
|
+
except Exception as e:
|
|
565
|
+
print(f"\nERROR: Failed to start gateway: {e}", file=sys.stderr)
|
|
566
|
+
sys.exit(1)
|
|
567
|
+
|
|
568
|
+
|
|
569
|
+
if __name__ == "__main__":
|
|
570
|
+
main()
|