mcpshield-agent 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.
- mcpshield_agent/__init__.py +5 -0
- mcpshield_agent/__main__.py +13 -0
- mcpshield_agent/cli.py +327 -0
- mcpshield_agent/client.py +68 -0
- mcpshield_agent/config.py +65 -0
- mcpshield_agent/reporter.py +261 -0
- mcpshield_agent/scanner.py +225 -0
- mcpshield_agent/service.py +439 -0
- mcpshield_agent-0.1.0.dist-info/METADATA +149 -0
- mcpshield_agent-0.1.0.dist-info/RECORD +13 -0
- mcpshield_agent-0.1.0.dist-info/WHEEL +5 -0
- mcpshield_agent-0.1.0.dist-info/entry_points.txt +2 -0
- mcpshield_agent-0.1.0.dist-info/top_level.txt +1 -0
mcpshield_agent/cli.py
ADDED
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
"""MCPShield Agent - CLI Interface"""
|
|
2
|
+
|
|
3
|
+
import click
|
|
4
|
+
import os
|
|
5
|
+
import socket
|
|
6
|
+
import platform
|
|
7
|
+
|
|
8
|
+
from .scanner import MCPScanner
|
|
9
|
+
from .client import MCPShieldClient
|
|
10
|
+
from .config import Config
|
|
11
|
+
from . import __version__
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@click.group()
|
|
15
|
+
@click.version_option(version=__version__, prog_name='mcpshield')
|
|
16
|
+
def cli():
|
|
17
|
+
"""MCPShield Agent - AI Agent Security Scanner
|
|
18
|
+
|
|
19
|
+
Discovers MCP servers on your system and reports them to MCPShield
|
|
20
|
+
for security analysis and risk assessment.
|
|
21
|
+
"""
|
|
22
|
+
pass
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@cli.command()
|
|
26
|
+
@click.option('--api-key', required=True, help='Your MCPShield API key from dashboard')
|
|
27
|
+
@click.option('--api-url', default='http://localhost:8000', help='API URL (default: localhost:8000)')
|
|
28
|
+
def configure(api_key: str, api_url: str):
|
|
29
|
+
"""Configure agent with API key"""
|
|
30
|
+
|
|
31
|
+
# Validate API key format
|
|
32
|
+
if not api_key.startswith('mcp_sk_'):
|
|
33
|
+
click.echo("Error: Invalid API key format. Should start with 'mcp_sk_'")
|
|
34
|
+
return
|
|
35
|
+
|
|
36
|
+
# Test connection
|
|
37
|
+
click.echo(f"Testing connection to {api_url}...")
|
|
38
|
+
client = MCPShieldClient(api_url, api_key)
|
|
39
|
+
|
|
40
|
+
if client.test_connection():
|
|
41
|
+
click.echo("Connected successfully!")
|
|
42
|
+
else:
|
|
43
|
+
click.echo(f"Warning: Could not connect to {api_url}")
|
|
44
|
+
click.echo("Saving config anyway - API might be down temporarily")
|
|
45
|
+
|
|
46
|
+
# Save config
|
|
47
|
+
config = Config.load()
|
|
48
|
+
config['api_key'] = api_key
|
|
49
|
+
config['api_url'] = api_url
|
|
50
|
+
Config.save(config)
|
|
51
|
+
|
|
52
|
+
click.echo("")
|
|
53
|
+
click.echo("Agent configured successfully!")
|
|
54
|
+
click.echo(f" API URL: {api_url}")
|
|
55
|
+
click.echo(f" Config: {Config.CONFIG_FILE}")
|
|
56
|
+
click.echo("")
|
|
57
|
+
click.echo("Next steps:")
|
|
58
|
+
click.echo(" mcpshield scan # Scan for MCP servers")
|
|
59
|
+
click.echo(" mcpshield status # Check agent status")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@cli.command()
|
|
63
|
+
@click.option('--dry-run', is_flag=True, help='Scan but do not report to API')
|
|
64
|
+
def scan(dry_run: bool):
|
|
65
|
+
"""Scan for MCP servers and report to API"""
|
|
66
|
+
|
|
67
|
+
# Load config
|
|
68
|
+
config = Config.load()
|
|
69
|
+
api_key = config.get('api_key')
|
|
70
|
+
|
|
71
|
+
if not api_key and not dry_run:
|
|
72
|
+
click.echo("Error: Not configured. Run: mcpshield configure --api-key YOUR_KEY")
|
|
73
|
+
return
|
|
74
|
+
|
|
75
|
+
# Scan for servers
|
|
76
|
+
click.echo("Scanning for MCP servers...")
|
|
77
|
+
scanner = MCPScanner()
|
|
78
|
+
servers = scanner.scan()
|
|
79
|
+
|
|
80
|
+
if not servers:
|
|
81
|
+
click.echo("No MCP servers found.")
|
|
82
|
+
click.echo("")
|
|
83
|
+
click.echo("Searched in:")
|
|
84
|
+
for path in scanner.config_paths:
|
|
85
|
+
exists = "[exists]" if path.exists() else ""
|
|
86
|
+
click.echo(f" {path} {exists}")
|
|
87
|
+
return
|
|
88
|
+
|
|
89
|
+
click.echo(f"Found {len(servers)} MCP server(s):")
|
|
90
|
+
click.echo("")
|
|
91
|
+
|
|
92
|
+
# Display found servers
|
|
93
|
+
for server in servers:
|
|
94
|
+
status_icon = "[active]" if server['status'] == 'active' else "[dormant]"
|
|
95
|
+
click.echo(f" {server['server_name']} {status_icon}")
|
|
96
|
+
click.echo(f" Type: {server['server_type']}")
|
|
97
|
+
if server.get('scope'):
|
|
98
|
+
click.echo(f" Scope: {server['scope']}")
|
|
99
|
+
if server.get('env_vars'):
|
|
100
|
+
click.echo(f" Env: {', '.join(server['env_vars'])}")
|
|
101
|
+
if server.get('source'):
|
|
102
|
+
click.echo(f" Source: {server['source']}")
|
|
103
|
+
click.echo("")
|
|
104
|
+
|
|
105
|
+
if dry_run:
|
|
106
|
+
click.echo("(Dry run - not reporting to API)")
|
|
107
|
+
return
|
|
108
|
+
|
|
109
|
+
# Report to API
|
|
110
|
+
click.echo("Reporting to MCPShield...")
|
|
111
|
+
client = MCPShieldClient(config['api_url'], api_key)
|
|
112
|
+
|
|
113
|
+
try:
|
|
114
|
+
# Send heartbeat first
|
|
115
|
+
client.heartbeat(
|
|
116
|
+
hostname=socket.gethostname(),
|
|
117
|
+
os_type=platform.system().lower(),
|
|
118
|
+
username=os.getenv('USERNAME', os.getenv('USER', 'unknown')),
|
|
119
|
+
ip_address=_get_ip_address(),
|
|
120
|
+
agent_version=__version__
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
# Report servers
|
|
124
|
+
result = client.report_servers(servers)
|
|
125
|
+
|
|
126
|
+
click.echo("")
|
|
127
|
+
click.echo("Success!")
|
|
128
|
+
click.echo(f" Created: {result.get('created', 0)}")
|
|
129
|
+
click.echo(f" Updated: {result.get('updated', 0)}")
|
|
130
|
+
click.echo(f" Alerts: {result.get('alerts', 0)}")
|
|
131
|
+
|
|
132
|
+
# Show risk info if available
|
|
133
|
+
if 'servers' in result:
|
|
134
|
+
click.echo("")
|
|
135
|
+
click.echo("Risk Assessment:")
|
|
136
|
+
for s in result['servers']:
|
|
137
|
+
risk = s.get('risk_level', 'unknown')
|
|
138
|
+
score = s.get('risk_score', 0)
|
|
139
|
+
click.echo(f" {s['server_name']}: {risk} (score: {score})")
|
|
140
|
+
|
|
141
|
+
except Exception as e:
|
|
142
|
+
click.echo(f"Error: Failed to report - {e}")
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
@cli.command()
|
|
146
|
+
def status():
|
|
147
|
+
"""Show agent configuration and status"""
|
|
148
|
+
|
|
149
|
+
config = Config.load()
|
|
150
|
+
|
|
151
|
+
click.echo("MCPShield Agent Status")
|
|
152
|
+
click.echo("=" * 50)
|
|
153
|
+
click.echo(f"Version: {__version__}")
|
|
154
|
+
click.echo(f"Config file: {Config.CONFIG_FILE}")
|
|
155
|
+
click.echo(f"API URL: {config.get('api_url', 'Not set')}")
|
|
156
|
+
|
|
157
|
+
api_key = config.get('api_key')
|
|
158
|
+
if api_key:
|
|
159
|
+
masked_key = api_key[:12] + "..." + api_key[-4:] if len(api_key) > 20 else api_key[:8] + "..."
|
|
160
|
+
click.echo(f"API Key: {masked_key}")
|
|
161
|
+
else:
|
|
162
|
+
click.echo("API Key: Not configured")
|
|
163
|
+
|
|
164
|
+
click.echo("")
|
|
165
|
+
|
|
166
|
+
# Test API connection
|
|
167
|
+
if api_key:
|
|
168
|
+
client = MCPShieldClient(config['api_url'], api_key)
|
|
169
|
+
if client.test_connection():
|
|
170
|
+
click.echo("API Status: Connected")
|
|
171
|
+
else:
|
|
172
|
+
click.echo("API Status: Cannot connect")
|
|
173
|
+
else:
|
|
174
|
+
click.echo("API Status: Not configured")
|
|
175
|
+
|
|
176
|
+
# Show config paths
|
|
177
|
+
click.echo("")
|
|
178
|
+
click.echo("MCP Config Locations:")
|
|
179
|
+
scanner = MCPScanner()
|
|
180
|
+
for path in scanner.config_paths:
|
|
181
|
+
if path.exists():
|
|
182
|
+
click.echo(f" [found] {path}")
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
@cli.command()
|
|
186
|
+
def list():
|
|
187
|
+
"""List discovered MCP servers (without reporting)"""
|
|
188
|
+
|
|
189
|
+
click.echo("Scanning for MCP servers...")
|
|
190
|
+
scanner = MCPScanner()
|
|
191
|
+
servers = scanner.scan()
|
|
192
|
+
|
|
193
|
+
if not servers:
|
|
194
|
+
click.echo("No MCP servers found.")
|
|
195
|
+
return
|
|
196
|
+
|
|
197
|
+
click.echo(f"Found {len(servers)} MCP server(s):")
|
|
198
|
+
click.echo("")
|
|
199
|
+
|
|
200
|
+
for i, server in enumerate(servers, 1):
|
|
201
|
+
click.echo(f"{i}. {server['server_name']}")
|
|
202
|
+
click.echo(f" Type: {server['server_type']}")
|
|
203
|
+
click.echo(f" Status: {server['status']}")
|
|
204
|
+
if server.get('scope'):
|
|
205
|
+
click.echo(f" Scope: {server['scope']}")
|
|
206
|
+
if server.get('source'):
|
|
207
|
+
click.echo(f" Source: {server['source']}")
|
|
208
|
+
click.echo("")
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
@cli.command()
|
|
212
|
+
@click.option('--interval', default=None, type=int, help='Scan interval in seconds (default: from config, or 3600)')
|
|
213
|
+
def daemon(interval: int):
|
|
214
|
+
"""Run continuous scanning on a schedule.
|
|
215
|
+
|
|
216
|
+
Automatically scans for MCP servers and reports to the backend
|
|
217
|
+
at regular intervals. Press Ctrl+C to stop.
|
|
218
|
+
"""
|
|
219
|
+
import time
|
|
220
|
+
import signal
|
|
221
|
+
import sys
|
|
222
|
+
|
|
223
|
+
config = Config.load()
|
|
224
|
+
|
|
225
|
+
if not Config.is_configured():
|
|
226
|
+
click.echo("Error: Agent not configured. Run 'mcpshield configure' first.")
|
|
227
|
+
sys.exit(1)
|
|
228
|
+
|
|
229
|
+
scan_interval = interval or config.get('scan_interval', 3600)
|
|
230
|
+
|
|
231
|
+
click.echo(f"Starting MCPShield daemon (scanning every {scan_interval}s)")
|
|
232
|
+
click.echo("Press Ctrl+C to stop.\n")
|
|
233
|
+
|
|
234
|
+
running = True
|
|
235
|
+
|
|
236
|
+
def handle_signal(signum, frame):
|
|
237
|
+
nonlocal running
|
|
238
|
+
click.echo("\nShutting down daemon...")
|
|
239
|
+
running = False
|
|
240
|
+
|
|
241
|
+
signal.signal(signal.SIGINT, handle_signal)
|
|
242
|
+
signal.signal(signal.SIGTERM, handle_signal)
|
|
243
|
+
|
|
244
|
+
client = MCPShieldClient(config['api_url'], config['api_key'])
|
|
245
|
+
scanner = MCPScanner()
|
|
246
|
+
cycle = 0
|
|
247
|
+
|
|
248
|
+
while running:
|
|
249
|
+
cycle += 1
|
|
250
|
+
click.echo(f"[Cycle {cycle}] Scanning for MCP servers...")
|
|
251
|
+
|
|
252
|
+
try:
|
|
253
|
+
servers = scanner.scan()
|
|
254
|
+
click.echo(f"[Cycle {cycle}] Found {len(servers)} MCP server(s)")
|
|
255
|
+
|
|
256
|
+
if servers:
|
|
257
|
+
# Send heartbeat
|
|
258
|
+
import platform
|
|
259
|
+
import socket
|
|
260
|
+
hostname = platform.node()
|
|
261
|
+
os_type = platform.system().lower()
|
|
262
|
+
username = os.getenv('USER') or os.getenv('USERNAME') or 'unknown'
|
|
263
|
+
|
|
264
|
+
# Get IP with fallback
|
|
265
|
+
ip = "127.0.0.1"
|
|
266
|
+
try:
|
|
267
|
+
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
268
|
+
for target in [("8.8.8.8", 80), ("1.1.1.1", 80)]:
|
|
269
|
+
try:
|
|
270
|
+
s.connect(target)
|
|
271
|
+
ip = s.getsockname()[0]
|
|
272
|
+
break
|
|
273
|
+
except Exception:
|
|
274
|
+
continue
|
|
275
|
+
s.close()
|
|
276
|
+
except Exception:
|
|
277
|
+
pass
|
|
278
|
+
|
|
279
|
+
client.heartbeat(hostname, os_type, username, ip, __version__)
|
|
280
|
+
result = client.report_servers(servers)
|
|
281
|
+
|
|
282
|
+
if result:
|
|
283
|
+
click.echo(f"[Cycle {cycle}] Reported to backend successfully")
|
|
284
|
+
else:
|
|
285
|
+
click.echo(f"[Cycle {cycle}] Warning: Failed to report to backend")
|
|
286
|
+
else:
|
|
287
|
+
click.echo(f"[Cycle {cycle}] No servers found")
|
|
288
|
+
|
|
289
|
+
except Exception as e:
|
|
290
|
+
click.echo(f"[Cycle {cycle}] Error during scan: {e}")
|
|
291
|
+
|
|
292
|
+
click.echo(f"[Cycle {cycle}] Next scan in {scan_interval}s\n")
|
|
293
|
+
|
|
294
|
+
# Sleep in small increments to allow clean shutdown
|
|
295
|
+
elapsed = 0
|
|
296
|
+
while running and elapsed < scan_interval:
|
|
297
|
+
time.sleep(min(1, scan_interval - elapsed))
|
|
298
|
+
elapsed += 1
|
|
299
|
+
|
|
300
|
+
click.echo("Daemon stopped.")
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _get_ip_address() -> str:
|
|
304
|
+
"""Get local IP address"""
|
|
305
|
+
ip = "127.0.0.1"
|
|
306
|
+
try:
|
|
307
|
+
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
308
|
+
for target in [("8.8.8.8", 80), ("1.1.1.1", 80)]:
|
|
309
|
+
try:
|
|
310
|
+
s.connect(target)
|
|
311
|
+
ip = s.getsockname()[0]
|
|
312
|
+
break
|
|
313
|
+
except Exception:
|
|
314
|
+
continue
|
|
315
|
+
s.close()
|
|
316
|
+
except Exception:
|
|
317
|
+
pass
|
|
318
|
+
return ip
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def main():
|
|
322
|
+
"""Entry point for CLI"""
|
|
323
|
+
cli()
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
if __name__ == '__main__':
|
|
327
|
+
main()
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""MCPShield Agent - API Client"""
|
|
2
|
+
|
|
3
|
+
import requests
|
|
4
|
+
from typing import Dict, List, Optional
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class MCPShieldClient:
|
|
8
|
+
"""HTTP client for MCPShield API"""
|
|
9
|
+
|
|
10
|
+
def __init__(self, api_url: str = "http://localhost:8000", api_key: Optional[str] = None):
|
|
11
|
+
self.api_url = api_url.rstrip('/')
|
|
12
|
+
self.api_key = api_key
|
|
13
|
+
self.session = requests.Session()
|
|
14
|
+
self.session.headers['Content-Type'] = 'application/json'
|
|
15
|
+
|
|
16
|
+
if api_key:
|
|
17
|
+
self.session.headers['X-API-Key'] = api_key
|
|
18
|
+
|
|
19
|
+
def test_connection(self) -> bool:
|
|
20
|
+
"""Test if API is reachable"""
|
|
21
|
+
try:
|
|
22
|
+
response = self.session.get(f"{self.api_url}/health", timeout=5)
|
|
23
|
+
return response.status_code == 200
|
|
24
|
+
except Exception:
|
|
25
|
+
return False
|
|
26
|
+
|
|
27
|
+
def heartbeat(self, hostname: str, os_type: str, username: str,
|
|
28
|
+
ip_address: str, agent_version: str) -> Dict:
|
|
29
|
+
"""
|
|
30
|
+
Send heartbeat to update agent status.
|
|
31
|
+
|
|
32
|
+
POST /api/v1/agents/heartbeat
|
|
33
|
+
"""
|
|
34
|
+
url = f"{self.api_url}/api/v1/agents/heartbeat"
|
|
35
|
+
|
|
36
|
+
payload = {
|
|
37
|
+
"hostname": hostname,
|
|
38
|
+
"os_type": os_type,
|
|
39
|
+
"username": username,
|
|
40
|
+
"ip_address": ip_address,
|
|
41
|
+
"agent_version": agent_version
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
response = self.session.post(url, json=payload, timeout=30)
|
|
45
|
+
response.raise_for_status()
|
|
46
|
+
return response.json()
|
|
47
|
+
|
|
48
|
+
def report_servers(self, servers: List[Dict]) -> Dict:
|
|
49
|
+
"""
|
|
50
|
+
Report discovered MCP servers.
|
|
51
|
+
|
|
52
|
+
POST /api/v1/mcp/report
|
|
53
|
+
"""
|
|
54
|
+
url = f"{self.api_url}/api/v1/mcp/report"
|
|
55
|
+
|
|
56
|
+
payload = {"servers": servers}
|
|
57
|
+
|
|
58
|
+
response = self.session.post(url, json=payload, timeout=30)
|
|
59
|
+
response.raise_for_status()
|
|
60
|
+
return response.json()
|
|
61
|
+
|
|
62
|
+
def get_api_status(self) -> Dict:
|
|
63
|
+
"""Get API health status"""
|
|
64
|
+
try:
|
|
65
|
+
response = self.session.get(f"{self.api_url}/health", timeout=5)
|
|
66
|
+
return response.json()
|
|
67
|
+
except Exception as e:
|
|
68
|
+
return {"status": "error", "message": str(e)}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""MCPShield Agent - Configuration Management"""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import platform
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Dict
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Config:
|
|
11
|
+
"""Manage agent configuration with platform-appropriate paths."""
|
|
12
|
+
|
|
13
|
+
# Platform-specific config directory
|
|
14
|
+
_system = platform.system()
|
|
15
|
+
if _system == "Windows":
|
|
16
|
+
CONFIG_DIR = Path(os.getenv('LOCALAPPDATA', Path.home())) / 'MCPShield'
|
|
17
|
+
elif _system == "Darwin":
|
|
18
|
+
CONFIG_DIR = Path.home() / 'Library' / 'Application Support' / 'MCPShield'
|
|
19
|
+
else: # Linux and other Unix
|
|
20
|
+
CONFIG_DIR = Path(os.getenv('XDG_CONFIG_HOME', str(Path.home() / '.config'))) / 'mcpshield'
|
|
21
|
+
CONFIG_FILE = CONFIG_DIR / 'config.json'
|
|
22
|
+
LOG_FILE = CONFIG_DIR / 'agent.log'
|
|
23
|
+
|
|
24
|
+
@classmethod
|
|
25
|
+
def load(cls) -> Dict:
|
|
26
|
+
"""Load config from file, or return defaults"""
|
|
27
|
+
if not cls.CONFIG_FILE.exists():
|
|
28
|
+
return cls.default_config()
|
|
29
|
+
|
|
30
|
+
try:
|
|
31
|
+
with open(cls.CONFIG_FILE, 'r', encoding='utf-8') as f:
|
|
32
|
+
config = json.load(f)
|
|
33
|
+
# Merge with defaults to ensure all keys exist
|
|
34
|
+
defaults = cls.default_config()
|
|
35
|
+
defaults.update(config)
|
|
36
|
+
return defaults
|
|
37
|
+
except Exception:
|
|
38
|
+
return cls.default_config()
|
|
39
|
+
|
|
40
|
+
@classmethod
|
|
41
|
+
def save(cls, config: Dict):
|
|
42
|
+
"""Save config to file"""
|
|
43
|
+
cls.CONFIG_DIR.mkdir(parents=True, exist_ok=True)
|
|
44
|
+
|
|
45
|
+
with open(cls.CONFIG_FILE, 'w', encoding='utf-8') as f:
|
|
46
|
+
json.dump(config, f, indent=2)
|
|
47
|
+
|
|
48
|
+
@classmethod
|
|
49
|
+
def default_config(cls) -> Dict:
|
|
50
|
+
"""Default configuration"""
|
|
51
|
+
return {
|
|
52
|
+
"api_url": "http://localhost:8000",
|
|
53
|
+
"api_key": None,
|
|
54
|
+
"log_level": "INFO"
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
@classmethod
|
|
58
|
+
def get_api_key(cls) -> str:
|
|
59
|
+
"""Get API key from config"""
|
|
60
|
+
return cls.load().get('api_key')
|
|
61
|
+
|
|
62
|
+
@classmethod
|
|
63
|
+
def is_configured(cls) -> bool:
|
|
64
|
+
"""Check if agent is configured with API key"""
|
|
65
|
+
return bool(cls.get_api_key())
|