rigout 0.1.0__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.
- rigout/__init__.py +40 -0
- rigout/config_manager.py +394 -0
- rigout/mcp_http_server.py +262 -0
- rigout/mcp_url_launcher.py +240 -0
- rigout/mcp_workspace_manager.py +361 -0
- rigout/security_validator.py +371 -0
- rigout/server.py +374 -0
- rigout/ssh_manager.py +984 -0
- rigout/terminal_session.py +41 -0
- rigout/tools/__init__.py +30 -0
- rigout/tools/command.py +182 -0
- rigout/tools/docker.py +79 -0
- rigout/tools/environment.py +91 -0
- rigout/tools/file_ops.py +209 -0
- rigout/tools/monitoring.py +110 -0
- rigout/tools/tunnel.py +92 -0
- rigout-0.1.0.dist-info/METADATA +176 -0
- rigout-0.1.0.dist-info/RECORD +21 -0
- rigout-0.1.0.dist-info/WHEEL +4 -0
- rigout-0.1.0.dist-info/entry_points.txt +3 -0
- rigout-0.1.0.dist-info/licenses/LICENSE +201 -0
rigout/__init__.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# Rigout package
|
|
2
|
+
__version__ = "0.1.0"
|
|
3
|
+
|
|
4
|
+
from .config_manager import CloudflareConfig, ConfigManager, SecurityConfig, ServerConfig, SSHConfig
|
|
5
|
+
from .security_validator import SecurityValidator
|
|
6
|
+
from .ssh_manager import (
|
|
7
|
+
ConfigurationError,
|
|
8
|
+
ConnectionError,
|
|
9
|
+
HardwareInfo,
|
|
10
|
+
SecurityError,
|
|
11
|
+
TunnelEndpoint,
|
|
12
|
+
TunnelManager,
|
|
13
|
+
build_env_assignments,
|
|
14
|
+
get_tunnel_manager,
|
|
15
|
+
heredoc_redirect,
|
|
16
|
+
shell_join,
|
|
17
|
+
shell_quote,
|
|
18
|
+
)
|
|
19
|
+
from .terminal_session import TerminalSession
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
"ConfigurationError",
|
|
23
|
+
"SecurityError",
|
|
24
|
+
"ConnectionError",
|
|
25
|
+
"TunnelEndpoint",
|
|
26
|
+
"HardwareInfo",
|
|
27
|
+
"TunnelManager",
|
|
28
|
+
"get_tunnel_manager",
|
|
29
|
+
"shell_quote",
|
|
30
|
+
"shell_join",
|
|
31
|
+
"build_env_assignments",
|
|
32
|
+
"heredoc_redirect",
|
|
33
|
+
"TerminalSession",
|
|
34
|
+
"SecurityValidator",
|
|
35
|
+
"ServerConfig",
|
|
36
|
+
"SSHConfig",
|
|
37
|
+
"CloudflareConfig",
|
|
38
|
+
"SecurityConfig",
|
|
39
|
+
"ConfigManager",
|
|
40
|
+
]
|
rigout/config_manager.py
ADDED
|
@@ -0,0 +1,394 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
Configuration Management System for Enhanced MCP Hardware Server
|
|
4
|
+
Handles secure configuration loading, validation, and management
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
import logging
|
|
9
|
+
import os
|
|
10
|
+
from dataclasses import asdict, dataclass
|
|
11
|
+
from datetime import datetime
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
logger = logging.getLogger(__name__)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass
|
|
19
|
+
class ServerConfig:
|
|
20
|
+
"""Server configuration structure"""
|
|
21
|
+
|
|
22
|
+
name: str = "enhanced-hardware-server"
|
|
23
|
+
version: str = "1.0.0"
|
|
24
|
+
log_level: str = "INFO"
|
|
25
|
+
max_connections: int = 100
|
|
26
|
+
request_timeout: int = 30
|
|
27
|
+
session_timeout: int = 3600
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass
|
|
31
|
+
class SSHConfig:
|
|
32
|
+
"""SSH configuration structure"""
|
|
33
|
+
|
|
34
|
+
private_key_path: str = ""
|
|
35
|
+
public_key_path: str = ""
|
|
36
|
+
public_key_content: str = ""
|
|
37
|
+
username: str = "agent"
|
|
38
|
+
default_port: int = 22
|
|
39
|
+
connection_timeout: int = 10
|
|
40
|
+
auth_timeout: int = 10
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass
|
|
44
|
+
class CloudflareConfig:
|
|
45
|
+
"""Cloudflare configuration structure"""
|
|
46
|
+
|
|
47
|
+
email: str = ""
|
|
48
|
+
api_key: str = ""
|
|
49
|
+
domain: str = ""
|
|
50
|
+
auto_tunnel_creation: bool = False
|
|
51
|
+
tunnel_timeout: int = 60
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass
|
|
55
|
+
class SecurityConfig:
|
|
56
|
+
"""Security configuration structure"""
|
|
57
|
+
|
|
58
|
+
enable_rate_limiting: bool = True
|
|
59
|
+
max_requests_per_minute: int = 60
|
|
60
|
+
enable_command_validation: bool = True
|
|
61
|
+
enable_audit_logging: bool = True
|
|
62
|
+
ai_agent_mode: bool = False # Enable maximum flexibility for AI agents
|
|
63
|
+
allowed_sudo_commands: list[str] = None
|
|
64
|
+
blocked_commands: list[str] = None
|
|
65
|
+
|
|
66
|
+
def __post_init__(self):
|
|
67
|
+
if self.allowed_sudo_commands is None:
|
|
68
|
+
if self.ai_agent_mode:
|
|
69
|
+
# In AI agent mode, allow most common commands
|
|
70
|
+
self.allowed_sudo_commands = [
|
|
71
|
+
"apt",
|
|
72
|
+
"yum",
|
|
73
|
+
"dnf",
|
|
74
|
+
"systemctl",
|
|
75
|
+
"service",
|
|
76
|
+
"docker",
|
|
77
|
+
"pip",
|
|
78
|
+
"npm",
|
|
79
|
+
"make",
|
|
80
|
+
"cmake",
|
|
81
|
+
"git",
|
|
82
|
+
"wget",
|
|
83
|
+
"curl",
|
|
84
|
+
"tar",
|
|
85
|
+
"unzip",
|
|
86
|
+
"chmod",
|
|
87
|
+
"chown",
|
|
88
|
+
"mount",
|
|
89
|
+
"umount",
|
|
90
|
+
"iptables",
|
|
91
|
+
"ufw",
|
|
92
|
+
"firewall-cmd",
|
|
93
|
+
]
|
|
94
|
+
else:
|
|
95
|
+
self.allowed_sudo_commands = [
|
|
96
|
+
"apt",
|
|
97
|
+
"yum",
|
|
98
|
+
"dnf",
|
|
99
|
+
"systemctl",
|
|
100
|
+
"service",
|
|
101
|
+
"docker",
|
|
102
|
+
"pip",
|
|
103
|
+
"npm",
|
|
104
|
+
"make",
|
|
105
|
+
"cmake",
|
|
106
|
+
]
|
|
107
|
+
if self.blocked_commands is None:
|
|
108
|
+
if self.ai_agent_mode:
|
|
109
|
+
# In AI agent mode, only block the most dangerous commands
|
|
110
|
+
self.blocked_commands = [
|
|
111
|
+
"rm -rf /",
|
|
112
|
+
"dd if=/dev/zero",
|
|
113
|
+
"mkfs.ext4 /dev/sd",
|
|
114
|
+
"fdisk /dev/sd",
|
|
115
|
+
"parted /dev/sd",
|
|
116
|
+
]
|
|
117
|
+
else:
|
|
118
|
+
self.blocked_commands = [
|
|
119
|
+
"rm -rf /",
|
|
120
|
+
"dd if=",
|
|
121
|
+
"mkfs.",
|
|
122
|
+
"fdisk",
|
|
123
|
+
"parted",
|
|
124
|
+
"format",
|
|
125
|
+
"del /s",
|
|
126
|
+
"rmdir /s",
|
|
127
|
+
]
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class ConfigManager:
|
|
131
|
+
"""Manages configuration loading, validation, and updates"""
|
|
132
|
+
|
|
133
|
+
def __init__(self, config_file: str = "mcp-server-config.json"):
|
|
134
|
+
self.config_file = Path(config_file)
|
|
135
|
+
self.server_config = ServerConfig()
|
|
136
|
+
self.ssh_config = SSHConfig()
|
|
137
|
+
self.cloudflare_config = CloudflareConfig()
|
|
138
|
+
self.security_config = SecurityConfig()
|
|
139
|
+
self._config_hash = ""
|
|
140
|
+
|
|
141
|
+
def load_config(self) -> bool:
|
|
142
|
+
"""Load configuration from file and environment variables"""
|
|
143
|
+
try:
|
|
144
|
+
# Create default config if doesn't exist
|
|
145
|
+
if not self.config_file.exists():
|
|
146
|
+
logger.info(f"Configuration file not found, creating default: {self.config_file}")
|
|
147
|
+
self._create_default_config()
|
|
148
|
+
return True
|
|
149
|
+
|
|
150
|
+
# Load from file
|
|
151
|
+
with open(self.config_file, encoding="utf-8") as f:
|
|
152
|
+
data = json.load(f)
|
|
153
|
+
|
|
154
|
+
# Validate structure
|
|
155
|
+
self._validate_config_structure(data)
|
|
156
|
+
|
|
157
|
+
# Load server config
|
|
158
|
+
server_data = data.get("server_config", {})
|
|
159
|
+
self.server_config = ServerConfig(
|
|
160
|
+
**{k: v for k, v in server_data.items() if k in ServerConfig.__dataclass_fields__}
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
# Load SSH config with environment override
|
|
164
|
+
ssh_data = data.get("ssh_config", {})
|
|
165
|
+
self.ssh_config = SSHConfig(**{k: v for k, v in ssh_data.items() if k in SSHConfig.__dataclass_fields__})
|
|
166
|
+
|
|
167
|
+
# Override with environment variables
|
|
168
|
+
if os.getenv("SSH_PRIVATE_KEY_PATH"):
|
|
169
|
+
self.ssh_config.private_key_path = os.getenv("SSH_PRIVATE_KEY_PATH")
|
|
170
|
+
if os.getenv("SSH_USERNAME"):
|
|
171
|
+
self.ssh_config.username = os.getenv("SSH_USERNAME")
|
|
172
|
+
|
|
173
|
+
# Load Cloudflare config with environment override
|
|
174
|
+
cf_data = data.get("cloudflare_config", {})
|
|
175
|
+
self.cloudflare_config = CloudflareConfig(
|
|
176
|
+
**{k: v for k, v in cf_data.items() if k in CloudflareConfig.__dataclass_fields__}
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
# Override with environment variables (more secure)
|
|
180
|
+
if os.getenv("CLOUDFLARE_EMAIL"):
|
|
181
|
+
self.cloudflare_config.email = os.getenv("CLOUDFLARE_EMAIL")
|
|
182
|
+
if os.getenv("CLOUDFLARE_API_KEY"):
|
|
183
|
+
self.cloudflare_config.api_key = os.getenv("CLOUDFLARE_API_KEY")
|
|
184
|
+
|
|
185
|
+
# Load security config
|
|
186
|
+
security_data = data.get("security_config", {})
|
|
187
|
+
self.security_config = SecurityConfig(
|
|
188
|
+
**{k: v for k, v in security_data.items() if k in SecurityConfig.__dataclass_fields__}
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
# Calculate config hash for change detection
|
|
192
|
+
self._config_hash = self._calculate_config_hash(data)
|
|
193
|
+
|
|
194
|
+
logger.info("Configuration loaded successfully")
|
|
195
|
+
return True
|
|
196
|
+
|
|
197
|
+
except json.JSONDecodeError as e:
|
|
198
|
+
logger.error(f"Invalid JSON in config file: {e}")
|
|
199
|
+
return False
|
|
200
|
+
except Exception as e:
|
|
201
|
+
logger.error(f"Error loading configuration: {e}")
|
|
202
|
+
return False
|
|
203
|
+
|
|
204
|
+
def save_config(self) -> bool:
|
|
205
|
+
"""Save current configuration to file"""
|
|
206
|
+
try:
|
|
207
|
+
config_data = {
|
|
208
|
+
"server_config": asdict(self.server_config),
|
|
209
|
+
"ssh_config": asdict(self.ssh_config),
|
|
210
|
+
"cloudflare_config": asdict(self.cloudflare_config),
|
|
211
|
+
"security_config": asdict(self.security_config),
|
|
212
|
+
"last_updated": datetime.now().isoformat(),
|
|
213
|
+
"version": "1.0.0",
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
# Don't save sensitive data to file (use environment variables)
|
|
217
|
+
config_data["cloudflare_config"]["email"] = ""
|
|
218
|
+
config_data["cloudflare_config"]["api_key"] = ""
|
|
219
|
+
|
|
220
|
+
# Create backup of existing config
|
|
221
|
+
if self.config_file.exists():
|
|
222
|
+
backup_file = self.config_file.with_suffix(".json.backup")
|
|
223
|
+
if backup_file.exists():
|
|
224
|
+
backup_file.unlink()
|
|
225
|
+
self.config_file.rename(backup_file)
|
|
226
|
+
logger.info(f"Created config backup: {backup_file}")
|
|
227
|
+
|
|
228
|
+
# Write new config
|
|
229
|
+
with open(self.config_file, "w", encoding="utf-8") as f:
|
|
230
|
+
json.dump(config_data, f, indent=2, ensure_ascii=False)
|
|
231
|
+
|
|
232
|
+
logger.info(f"Configuration saved to: {self.config_file}")
|
|
233
|
+
return True
|
|
234
|
+
|
|
235
|
+
except Exception as e:
|
|
236
|
+
logger.error(f"Error saving configuration: {e}")
|
|
237
|
+
return False
|
|
238
|
+
|
|
239
|
+
def validate_config(self) -> list[str]:
|
|
240
|
+
"""Validate current configuration and return list of issues"""
|
|
241
|
+
issues = []
|
|
242
|
+
|
|
243
|
+
# Validate SSH config
|
|
244
|
+
if not self.ssh_config.private_key_path:
|
|
245
|
+
issues.append("SSH private key path not configured")
|
|
246
|
+
elif not Path(self.ssh_config.private_key_path).exists():
|
|
247
|
+
issues.append(f"SSH private key file not found: {self.ssh_config.private_key_path}")
|
|
248
|
+
|
|
249
|
+
if not self.ssh_config.username:
|
|
250
|
+
issues.append("SSH username not configured")
|
|
251
|
+
|
|
252
|
+
# Validate Cloudflare config (if auto tunnel creation is enabled)
|
|
253
|
+
if self.cloudflare_config.auto_tunnel_creation:
|
|
254
|
+
if not self.cloudflare_config.email:
|
|
255
|
+
issues.append("Cloudflare email not configured (required for auto tunnel creation)")
|
|
256
|
+
if not self.cloudflare_config.api_key:
|
|
257
|
+
issues.append("Cloudflare API key not configured (required for auto tunnel creation)")
|
|
258
|
+
|
|
259
|
+
# Validate server config
|
|
260
|
+
if self.server_config.max_connections < 1:
|
|
261
|
+
issues.append("Max connections must be at least 1")
|
|
262
|
+
|
|
263
|
+
if self.server_config.request_timeout < 5:
|
|
264
|
+
issues.append("Request timeout must be at least 5 seconds")
|
|
265
|
+
|
|
266
|
+
# Validate security config
|
|
267
|
+
if self.security_config.max_requests_per_minute < 1:
|
|
268
|
+
issues.append("Max requests per minute must be at least 1")
|
|
269
|
+
|
|
270
|
+
return issues
|
|
271
|
+
|
|
272
|
+
def get_config_summary(self) -> dict[str, Any]:
|
|
273
|
+
"""Get a summary of current configuration (without sensitive data)"""
|
|
274
|
+
return {
|
|
275
|
+
"server": {
|
|
276
|
+
"name": self.server_config.name,
|
|
277
|
+
"version": self.server_config.version,
|
|
278
|
+
"log_level": self.server_config.log_level,
|
|
279
|
+
"max_connections": self.server_config.max_connections,
|
|
280
|
+
},
|
|
281
|
+
"ssh": {
|
|
282
|
+
"username": self.ssh_config.username,
|
|
283
|
+
"default_port": self.ssh_config.default_port,
|
|
284
|
+
"has_private_key": bool(self.ssh_config.private_key_path),
|
|
285
|
+
"key_exists": Path(self.ssh_config.private_key_path).exists()
|
|
286
|
+
if self.ssh_config.private_key_path
|
|
287
|
+
else False,
|
|
288
|
+
},
|
|
289
|
+
"cloudflare": {
|
|
290
|
+
"domain": self.cloudflare_config.domain,
|
|
291
|
+
"auto_tunnel_creation": self.cloudflare_config.auto_tunnel_creation,
|
|
292
|
+
"has_credentials": bool(self.cloudflare_config.email and self.cloudflare_config.api_key),
|
|
293
|
+
},
|
|
294
|
+
"security": {
|
|
295
|
+
"rate_limiting_enabled": self.security_config.enable_rate_limiting,
|
|
296
|
+
"command_validation_enabled": self.security_config.enable_command_validation,
|
|
297
|
+
"audit_logging_enabled": self.security_config.enable_audit_logging,
|
|
298
|
+
"max_requests_per_minute": self.security_config.max_requests_per_minute,
|
|
299
|
+
},
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
def update_config(self, section: str, updates: dict[str, Any]) -> bool:
|
|
303
|
+
"""Update specific configuration section"""
|
|
304
|
+
try:
|
|
305
|
+
if section == "server":
|
|
306
|
+
for key, value in updates.items():
|
|
307
|
+
if hasattr(self.server_config, key):
|
|
308
|
+
setattr(self.server_config, key, value)
|
|
309
|
+
elif section == "ssh":
|
|
310
|
+
for key, value in updates.items():
|
|
311
|
+
if hasattr(self.ssh_config, key):
|
|
312
|
+
setattr(self.ssh_config, key, value)
|
|
313
|
+
elif section == "cloudflare":
|
|
314
|
+
for key, value in updates.items():
|
|
315
|
+
if hasattr(self.cloudflare_config, key):
|
|
316
|
+
setattr(self.cloudflare_config, key, value)
|
|
317
|
+
elif section == "security":
|
|
318
|
+
for key, value in updates.items():
|
|
319
|
+
if hasattr(self.security_config, key):
|
|
320
|
+
setattr(self.security_config, key, value)
|
|
321
|
+
else:
|
|
322
|
+
logger.error(f"Unknown configuration section: {section}")
|
|
323
|
+
return False
|
|
324
|
+
|
|
325
|
+
logger.info(f"Updated configuration section: {section}")
|
|
326
|
+
return True
|
|
327
|
+
|
|
328
|
+
except Exception as e:
|
|
329
|
+
logger.error(f"Error updating configuration: {e}")
|
|
330
|
+
return False
|
|
331
|
+
|
|
332
|
+
def has_config_changed(self) -> bool:
|
|
333
|
+
"""Check if configuration file has changed since last load"""
|
|
334
|
+
if not self.config_file.exists():
|
|
335
|
+
return False
|
|
336
|
+
|
|
337
|
+
try:
|
|
338
|
+
with open(self.config_file, encoding="utf-8") as f:
|
|
339
|
+
data = json.load(f)
|
|
340
|
+
|
|
341
|
+
current_hash = self._calculate_config_hash(data)
|
|
342
|
+
return current_hash != self._config_hash
|
|
343
|
+
|
|
344
|
+
except Exception:
|
|
345
|
+
return False
|
|
346
|
+
|
|
347
|
+
def reload_if_changed(self) -> bool:
|
|
348
|
+
"""Reload configuration if it has changed"""
|
|
349
|
+
if self.has_config_changed():
|
|
350
|
+
logger.info("Configuration file changed, reloading...")
|
|
351
|
+
return self.load_config()
|
|
352
|
+
return True
|
|
353
|
+
|
|
354
|
+
def _validate_config_structure(self, data: dict[str, Any]):
|
|
355
|
+
"""Validate configuration file structure"""
|
|
356
|
+
required_sections = ["server_config", "ssh_config"]
|
|
357
|
+
for section in required_sections:
|
|
358
|
+
if section not in data:
|
|
359
|
+
raise ValueError(f"Missing required configuration section: {section}")
|
|
360
|
+
|
|
361
|
+
def _create_default_config(self):
|
|
362
|
+
"""Create default configuration file"""
|
|
363
|
+
default_config = {
|
|
364
|
+
"server_config": asdict(self.server_config),
|
|
365
|
+
"ssh_config": asdict(self.ssh_config),
|
|
366
|
+
"cloudflare_config": asdict(self.cloudflare_config),
|
|
367
|
+
"security_config": asdict(self.security_config),
|
|
368
|
+
"endpoints": [],
|
|
369
|
+
"created": datetime.now().isoformat(),
|
|
370
|
+
"version": "1.0.0",
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
# Create directory if it doesn't exist
|
|
374
|
+
try:
|
|
375
|
+
self.config_file.parent.mkdir(parents=True, exist_ok=True)
|
|
376
|
+
except (OSError, PermissionError):
|
|
377
|
+
# If we can't create the directory, try current directory
|
|
378
|
+
self.config_file = Path(self.config_file.name)
|
|
379
|
+
|
|
380
|
+
with open(self.config_file, "w", encoding="utf-8") as f:
|
|
381
|
+
json.dump(default_config, f, indent=2, ensure_ascii=False)
|
|
382
|
+
|
|
383
|
+
logger.info(f"Created default configuration: {self.config_file}")
|
|
384
|
+
|
|
385
|
+
def _calculate_config_hash(self, data: dict[str, Any]) -> str:
|
|
386
|
+
"""Calculate hash of configuration data for change detection"""
|
|
387
|
+
import hashlib
|
|
388
|
+
|
|
389
|
+
config_str = json.dumps(data, sort_keys=True)
|
|
390
|
+
return hashlib.sha256(config_str.encode()).hexdigest()
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
# Global configuration manager instance
|
|
394
|
+
config_manager = ConfigManager()
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
Streamable HTTP MCP server for AI Agent Hardware Access.
|
|
4
|
+
|
|
5
|
+
This keeps the existing low-level MCP tool implementation intact and exposes it
|
|
6
|
+
at a URL, normally http://127.0.0.1:8765/mcp or a public tunnel URL.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import argparse
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import platform
|
|
13
|
+
import secrets
|
|
14
|
+
import socket
|
|
15
|
+
import sys
|
|
16
|
+
from contextlib import asynccontextmanager
|
|
17
|
+
from datetime import datetime
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
import uvicorn
|
|
22
|
+
from mcp.server.streamable_http_manager import StreamableHTTPSessionManager
|
|
23
|
+
from starlette.applications import Starlette
|
|
24
|
+
from starlette.requests import Request
|
|
25
|
+
from starlette.responses import JSONResponse, PlainTextResponse
|
|
26
|
+
from starlette.routing import Route
|
|
27
|
+
|
|
28
|
+
from .server import server
|
|
29
|
+
|
|
30
|
+
DEFAULT_HOST = "127.0.0.1"
|
|
31
|
+
DEFAULT_PORT = 8765
|
|
32
|
+
DEFAULT_PATH = "/mcp"
|
|
33
|
+
DEFAULT_CONNECTION_FILE = "ai_agent_connection.json"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class BearerAuthASGIApp:
|
|
37
|
+
"""Protect an ASGI app with a static bearer token."""
|
|
38
|
+
|
|
39
|
+
def __init__(self, app, token: str):
|
|
40
|
+
self.app = app
|
|
41
|
+
self.expected = f"Bearer {token}".encode()
|
|
42
|
+
|
|
43
|
+
async def __call__(self, scope, receive, send) -> None:
|
|
44
|
+
headers = dict(scope.get("headers") or [])
|
|
45
|
+
if headers.get(b"authorization") != self.expected:
|
|
46
|
+
response = JSONResponse({"error": "unauthorized"}, status_code=401)
|
|
47
|
+
await response(scope, receive, send)
|
|
48
|
+
return
|
|
49
|
+
await self.app(scope, receive, send)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class StreamableHTTPASGIApp:
|
|
53
|
+
"""Small ASGI adapter for the MCP streamable HTTP session manager."""
|
|
54
|
+
|
|
55
|
+
def __init__(self, session_manager: StreamableHTTPSessionManager):
|
|
56
|
+
self.session_manager = session_manager
|
|
57
|
+
|
|
58
|
+
async def __call__(self, scope, receive, send) -> None:
|
|
59
|
+
await self.session_manager.handle_request(scope, receive, send)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def normalize_path(path: str) -> str:
|
|
63
|
+
if not path:
|
|
64
|
+
return DEFAULT_PATH
|
|
65
|
+
return path if path.startswith("/") else f"/{path}"
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def local_url(host: str, port: int, path: str) -> str:
|
|
69
|
+
display_host = "127.0.0.1" if host in {"0.0.0.0", "::"} else host
|
|
70
|
+
return f"http://{display_host}:{port}{normalize_path(path)}"
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def health_url_from_mcp_url(mcp_url: str, path: str) -> str:
|
|
74
|
+
normalized = normalize_path(path)
|
|
75
|
+
if mcp_url.endswith(normalized):
|
|
76
|
+
return mcp_url[: -len(normalized)] + "/health"
|
|
77
|
+
return mcp_url.rstrip("/") + "/health"
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def get_hardware_summary() -> dict[str, Any]:
|
|
81
|
+
gpu_info: list[str] = []
|
|
82
|
+
return {
|
|
83
|
+
"cpu_count": os.cpu_count() or 0,
|
|
84
|
+
"gpu_info": gpu_info,
|
|
85
|
+
"platform": platform.system(),
|
|
86
|
+
"architecture": platform.machine(),
|
|
87
|
+
"hostname": socket.gethostname(),
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def build_connection_data(
|
|
92
|
+
mcp_url: str,
|
|
93
|
+
host: str,
|
|
94
|
+
port: int,
|
|
95
|
+
path: str,
|
|
96
|
+
auth_token: str | None = None,
|
|
97
|
+
) -> dict[str, Any]:
|
|
98
|
+
headers = {"Authorization": f"Bearer {auth_token}"} if auth_token else {}
|
|
99
|
+
return {
|
|
100
|
+
"mcp_server_type": "hardware_access",
|
|
101
|
+
"connection_method": "mcp_streamable_http",
|
|
102
|
+
"mcp_server_url": mcp_url,
|
|
103
|
+
"mcp": {
|
|
104
|
+
"transport": "streamable-http",
|
|
105
|
+
"url": mcp_url,
|
|
106
|
+
"health_url": health_url_from_mcp_url(mcp_url, path),
|
|
107
|
+
"headers": headers,
|
|
108
|
+
},
|
|
109
|
+
"capabilities": [
|
|
110
|
+
"command_execution",
|
|
111
|
+
"file_operations",
|
|
112
|
+
"docker_management",
|
|
113
|
+
"environment_setup",
|
|
114
|
+
"system_monitoring",
|
|
115
|
+
"package_installation",
|
|
116
|
+
"hardware_access",
|
|
117
|
+
"terminal_sessions",
|
|
118
|
+
],
|
|
119
|
+
"security": {
|
|
120
|
+
"ai_agent_mode": True,
|
|
121
|
+
"bypass_security_available": True,
|
|
122
|
+
"audit_log": "mcp-hardware-server.log",
|
|
123
|
+
"bind_host": host,
|
|
124
|
+
"port": port,
|
|
125
|
+
"auth": "bearer" if auth_token else "none",
|
|
126
|
+
},
|
|
127
|
+
"hardware_info": get_hardware_summary(),
|
|
128
|
+
"agent_instructions": [
|
|
129
|
+
"Configure the agent MCP client with mcp.url using streamable-http transport.",
|
|
130
|
+
"Call manage_tunnels/add if remote SSH endpoints should be registered.",
|
|
131
|
+
"Call manage_tunnels/list or system_monitoring to verify connectivity before heavy work.",
|
|
132
|
+
],
|
|
133
|
+
"setup_date": datetime.now().isoformat(),
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def write_connection_file(
|
|
138
|
+
path: str | Path,
|
|
139
|
+
mcp_url: str,
|
|
140
|
+
host: str,
|
|
141
|
+
port: int,
|
|
142
|
+
mcp_path: str,
|
|
143
|
+
auth_token: str | None = None,
|
|
144
|
+
) -> None:
|
|
145
|
+
connection_path = Path(path)
|
|
146
|
+
connection_path.write_text(
|
|
147
|
+
json.dumps(build_connection_data(mcp_url, host, port, mcp_path, auth_token), indent=2),
|
|
148
|
+
encoding="utf-8",
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def create_app(
|
|
153
|
+
*,
|
|
154
|
+
host: str = DEFAULT_HOST,
|
|
155
|
+
port: int = DEFAULT_PORT,
|
|
156
|
+
path: str = DEFAULT_PATH,
|
|
157
|
+
public_url: str | None = None,
|
|
158
|
+
connection_file: str | Path | None = None,
|
|
159
|
+
auth_token: str | None = None,
|
|
160
|
+
json_response: bool = False,
|
|
161
|
+
stateless: bool = False,
|
|
162
|
+
) -> Starlette:
|
|
163
|
+
path = normalize_path(path)
|
|
164
|
+
mcp_url = public_url or local_url(host, port, path)
|
|
165
|
+
|
|
166
|
+
if connection_file:
|
|
167
|
+
write_connection_file(connection_file, mcp_url, host, port, path, auth_token)
|
|
168
|
+
|
|
169
|
+
session_manager = StreamableHTTPSessionManager(
|
|
170
|
+
app=server,
|
|
171
|
+
json_response=json_response,
|
|
172
|
+
stateless=stateless,
|
|
173
|
+
)
|
|
174
|
+
mcp_app = StreamableHTTPASGIApp(session_manager)
|
|
175
|
+
protected_mcp_app = BearerAuthASGIApp(mcp_app, auth_token) if auth_token else mcp_app
|
|
176
|
+
|
|
177
|
+
async def health(_: Request) -> JSONResponse:
|
|
178
|
+
return JSONResponse(
|
|
179
|
+
{
|
|
180
|
+
"status": "ok",
|
|
181
|
+
"server": "enhanced-hardware-server",
|
|
182
|
+
"transport": "streamable-http",
|
|
183
|
+
"mcp_url": mcp_url,
|
|
184
|
+
"mcp_path": path,
|
|
185
|
+
}
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
async def connection(_: Request) -> JSONResponse:
|
|
189
|
+
return JSONResponse(build_connection_data(mcp_url, host, port, path, auth_token))
|
|
190
|
+
|
|
191
|
+
async def root(_: Request) -> PlainTextResponse:
|
|
192
|
+
return PlainTextResponse(
|
|
193
|
+
"AI Agent Hardware Access MCP server\n"
|
|
194
|
+
f"MCP endpoint: {mcp_url}\n"
|
|
195
|
+
f"Health: {health_url_from_mcp_url(mcp_url, path)}\n"
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
@asynccontextmanager
|
|
199
|
+
async def lifespan(_: Starlette):
|
|
200
|
+
async with session_manager.run():
|
|
201
|
+
yield
|
|
202
|
+
|
|
203
|
+
return Starlette(
|
|
204
|
+
routes=[
|
|
205
|
+
Route("/", endpoint=root, methods=["GET"]),
|
|
206
|
+
Route("/health", endpoint=health, methods=["GET"]),
|
|
207
|
+
Route("/connection.json", endpoint=connection, methods=["GET"]),
|
|
208
|
+
Route(path, endpoint=protected_mcp_app, methods=["GET", "POST", "DELETE"]),
|
|
209
|
+
],
|
|
210
|
+
lifespan=lifespan,
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
|
|
215
|
+
parser = argparse.ArgumentParser(description="Run the hardware MCP server over Streamable HTTP")
|
|
216
|
+
parser.add_argument("--host", default=DEFAULT_HOST, help="Bind host, default: 127.0.0.1")
|
|
217
|
+
parser.add_argument("--port", type=int, default=DEFAULT_PORT, help="Bind port, default: 8765")
|
|
218
|
+
parser.add_argument("--path", default=DEFAULT_PATH, help="MCP path, default: /mcp")
|
|
219
|
+
parser.add_argument("--public-url", help="Public MCP URL to write into connection files")
|
|
220
|
+
parser.add_argument("--connection-file", default=DEFAULT_CONNECTION_FILE)
|
|
221
|
+
parser.add_argument("--auth-token", help="Bearer token required for MCP requests")
|
|
222
|
+
parser.add_argument(
|
|
223
|
+
"--generate-token", action="store_true", help="Generate a bearer token and write it to the connection file"
|
|
224
|
+
)
|
|
225
|
+
parser.add_argument("--no-write-connection", action="store_true")
|
|
226
|
+
parser.add_argument("--json-response", action="store_true", help="Use JSON responses instead of SSE streams")
|
|
227
|
+
parser.add_argument("--stateless", action="store_true", help="Use stateless HTTP sessions")
|
|
228
|
+
return parser.parse_args(argv)
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def main(argv: list[str] | None = None) -> int:
|
|
232
|
+
args = parse_args(argv)
|
|
233
|
+
mcp_path = normalize_path(args.path)
|
|
234
|
+
mcp_url = args.public_url or local_url(args.host, args.port, mcp_path)
|
|
235
|
+
connection_file = None if args.no_write_connection else args.connection_file
|
|
236
|
+
auth_token = args.auth_token or (secrets.token_urlsafe(32) if args.generate_token else None)
|
|
237
|
+
|
|
238
|
+
app = create_app(
|
|
239
|
+
host=args.host,
|
|
240
|
+
port=args.port,
|
|
241
|
+
path=mcp_path,
|
|
242
|
+
public_url=mcp_url,
|
|
243
|
+
connection_file=connection_file,
|
|
244
|
+
auth_token=auth_token,
|
|
245
|
+
json_response=args.json_response,
|
|
246
|
+
stateless=args.stateless,
|
|
247
|
+
)
|
|
248
|
+
|
|
249
|
+
print("AI Agent Hardware Access MCP server")
|
|
250
|
+
print(f"MCP URL: {mcp_url}")
|
|
251
|
+
print(f"Health: {health_url_from_mcp_url(mcp_url, mcp_path)}")
|
|
252
|
+
if connection_file:
|
|
253
|
+
print(f"Connection file: {Path(connection_file).resolve()}")
|
|
254
|
+
if auth_token:
|
|
255
|
+
print("Auth: bearer token written to connection file")
|
|
256
|
+
|
|
257
|
+
uvicorn.run(app, host=args.host, port=args.port, log_level="info")
|
|
258
|
+
return 0
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
if __name__ == "__main__":
|
|
262
|
+
sys.exit(main())
|