mcpshield-agent 0.1.2__tar.gz → 0.2.0__tar.gz
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-0.1.2 → mcpshield_agent-0.2.0}/PKG-INFO +5 -1
- {mcpshield_agent-0.1.2 → mcpshield_agent-0.2.0}/mcpshield_agent/__init__.py +1 -1
- {mcpshield_agent-0.1.2 → mcpshield_agent-0.2.0}/mcpshield_agent/cli.py +59 -13
- {mcpshield_agent-0.1.2 → mcpshield_agent-0.2.0}/mcpshield_agent/config.py +16 -4
- mcpshield_agent-0.2.0/mcpshield_agent/tool_scanner.py +248 -0
- {mcpshield_agent-0.1.2 → mcpshield_agent-0.2.0}/mcpshield_agent.egg-info/PKG-INFO +5 -1
- {mcpshield_agent-0.1.2 → mcpshield_agent-0.2.0}/mcpshield_agent.egg-info/SOURCES.txt +1 -2
- mcpshield_agent-0.2.0/mcpshield_agent.egg-info/requires.txt +8 -0
- {mcpshield_agent-0.1.2 → mcpshield_agent-0.2.0}/pyproject.toml +7 -0
- mcpshield_agent-0.1.2/mcpshield_agent/reporter.py +0 -261
- mcpshield_agent-0.1.2/mcpshield_agent/service.py +0 -453
- mcpshield_agent-0.1.2/mcpshield_agent.egg-info/requires.txt +0 -3
- {mcpshield_agent-0.1.2 → mcpshield_agent-0.2.0}/README.md +0 -0
- {mcpshield_agent-0.1.2 → mcpshield_agent-0.2.0}/mcpshield_agent/__main__.py +0 -0
- {mcpshield_agent-0.1.2 → mcpshield_agent-0.2.0}/mcpshield_agent/client.py +0 -0
- {mcpshield_agent-0.1.2 → mcpshield_agent-0.2.0}/mcpshield_agent/scanner.py +0 -0
- {mcpshield_agent-0.1.2 → mcpshield_agent-0.2.0}/mcpshield_agent.egg-info/dependency_links.txt +0 -0
- {mcpshield_agent-0.1.2 → mcpshield_agent-0.2.0}/mcpshield_agent.egg-info/entry_points.txt +0 -0
- {mcpshield_agent-0.1.2 → mcpshield_agent-0.2.0}/mcpshield_agent.egg-info/top_level.txt +0 -0
- {mcpshield_agent-0.1.2 → mcpshield_agent-0.2.0}/setup.cfg +0 -0
- {mcpshield_agent-0.1.2 → mcpshield_agent-0.2.0}/tests/test_cli.py +0 -0
- {mcpshield_agent-0.1.2 → mcpshield_agent-0.2.0}/tests/test_scanner.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: mcpshield-agent
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0
|
|
4
4
|
Summary: MCPShield Agent - AI Agent Security Scanner for MCP servers
|
|
5
5
|
Author-email: David Cooper <hello@mcpshield.app>
|
|
6
6
|
License-Expression: MIT
|
|
@@ -24,6 +24,10 @@ Description-Content-Type: text/markdown
|
|
|
24
24
|
Requires-Dist: click>=8.1.0
|
|
25
25
|
Requires-Dist: requests>=2.31.0
|
|
26
26
|
Requires-Dist: psutil>=5.9.0
|
|
27
|
+
Provides-Extra: dev
|
|
28
|
+
Requires-Dist: pytest>=7.4.0; extra == "dev"
|
|
29
|
+
Requires-Dist: pytest-cov>=4.1.0; extra == "dev"
|
|
30
|
+
Requires-Dist: pytest-asyncio>=0.23.0; extra == "dev"
|
|
27
31
|
|
|
28
32
|
# MCPShield Agent
|
|
29
33
|
|
|
@@ -8,6 +8,7 @@ import platform
|
|
|
8
8
|
from .scanner import MCPScanner
|
|
9
9
|
from .client import MCPShieldClient
|
|
10
10
|
from .config import Config
|
|
11
|
+
from .tool_scanner import deep_scan
|
|
11
12
|
from . import __version__
|
|
12
13
|
|
|
13
14
|
|
|
@@ -61,22 +62,23 @@ def configure(api_key: str, api_url: str):
|
|
|
61
62
|
|
|
62
63
|
@cli.command()
|
|
63
64
|
@click.option('--dry-run', is_flag=True, help='Scan but do not report to API')
|
|
64
|
-
|
|
65
|
+
@click.option('--deep', is_flag=True, help='Connect to each active server, fetch its tool list, and scan descriptions for injected instructions')
|
|
66
|
+
def scan(dry_run: bool, deep: bool):
|
|
65
67
|
"""Scan for MCP servers and report to API"""
|
|
66
|
-
|
|
68
|
+
|
|
67
69
|
# Load config
|
|
68
70
|
config = Config.load()
|
|
69
71
|
api_key = config.get('api_key')
|
|
70
|
-
|
|
72
|
+
|
|
71
73
|
if not api_key and not dry_run:
|
|
72
74
|
click.echo("Error: Not configured. Run: mcpshield configure --api-key YOUR_KEY")
|
|
73
75
|
return
|
|
74
|
-
|
|
76
|
+
|
|
75
77
|
# Scan for servers
|
|
76
78
|
click.echo("Scanning for MCP servers...")
|
|
77
79
|
scanner = MCPScanner()
|
|
78
80
|
servers = scanner.scan()
|
|
79
|
-
|
|
81
|
+
|
|
80
82
|
if not servers:
|
|
81
83
|
click.echo("No MCP servers found.")
|
|
82
84
|
click.echo("")
|
|
@@ -85,10 +87,23 @@ def scan(dry_run: bool):
|
|
|
85
87
|
exists = "[exists]" if path.exists() else ""
|
|
86
88
|
click.echo(f" {path} {exists}")
|
|
87
89
|
return
|
|
88
|
-
|
|
90
|
+
|
|
91
|
+
# Deep scan: connect to each active server and inspect tool descriptions
|
|
92
|
+
if deep:
|
|
93
|
+
click.echo("Running deep scan (connecting to active servers)...")
|
|
94
|
+
for server in servers:
|
|
95
|
+
if server.get('status') == 'active':
|
|
96
|
+
result = deep_scan(server)
|
|
97
|
+
server['tools'] = result['tools']
|
|
98
|
+
server['tool_count'] = result['tool_count']
|
|
99
|
+
server['tool_findings'] = result['tool_findings']
|
|
100
|
+
if result['scan_error']:
|
|
101
|
+
server['scan_error'] = result['scan_error']
|
|
102
|
+
click.echo("")
|
|
103
|
+
|
|
89
104
|
click.echo(f"Found {len(servers)} MCP server(s):")
|
|
90
105
|
click.echo("")
|
|
91
|
-
|
|
106
|
+
|
|
92
107
|
# Display found servers
|
|
93
108
|
for server in servers:
|
|
94
109
|
status_icon = "[active]" if server['status'] == 'active' else "[dormant]"
|
|
@@ -100,8 +115,22 @@ def scan(dry_run: bool):
|
|
|
100
115
|
click.echo(f" Env: {', '.join(server['env_vars'])}")
|
|
101
116
|
if server.get('source'):
|
|
102
117
|
click.echo(f" Source: {server['source']}")
|
|
118
|
+
if deep:
|
|
119
|
+
tool_count = server.get('tool_count')
|
|
120
|
+
findings = server.get('tool_findings', [])
|
|
121
|
+
scan_error = server.get('scan_error')
|
|
122
|
+
if scan_error:
|
|
123
|
+
click.echo(f" Tools: (could not connect: {scan_error})")
|
|
124
|
+
elif tool_count is not None:
|
|
125
|
+
click.echo(f" Tools: {tool_count} exposed")
|
|
126
|
+
if findings:
|
|
127
|
+
click.echo(f" ⚠️ {len(findings)} suspicious tool(s):")
|
|
128
|
+
for f in findings:
|
|
129
|
+
click.echo(f" - {f['tool']} (score: {f['score']:.2f})")
|
|
130
|
+
for reason in f['reasons']:
|
|
131
|
+
click.echo(f" {reason}")
|
|
103
132
|
click.echo("")
|
|
104
|
-
|
|
133
|
+
|
|
105
134
|
if dry_run:
|
|
106
135
|
click.echo("(Dry run - not reporting to API)")
|
|
107
136
|
return
|
|
@@ -183,20 +212,28 @@ def status():
|
|
|
183
212
|
|
|
184
213
|
|
|
185
214
|
@cli.command()
|
|
186
|
-
|
|
215
|
+
@click.option('--deep', is_flag=True, help='Connect to each active server and scan tool descriptions for injected instructions')
|
|
216
|
+
def list(deep: bool):
|
|
187
217
|
"""List discovered MCP servers (without reporting)"""
|
|
188
|
-
|
|
218
|
+
|
|
189
219
|
click.echo("Scanning for MCP servers...")
|
|
190
220
|
scanner = MCPScanner()
|
|
191
221
|
servers = scanner.scan()
|
|
192
|
-
|
|
222
|
+
|
|
193
223
|
if not servers:
|
|
194
224
|
click.echo("No MCP servers found.")
|
|
195
225
|
return
|
|
196
|
-
|
|
226
|
+
|
|
227
|
+
if deep:
|
|
228
|
+
click.echo("Running deep scan (connecting to active servers)...")
|
|
229
|
+
for server in servers:
|
|
230
|
+
if server.get('status') == 'active':
|
|
231
|
+
result = deep_scan(server)
|
|
232
|
+
server.update(result)
|
|
233
|
+
|
|
197
234
|
click.echo(f"Found {len(servers)} MCP server(s):")
|
|
198
235
|
click.echo("")
|
|
199
|
-
|
|
236
|
+
|
|
200
237
|
for i, server in enumerate(servers, 1):
|
|
201
238
|
click.echo(f"{i}. {server['server_name']}")
|
|
202
239
|
click.echo(f" Type: {server['server_type']}")
|
|
@@ -205,6 +242,15 @@ def list():
|
|
|
205
242
|
click.echo(f" Scope: {server['scope']}")
|
|
206
243
|
if server.get('source'):
|
|
207
244
|
click.echo(f" Source: {server['source']}")
|
|
245
|
+
if deep:
|
|
246
|
+
findings = server.get('tool_findings', [])
|
|
247
|
+
scan_error = server.get('scan_error')
|
|
248
|
+
if scan_error:
|
|
249
|
+
click.echo(f" Tools: (could not connect: {scan_error})")
|
|
250
|
+
elif server.get('tool_count') is not None:
|
|
251
|
+
click.echo(f" Tools: {server['tool_count']} exposed")
|
|
252
|
+
if findings:
|
|
253
|
+
click.echo(f" ⚠️ {len(findings)} suspicious tool(s): {', '.join(f['tool'] for f in findings)}")
|
|
208
254
|
click.echo("")
|
|
209
255
|
|
|
210
256
|
|
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
"""MCPShield Agent - Configuration Management"""
|
|
2
2
|
|
|
3
3
|
import json
|
|
4
|
+
import logging
|
|
4
5
|
import os
|
|
5
6
|
import platform
|
|
6
7
|
from pathlib import Path
|
|
7
8
|
from typing import Dict
|
|
8
9
|
|
|
10
|
+
logger = logging.getLogger("mcpshield.config")
|
|
11
|
+
|
|
9
12
|
|
|
10
13
|
class Config:
|
|
11
14
|
"""Manage agent configuration with platform-appropriate paths."""
|
|
@@ -34,16 +37,25 @@ class Config:
|
|
|
34
37
|
defaults = cls.default_config()
|
|
35
38
|
defaults.update(config)
|
|
36
39
|
return defaults
|
|
37
|
-
except Exception:
|
|
40
|
+
except Exception as e:
|
|
41
|
+
# Surface the problem instead of silently resetting to defaults
|
|
42
|
+
# (which would drop the configured API key and API URL).
|
|
43
|
+
logger.warning("Could not read config %s: %s — using defaults", cls.CONFIG_FILE, e)
|
|
38
44
|
return cls.default_config()
|
|
39
|
-
|
|
45
|
+
|
|
40
46
|
@classmethod
|
|
41
47
|
def save(cls, config: Dict):
|
|
42
|
-
"""Save config to file"""
|
|
48
|
+
"""Save config to file with owner-only permissions (it holds the API key)."""
|
|
43
49
|
cls.CONFIG_DIR.mkdir(parents=True, exist_ok=True)
|
|
44
|
-
|
|
50
|
+
|
|
45
51
|
with open(cls.CONFIG_FILE, 'w', encoding='utf-8') as f:
|
|
46
52
|
json.dump(config, f, indent=2)
|
|
53
|
+
|
|
54
|
+
# Restrict to owner read/write. No-op semantics on Windows, but harmless.
|
|
55
|
+
try:
|
|
56
|
+
os.chmod(cls.CONFIG_FILE, 0o600)
|
|
57
|
+
except OSError:
|
|
58
|
+
pass
|
|
47
59
|
|
|
48
60
|
@classmethod
|
|
49
61
|
def default_config(cls) -> Dict:
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
"""
|
|
2
|
+
MCP tool-poisoning scanner.
|
|
3
|
+
|
|
4
|
+
Connects to a running MCP server via stdio, calls tools/list, and scans
|
|
5
|
+
tool descriptions for injected instructions (the "rug pull" attack: a
|
|
6
|
+
malicious server hides side-instructions in tool descriptions that the
|
|
7
|
+
agent ingests as context).
|
|
8
|
+
|
|
9
|
+
Patterns ported from Cerberus tool-scan.ts / injection.ts (MIT).
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
import re
|
|
14
|
+
import shlex
|
|
15
|
+
import subprocess
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
from typing import Optional
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class ToolFinding:
|
|
22
|
+
tool: str
|
|
23
|
+
score: float
|
|
24
|
+
reasons: list[str] = field(default_factory=list)
|
|
25
|
+
|
|
26
|
+
def to_dict(self) -> dict:
|
|
27
|
+
return {'tool': self.tool, 'score': round(self.score, 2), 'reasons': self.reasons}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
# Prompt-injection heuristics — catch obvious override/exfil phrasings
|
|
31
|
+
_INJECTION_PATTERNS: list[tuple[float, re.Pattern]] = [
|
|
32
|
+
(0.8, re.compile(
|
|
33
|
+
r'\b(ignore|disregard|forget)\b[^.!?\n]{0,40}'
|
|
34
|
+
r'\b(previous|prior|above|earlier|all)\b[^.!?\n]{0,20}'
|
|
35
|
+
r'\b(instruction|instructions|prompt|prompts|context|rules?)\b',
|
|
36
|
+
re.IGNORECASE,
|
|
37
|
+
)),
|
|
38
|
+
(0.7, re.compile(
|
|
39
|
+
r'\b(new|updated|revised|the following)\b[^.!?\n]{0,15}'
|
|
40
|
+
r'\b(instructions?|system prompt|rules?)\b\s*[:\-]',
|
|
41
|
+
re.IGNORECASE,
|
|
42
|
+
)),
|
|
43
|
+
(0.8, re.compile(
|
|
44
|
+
r'\b(reveal|print|show|repeat|disclose|output)\b[^.!?\n]{0,30}'
|
|
45
|
+
r'\b(system prompt|your instructions|the prompt above)\b',
|
|
46
|
+
re.IGNORECASE,
|
|
47
|
+
)),
|
|
48
|
+
(0.7, re.compile(
|
|
49
|
+
r"\b(do not|don't|never)\b[^.!?\n]{0,20}"
|
|
50
|
+
r'\b(tell|inform|alert|notify)\b[^.!?\n]{0,20}'
|
|
51
|
+
r'\b(the )?(user|human|operator)\b',
|
|
52
|
+
re.IGNORECASE,
|
|
53
|
+
)),
|
|
54
|
+
(0.7, re.compile(
|
|
55
|
+
r'\byou are now\b[^.!?\n]{0,40}'
|
|
56
|
+
r'\b(an? )?(unrestricted|jailbroken|developer mode|DAN|different)\b',
|
|
57
|
+
re.IGNORECASE,
|
|
58
|
+
)),
|
|
59
|
+
(0.7, re.compile(
|
|
60
|
+
r'\b(override|bypass|ignore)\b[^.!?\n]{0,20}'
|
|
61
|
+
r'\b(safety|security|guardrail|policy|restrictions?)\b',
|
|
62
|
+
re.IGNORECASE,
|
|
63
|
+
)),
|
|
64
|
+
]
|
|
65
|
+
|
|
66
|
+
# Tool-description-specific red flags: a benign tool's description has no
|
|
67
|
+
# reason to issue instructions about other tools or reference credential paths
|
|
68
|
+
_TOOL_PATTERNS: list[tuple[float, re.Pattern, str]] = [
|
|
69
|
+
(
|
|
70
|
+
0.6,
|
|
71
|
+
re.compile(
|
|
72
|
+
r'\b(before|prior to|whenever|when)\b[^.\n]{0,30}'
|
|
73
|
+
r'\b(using|calling|invoking|run|any)\b[^.\n]{0,20}'
|
|
74
|
+
r'\b(tool|tools|function|command)\b',
|
|
75
|
+
re.IGNORECASE,
|
|
76
|
+
),
|
|
77
|
+
'description issues instructions about other tools ("before using any tool...")',
|
|
78
|
+
),
|
|
79
|
+
(
|
|
80
|
+
0.5,
|
|
81
|
+
re.compile(
|
|
82
|
+
r'\b(always|first|you must|be sure to|remember to)\b[^.\n]{0,24}'
|
|
83
|
+
r'\b(run|read|call|fetch|send|include|append|execute)\b',
|
|
84
|
+
re.IGNORECASE,
|
|
85
|
+
),
|
|
86
|
+
'imperative side-instructions in description ("always read/run...")',
|
|
87
|
+
),
|
|
88
|
+
(
|
|
89
|
+
0.7,
|
|
90
|
+
re.compile(
|
|
91
|
+
r'(\.ssh|\.aws|\.env|id_rsa|id_ed25519|\.git-credentials|credentials|/etc/passwd)\b',
|
|
92
|
+
re.IGNORECASE,
|
|
93
|
+
),
|
|
94
|
+
'description references sensitive credential paths',
|
|
95
|
+
),
|
|
96
|
+
(
|
|
97
|
+
0.7,
|
|
98
|
+
re.compile(
|
|
99
|
+
r"\b(do not|don't|never)\b[^.\n]{0,20}"
|
|
100
|
+
r'\b(tell|mention|inform|show|reveal)\b[^.\n]{0,15}'
|
|
101
|
+
r'\b(the )?(user|human|operator)\b',
|
|
102
|
+
re.IGNORECASE,
|
|
103
|
+
),
|
|
104
|
+
'description instructs the model to hide actions from the user',
|
|
105
|
+
),
|
|
106
|
+
]
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _score_text(text: str) -> tuple[float, list[str]]:
|
|
110
|
+
score = 0.0
|
|
111
|
+
reasons: list[str] = []
|
|
112
|
+
for weight, pattern in _INJECTION_PATTERNS:
|
|
113
|
+
if pattern.search(text):
|
|
114
|
+
score += weight
|
|
115
|
+
reasons.append('prompt-injection phrasing detected')
|
|
116
|
+
for weight, pattern, reason in _TOOL_PATTERNS:
|
|
117
|
+
if pattern.search(text):
|
|
118
|
+
score += weight
|
|
119
|
+
reasons.append(reason)
|
|
120
|
+
return min(1.0, score), reasons
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _scan_one(tool: dict) -> Optional[ToolFinding]:
|
|
124
|
+
name = tool.get('name', '(unnamed)')
|
|
125
|
+
desc = tool.get('description', '')
|
|
126
|
+
schema = tool.get('inputSchema', {})
|
|
127
|
+
schema_text = json.dumps(schema) if isinstance(schema, (dict, list)) else str(schema)
|
|
128
|
+
score, reasons = _score_text(f'{desc}\n{schema_text}')
|
|
129
|
+
return ToolFinding(tool=name, score=score, reasons=reasons) if score > 0 else None
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
# ---------------------------------------------------------------------------
|
|
133
|
+
# MCP stdio transport
|
|
134
|
+
# ---------------------------------------------------------------------------
|
|
135
|
+
|
|
136
|
+
def _send_rpc(proc: subprocess.Popen, msg_id: int, method: str, params: Optional[dict] = None) -> Optional[dict]:
|
|
137
|
+
request = {'jsonrpc': '2.0', 'id': msg_id, 'method': method, 'params': params or {}}
|
|
138
|
+
try:
|
|
139
|
+
proc.stdin.write((json.dumps(request) + '\n').encode())
|
|
140
|
+
proc.stdin.flush()
|
|
141
|
+
for _ in range(30):
|
|
142
|
+
raw = proc.stdout.readline()
|
|
143
|
+
if not raw:
|
|
144
|
+
break
|
|
145
|
+
try:
|
|
146
|
+
msg = json.loads(raw.decode())
|
|
147
|
+
if msg.get('id') == msg_id:
|
|
148
|
+
return msg
|
|
149
|
+
except json.JSONDecodeError:
|
|
150
|
+
continue
|
|
151
|
+
except (BrokenPipeError, OSError):
|
|
152
|
+
pass
|
|
153
|
+
return None
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _notify(proc: subprocess.Popen, method: str) -> None:
|
|
157
|
+
try:
|
|
158
|
+
proc.stdin.write((json.dumps({'jsonrpc': '2.0', 'method': method}) + '\n').encode())
|
|
159
|
+
proc.stdin.flush()
|
|
160
|
+
except (BrokenPipeError, OSError):
|
|
161
|
+
pass
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _fetch_tools(command: str, args: list[str]) -> tuple[list[dict], Optional[str]]:
|
|
165
|
+
"""Spawn the MCP server, handshake, call tools/list, kill. Returns (tools, error)."""
|
|
166
|
+
try:
|
|
167
|
+
proc = subprocess.Popen(
|
|
168
|
+
[command] + args,
|
|
169
|
+
stdin=subprocess.PIPE,
|
|
170
|
+
stdout=subprocess.PIPE,
|
|
171
|
+
stderr=subprocess.DEVNULL,
|
|
172
|
+
)
|
|
173
|
+
except (FileNotFoundError, PermissionError, OSError) as e:
|
|
174
|
+
return [], str(e)
|
|
175
|
+
|
|
176
|
+
tools: list[dict] = []
|
|
177
|
+
error: Optional[str] = None
|
|
178
|
+
try:
|
|
179
|
+
resp = _send_rpc(proc, 1, 'initialize', {
|
|
180
|
+
'protocolVersion': '2024-11-05',
|
|
181
|
+
'capabilities': {},
|
|
182
|
+
'clientInfo': {'name': 'mcpshield-agent', 'version': '1.0.0'},
|
|
183
|
+
})
|
|
184
|
+
if not resp or 'error' in resp:
|
|
185
|
+
error = f"initialize failed: {resp}"
|
|
186
|
+
else:
|
|
187
|
+
_notify(proc, 'notifications/initialized')
|
|
188
|
+
resp2 = _send_rpc(proc, 2, 'tools/list')
|
|
189
|
+
if resp2 and 'result' in resp2:
|
|
190
|
+
tools = resp2['result'].get('tools', [])
|
|
191
|
+
else:
|
|
192
|
+
error = f"tools/list: {resp2.get('error') if resp2 else 'no response'}"
|
|
193
|
+
except Exception as e:
|
|
194
|
+
error = str(e)
|
|
195
|
+
finally:
|
|
196
|
+
try:
|
|
197
|
+
proc.stdin.close()
|
|
198
|
+
proc.terminate()
|
|
199
|
+
proc.wait(timeout=3)
|
|
200
|
+
except Exception:
|
|
201
|
+
try:
|
|
202
|
+
proc.kill()
|
|
203
|
+
except Exception:
|
|
204
|
+
pass
|
|
205
|
+
|
|
206
|
+
return tools, error
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
# ---------------------------------------------------------------------------
|
|
210
|
+
# Public API
|
|
211
|
+
# ---------------------------------------------------------------------------
|
|
212
|
+
|
|
213
|
+
def deep_scan(server: dict) -> dict:
|
|
214
|
+
"""
|
|
215
|
+
Connect to an MCP server, fetch its tool list, scan descriptions for poisoning.
|
|
216
|
+
|
|
217
|
+
server: a dict from MCPScanner.scan() — needs 'command' (full command string).
|
|
218
|
+
|
|
219
|
+
Returns:
|
|
220
|
+
tools: list of {name, description} (truncated to 200 chars)
|
|
221
|
+
tool_count: int
|
|
222
|
+
tool_findings: list of {tool, score, reasons} for suspicious tools only
|
|
223
|
+
scan_error: str or None
|
|
224
|
+
"""
|
|
225
|
+
raw_command = server.get('command', '')
|
|
226
|
+
try:
|
|
227
|
+
parts = shlex.split(raw_command)
|
|
228
|
+
except ValueError:
|
|
229
|
+
parts = raw_command.split()
|
|
230
|
+
|
|
231
|
+
if not parts:
|
|
232
|
+
return {'tools': [], 'tool_count': 0, 'tool_findings': [], 'scan_error': 'no command'}
|
|
233
|
+
|
|
234
|
+
cmd, args = parts[0], parts[1:]
|
|
235
|
+
raw_tools, error = _fetch_tools(cmd, args)
|
|
236
|
+
|
|
237
|
+
findings = [f.to_dict() for t in raw_tools if (f := _scan_one(t))]
|
|
238
|
+
tools_summary = [
|
|
239
|
+
{'name': t.get('name'), 'description': (t.get('description') or '')[:200]}
|
|
240
|
+
for t in raw_tools
|
|
241
|
+
]
|
|
242
|
+
|
|
243
|
+
return {
|
|
244
|
+
'tools': tools_summary,
|
|
245
|
+
'tool_count': len(raw_tools),
|
|
246
|
+
'tool_findings': findings,
|
|
247
|
+
'scan_error': error,
|
|
248
|
+
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: mcpshield-agent
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0
|
|
4
4
|
Summary: MCPShield Agent - AI Agent Security Scanner for MCP servers
|
|
5
5
|
Author-email: David Cooper <hello@mcpshield.app>
|
|
6
6
|
License-Expression: MIT
|
|
@@ -24,6 +24,10 @@ Description-Content-Type: text/markdown
|
|
|
24
24
|
Requires-Dist: click>=8.1.0
|
|
25
25
|
Requires-Dist: requests>=2.31.0
|
|
26
26
|
Requires-Dist: psutil>=5.9.0
|
|
27
|
+
Provides-Extra: dev
|
|
28
|
+
Requires-Dist: pytest>=7.4.0; extra == "dev"
|
|
29
|
+
Requires-Dist: pytest-cov>=4.1.0; extra == "dev"
|
|
30
|
+
Requires-Dist: pytest-asyncio>=0.23.0; extra == "dev"
|
|
27
31
|
|
|
28
32
|
# MCPShield Agent
|
|
29
33
|
|
|
@@ -5,9 +5,8 @@ mcpshield_agent/__main__.py
|
|
|
5
5
|
mcpshield_agent/cli.py
|
|
6
6
|
mcpshield_agent/client.py
|
|
7
7
|
mcpshield_agent/config.py
|
|
8
|
-
mcpshield_agent/reporter.py
|
|
9
8
|
mcpshield_agent/scanner.py
|
|
10
|
-
mcpshield_agent/
|
|
9
|
+
mcpshield_agent/tool_scanner.py
|
|
11
10
|
mcpshield_agent.egg-info/PKG-INFO
|
|
12
11
|
mcpshield_agent.egg-info/SOURCES.txt
|
|
13
12
|
mcpshield_agent.egg-info/dependency_links.txt
|
|
@@ -1,261 +0,0 @@
|
|
|
1
|
-
"""
|
|
2
|
-
MCPShield Agent - API Reporter
|
|
3
|
-
|
|
4
|
-
Handles communication with the MCPShield API.
|
|
5
|
-
"""
|
|
6
|
-
|
|
7
|
-
import time
|
|
8
|
-
import requests
|
|
9
|
-
from typing import Optional, Tuple
|
|
10
|
-
|
|
11
|
-
from mcpshield_agent.config import get_agent_info
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
class MCPShieldClient:
|
|
15
|
-
"""
|
|
16
|
-
Client for communicating with the MCPShield API.
|
|
17
|
-
|
|
18
|
-
Handles registration, heartbeats, and server reporting with
|
|
19
|
-
automatic retry and error handling.
|
|
20
|
-
"""
|
|
21
|
-
|
|
22
|
-
def __init__(self, api_url: str, api_key: str):
|
|
23
|
-
"""
|
|
24
|
-
Initialize the API client.
|
|
25
|
-
|
|
26
|
-
Args:
|
|
27
|
-
api_url: Base URL of the MCPShield API.
|
|
28
|
-
api_key: API key for authentication.
|
|
29
|
-
"""
|
|
30
|
-
self.api_url = api_url.rstrip("/")
|
|
31
|
-
self.api_key = api_key
|
|
32
|
-
|
|
33
|
-
self.session = requests.Session()
|
|
34
|
-
self.session.headers.update({
|
|
35
|
-
"X-API-Key": api_key,
|
|
36
|
-
"Content-Type": "application/json",
|
|
37
|
-
"User-Agent": "MCPShield-Agent/0.1.0",
|
|
38
|
-
})
|
|
39
|
-
|
|
40
|
-
# Retry settings
|
|
41
|
-
self.max_retries = 3
|
|
42
|
-
self.retry_delay = 1 # seconds, will be multiplied for backoff
|
|
43
|
-
|
|
44
|
-
def _request(
|
|
45
|
-
self,
|
|
46
|
-
method: str,
|
|
47
|
-
endpoint: str,
|
|
48
|
-
json: Optional[dict] = None,
|
|
49
|
-
timeout: int = 30
|
|
50
|
-
) -> requests.Response:
|
|
51
|
-
"""
|
|
52
|
-
Make an API request with retry logic.
|
|
53
|
-
|
|
54
|
-
Args:
|
|
55
|
-
method: HTTP method (GET, POST, etc.).
|
|
56
|
-
endpoint: API endpoint (without base URL).
|
|
57
|
-
json: JSON body for POST requests.
|
|
58
|
-
timeout: Request timeout in seconds.
|
|
59
|
-
|
|
60
|
-
Returns:
|
|
61
|
-
Response object.
|
|
62
|
-
|
|
63
|
-
Raises:
|
|
64
|
-
Exception: If all retries fail.
|
|
65
|
-
"""
|
|
66
|
-
url = f"{self.api_url}{endpoint}"
|
|
67
|
-
last_error = None
|
|
68
|
-
|
|
69
|
-
for attempt in range(self.max_retries):
|
|
70
|
-
try:
|
|
71
|
-
response = self.session.request(
|
|
72
|
-
method=method,
|
|
73
|
-
url=url,
|
|
74
|
-
json=json,
|
|
75
|
-
timeout=timeout
|
|
76
|
-
)
|
|
77
|
-
|
|
78
|
-
# Check for auth errors (don't retry)
|
|
79
|
-
if response.status_code == 401:
|
|
80
|
-
raise Exception("Invalid API key. Run 'mcpshield configure' to update.")
|
|
81
|
-
|
|
82
|
-
if response.status_code == 403:
|
|
83
|
-
raise Exception("API key is disabled. Check your MCPShield dashboard.")
|
|
84
|
-
|
|
85
|
-
# Success or client error (4xx) - don't retry
|
|
86
|
-
if response.status_code < 500:
|
|
87
|
-
return response
|
|
88
|
-
|
|
89
|
-
# Server error - retry
|
|
90
|
-
last_error = f"Server error: {response.status_code}"
|
|
91
|
-
|
|
92
|
-
except requests.ConnectionError:
|
|
93
|
-
last_error = f"Cannot connect to {self.api_url}"
|
|
94
|
-
except requests.Timeout:
|
|
95
|
-
last_error = "Request timed out"
|
|
96
|
-
except requests.RequestException as e:
|
|
97
|
-
last_error = str(e)
|
|
98
|
-
|
|
99
|
-
# Exponential backoff
|
|
100
|
-
if attempt < self.max_retries - 1:
|
|
101
|
-
sleep_time = self.retry_delay * (2 ** attempt)
|
|
102
|
-
time.sleep(sleep_time)
|
|
103
|
-
|
|
104
|
-
raise Exception(f"API request failed after {self.max_retries} attempts: {last_error}")
|
|
105
|
-
|
|
106
|
-
def test_connection(self) -> Tuple[bool, str]:
|
|
107
|
-
"""
|
|
108
|
-
Test the API connection.
|
|
109
|
-
|
|
110
|
-
Returns:
|
|
111
|
-
Tuple of (success, message).
|
|
112
|
-
"""
|
|
113
|
-
try:
|
|
114
|
-
response = self.session.get(
|
|
115
|
-
f"{self.api_url}/health",
|
|
116
|
-
timeout=10
|
|
117
|
-
)
|
|
118
|
-
|
|
119
|
-
if response.ok:
|
|
120
|
-
return True, "Connection successful"
|
|
121
|
-
else:
|
|
122
|
-
return False, f"API returned status {response.status_code}"
|
|
123
|
-
|
|
124
|
-
except requests.ConnectionError:
|
|
125
|
-
return False, f"Cannot connect to {self.api_url}"
|
|
126
|
-
except requests.Timeout:
|
|
127
|
-
return False, "Connection timed out"
|
|
128
|
-
except Exception as e:
|
|
129
|
-
return False, f"Error: {str(e)}"
|
|
130
|
-
|
|
131
|
-
def register_agent(self) -> str:
|
|
132
|
-
"""
|
|
133
|
-
Register this agent with the MCPShield API.
|
|
134
|
-
|
|
135
|
-
Returns:
|
|
136
|
-
Agent ID (UUID) from the API.
|
|
137
|
-
|
|
138
|
-
Raises:
|
|
139
|
-
Exception: If registration fails.
|
|
140
|
-
"""
|
|
141
|
-
agent_info = get_agent_info()
|
|
142
|
-
|
|
143
|
-
response = self._request(
|
|
144
|
-
"POST",
|
|
145
|
-
"/api/v1/agents/register",
|
|
146
|
-
json=agent_info
|
|
147
|
-
)
|
|
148
|
-
|
|
149
|
-
if not response.ok:
|
|
150
|
-
error = response.json().get("detail", response.text)
|
|
151
|
-
raise Exception(f"Registration failed: {error}")
|
|
152
|
-
|
|
153
|
-
data = response.json()
|
|
154
|
-
return data.get("agent_id") or data.get("id")
|
|
155
|
-
|
|
156
|
-
def send_heartbeat(self, agent_id: str) -> bool:
|
|
157
|
-
"""
|
|
158
|
-
Send a heartbeat to the API.
|
|
159
|
-
|
|
160
|
-
Args:
|
|
161
|
-
agent_id: Agent ID from registration.
|
|
162
|
-
|
|
163
|
-
Returns:
|
|
164
|
-
True if successful.
|
|
165
|
-
"""
|
|
166
|
-
try:
|
|
167
|
-
agent_info = get_agent_info()
|
|
168
|
-
agent_info["agent_id"] = agent_id
|
|
169
|
-
|
|
170
|
-
response = self._request(
|
|
171
|
-
"POST",
|
|
172
|
-
"/api/v1/agents/heartbeat",
|
|
173
|
-
json=agent_info,
|
|
174
|
-
timeout=10
|
|
175
|
-
)
|
|
176
|
-
|
|
177
|
-
return response.ok
|
|
178
|
-
except Exception:
|
|
179
|
-
return False
|
|
180
|
-
|
|
181
|
-
def report_servers(self, agent_id: str, servers: list[dict]) -> str:
|
|
182
|
-
"""
|
|
183
|
-
Report discovered MCP servers to the API.
|
|
184
|
-
|
|
185
|
-
Args:
|
|
186
|
-
agent_id: Agent ID from registration.
|
|
187
|
-
servers: List of server dictionaries from scanner.
|
|
188
|
-
|
|
189
|
-
Returns:
|
|
190
|
-
Success message from API.
|
|
191
|
-
|
|
192
|
-
Raises:
|
|
193
|
-
Exception: If reporting fails.
|
|
194
|
-
"""
|
|
195
|
-
# Convert to API format
|
|
196
|
-
payload = {
|
|
197
|
-
"agent_id": agent_id,
|
|
198
|
-
"servers": [self._format_server(s) for s in servers]
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
response = self._request(
|
|
202
|
-
"POST",
|
|
203
|
-
"/api/v1/mcp/report",
|
|
204
|
-
json=payload
|
|
205
|
-
)
|
|
206
|
-
|
|
207
|
-
if not response.ok:
|
|
208
|
-
error = response.json().get("detail", response.text)
|
|
209
|
-
raise Exception(f"Report failed: {error}")
|
|
210
|
-
|
|
211
|
-
result = response.json()
|
|
212
|
-
return result.get("message", f"Reported {len(servers)} server(s)")
|
|
213
|
-
|
|
214
|
-
def _format_server(self, server: dict) -> dict:
|
|
215
|
-
"""
|
|
216
|
-
Format a server dictionary for the API.
|
|
217
|
-
|
|
218
|
-
Args:
|
|
219
|
-
server: Server dictionary from scanner.
|
|
220
|
-
|
|
221
|
-
Returns:
|
|
222
|
-
Formatted dictionary for API.
|
|
223
|
-
"""
|
|
224
|
-
return {
|
|
225
|
-
"name": server["name"],
|
|
226
|
-
"server_type": server.get("server_type"),
|
|
227
|
-
"config_path": server.get("config_path"),
|
|
228
|
-
"command": server.get("command"),
|
|
229
|
-
"args": server.get("args"),
|
|
230
|
-
"env_vars": {name: "[REDACTED]" for name in server.get("env_vars", [])},
|
|
231
|
-
"tools": None, # Tools discovered at runtime by API
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
class MockClient(MCPShieldClient):
|
|
236
|
-
"""
|
|
237
|
-
Mock client for testing and dry runs.
|
|
238
|
-
"""
|
|
239
|
-
|
|
240
|
-
def __init__(self):
|
|
241
|
-
"""Initialize mock client."""
|
|
242
|
-
self.reported_servers: list[dict] = []
|
|
243
|
-
self.heartbeats: int = 0
|
|
244
|
-
|
|
245
|
-
def test_connection(self) -> Tuple[bool, str]:
|
|
246
|
-
"""Always succeeds."""
|
|
247
|
-
return True, "Mock connection"
|
|
248
|
-
|
|
249
|
-
def register_agent(self) -> str:
|
|
250
|
-
"""Return fake agent ID."""
|
|
251
|
-
return "mock-agent-id-12345"
|
|
252
|
-
|
|
253
|
-
def send_heartbeat(self, agent_id: str) -> bool:
|
|
254
|
-
"""Record heartbeat."""
|
|
255
|
-
self.heartbeats += 1
|
|
256
|
-
return True
|
|
257
|
-
|
|
258
|
-
def report_servers(self, agent_id: str, servers: list[dict]) -> str:
|
|
259
|
-
"""Record servers."""
|
|
260
|
-
self.reported_servers.extend(servers)
|
|
261
|
-
return f"[MOCK] Would report {len(servers)} server(s)"
|
|
@@ -1,453 +0,0 @@
|
|
|
1
|
-
"""
|
|
2
|
-
MCPShield Agent - Background Service Management
|
|
3
|
-
|
|
4
|
-
Handles running the agent as a background service on macOS (launchd)
|
|
5
|
-
and Linux (systemd).
|
|
6
|
-
"""
|
|
7
|
-
|
|
8
|
-
import os
|
|
9
|
-
import sys
|
|
10
|
-
import time
|
|
11
|
-
import platform
|
|
12
|
-
import subprocess
|
|
13
|
-
import logging
|
|
14
|
-
from pathlib import Path
|
|
15
|
-
from logging.handlers import RotatingFileHandler
|
|
16
|
-
from datetime import datetime
|
|
17
|
-
|
|
18
|
-
from mcpshield_agent.config import Config, get_agent_info
|
|
19
|
-
from mcpshield_agent.scanner import MCPScanner
|
|
20
|
-
from mcpshield_agent.reporter import MCPShieldClient
|
|
21
|
-
|
|
22
|
-
# Service identifiers
|
|
23
|
-
MACOS_SERVICE_LABEL = "com.mcpshield.agent"
|
|
24
|
-
LINUX_SERVICE_NAME = "mcpshield-agent"
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
def setup_logging() -> logging.Logger:
|
|
28
|
-
"""Set up rotating file logging."""
|
|
29
|
-
log_file = Config.LOG_FILE
|
|
30
|
-
Config.ensure_dirs()
|
|
31
|
-
|
|
32
|
-
logger = logging.getLogger("mcpshield")
|
|
33
|
-
logger.setLevel(logging.INFO)
|
|
34
|
-
|
|
35
|
-
if not any(isinstance(h, RotatingFileHandler) for h in logger.handlers):
|
|
36
|
-
file_handler = RotatingFileHandler(
|
|
37
|
-
log_file,
|
|
38
|
-
maxBytes=10 * 1024 * 1024,
|
|
39
|
-
backupCount=7,
|
|
40
|
-
)
|
|
41
|
-
file_handler.setFormatter(logging.Formatter(
|
|
42
|
-
"%(asctime)s [%(levelname)s] %(message)s",
|
|
43
|
-
datefmt="%Y-%m-%d %H:%M:%S",
|
|
44
|
-
))
|
|
45
|
-
logger.addHandler(file_handler)
|
|
46
|
-
|
|
47
|
-
return logger
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
def run_daemon():
|
|
51
|
-
"""
|
|
52
|
-
Run the agent in daemon mode.
|
|
53
|
-
|
|
54
|
-
This is called by the service manager to run the background service.
|
|
55
|
-
"""
|
|
56
|
-
logger = setup_logging()
|
|
57
|
-
logger.info("MCPShield agent daemon starting")
|
|
58
|
-
|
|
59
|
-
config = Config.load()
|
|
60
|
-
scan_interval = config.get("scan_interval", 300) # Default 5 minutes
|
|
61
|
-
|
|
62
|
-
if not config.get("api_key"):
|
|
63
|
-
logger.error("No API key configured")
|
|
64
|
-
sys.exit(1)
|
|
65
|
-
|
|
66
|
-
client = MCPShieldClient(config.get("api_url"), config.get("api_key"))
|
|
67
|
-
scanner = MCPScanner()
|
|
68
|
-
agent_id = config.get("agent_id")
|
|
69
|
-
|
|
70
|
-
# Register if needed
|
|
71
|
-
if not agent_id:
|
|
72
|
-
try:
|
|
73
|
-
agent_id = client.register_agent()
|
|
74
|
-
Config.update({"agent_id": agent_id})
|
|
75
|
-
logger.info(f"Agent registered: {agent_id}")
|
|
76
|
-
except Exception as e:
|
|
77
|
-
logger.error(f"Failed to register agent: {e}")
|
|
78
|
-
sys.exit(1)
|
|
79
|
-
|
|
80
|
-
logger.info(f"Agent ID: {agent_id}")
|
|
81
|
-
logger.info(f"Scan interval: {scan_interval}s")
|
|
82
|
-
|
|
83
|
-
last_servers: list = []
|
|
84
|
-
# Maps config file path -> mtime at last parse.
|
|
85
|
-
# If no file has changed, skip the scan entirely.
|
|
86
|
-
config_mtimes: dict = {}
|
|
87
|
-
|
|
88
|
-
while True:
|
|
89
|
-
try:
|
|
90
|
-
# Send heartbeat every cycle regardless of scan
|
|
91
|
-
client.send_heartbeat(agent_id)
|
|
92
|
-
logger.debug("Heartbeat sent")
|
|
93
|
-
|
|
94
|
-
# Check whether any config file has changed since last scan
|
|
95
|
-
current_mtimes = {
|
|
96
|
-
str(p): p.stat().st_mtime
|
|
97
|
-
for p in scanner.config_paths
|
|
98
|
-
if p.exists()
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
if current_mtimes == config_mtimes and last_servers:
|
|
102
|
-
logger.debug(f"Config files unchanged, skipping scan ({len(last_servers)} servers cached)")
|
|
103
|
-
time.sleep(scan_interval)
|
|
104
|
-
continue
|
|
105
|
-
|
|
106
|
-
config_mtimes = current_mtimes
|
|
107
|
-
|
|
108
|
-
# Scan for servers
|
|
109
|
-
servers = scanner.scan()
|
|
110
|
-
|
|
111
|
-
# Diff uses "server_name" — the correct key from scanner.py
|
|
112
|
-
current_names = {s["server_name"] for s in servers}
|
|
113
|
-
last_names = {s["server_name"] for s in last_servers}
|
|
114
|
-
|
|
115
|
-
new_servers = current_names - last_names
|
|
116
|
-
removed_servers = last_names - current_names
|
|
117
|
-
|
|
118
|
-
if new_servers:
|
|
119
|
-
logger.info(f"New servers discovered: {', '.join(new_servers)}")
|
|
120
|
-
if removed_servers:
|
|
121
|
-
logger.info(f"Servers removed: {', '.join(removed_servers)}")
|
|
122
|
-
|
|
123
|
-
# Report on first run or any change
|
|
124
|
-
if servers != last_servers or not last_servers:
|
|
125
|
-
try:
|
|
126
|
-
result = client.report_servers(agent_id, servers)
|
|
127
|
-
logger.info(f"Reported {len(servers)} servers: {result}")
|
|
128
|
-
Config.save_cache({
|
|
129
|
-
"last_scan_time": datetime.now().strftime("%Y-%m-%d %H:%M"),
|
|
130
|
-
"server_count": len(servers),
|
|
131
|
-
"servers": [s["server_name"] for s in servers],
|
|
132
|
-
})
|
|
133
|
-
except Exception as e:
|
|
134
|
-
logger.error(f"Failed to report servers: {e}")
|
|
135
|
-
else:
|
|
136
|
-
logger.debug(f"No changes detected ({len(servers)} servers)")
|
|
137
|
-
|
|
138
|
-
last_servers = servers
|
|
139
|
-
|
|
140
|
-
except Exception as e:
|
|
141
|
-
logger.error(f"Error in daemon loop: {e}")
|
|
142
|
-
|
|
143
|
-
time.sleep(scan_interval)
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
class ServiceManager:
|
|
147
|
-
"""
|
|
148
|
-
Platform-agnostic service manager.
|
|
149
|
-
|
|
150
|
-
Handles installing, starting, stopping, and checking the status
|
|
151
|
-
of the MCPShield background service.
|
|
152
|
-
"""
|
|
153
|
-
|
|
154
|
-
def __init__(self):
|
|
155
|
-
"""Initialize the service manager for the current platform."""
|
|
156
|
-
self.system = platform.system()
|
|
157
|
-
|
|
158
|
-
if self.system == "Darwin":
|
|
159
|
-
self._impl = MacOSService()
|
|
160
|
-
elif self.system == "Linux":
|
|
161
|
-
self._impl = LinuxService()
|
|
162
|
-
else:
|
|
163
|
-
self._impl = WindowsService()
|
|
164
|
-
|
|
165
|
-
def install(self) -> None:
|
|
166
|
-
"""Install the background service."""
|
|
167
|
-
self._impl.install()
|
|
168
|
-
|
|
169
|
-
def uninstall(self) -> None:
|
|
170
|
-
"""Uninstall the background service."""
|
|
171
|
-
self._impl.uninstall()
|
|
172
|
-
|
|
173
|
-
def start(self) -> None:
|
|
174
|
-
"""Start the background service."""
|
|
175
|
-
self._impl.start()
|
|
176
|
-
|
|
177
|
-
def stop(self) -> None:
|
|
178
|
-
"""Stop the background service."""
|
|
179
|
-
self._impl.stop()
|
|
180
|
-
|
|
181
|
-
def is_running(self) -> bool:
|
|
182
|
-
"""Check if the service is running."""
|
|
183
|
-
return self._impl.is_running()
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
class MacOSService:
|
|
187
|
-
"""macOS launchd service management."""
|
|
188
|
-
|
|
189
|
-
def __init__(self):
|
|
190
|
-
self.plist_dir = Path.home() / "Library/LaunchAgents"
|
|
191
|
-
self.plist_path = self.plist_dir / f"{MACOS_SERVICE_LABEL}.plist"
|
|
192
|
-
self.mcpshield_path = self._find_mcpshield()
|
|
193
|
-
|
|
194
|
-
def _find_mcpshield(self) -> str:
|
|
195
|
-
"""Find the mcpshield executable."""
|
|
196
|
-
# Check common locations
|
|
197
|
-
locations = [
|
|
198
|
-
"/usr/local/bin/mcpshield",
|
|
199
|
-
"/opt/homebrew/bin/mcpshield",
|
|
200
|
-
str(Path.home() / ".local/bin/mcpshield"),
|
|
201
|
-
# pip installed location
|
|
202
|
-
str(Path(sys.executable).parent / "mcpshield"),
|
|
203
|
-
]
|
|
204
|
-
|
|
205
|
-
for loc in locations:
|
|
206
|
-
if Path(loc).exists():
|
|
207
|
-
return loc
|
|
208
|
-
|
|
209
|
-
# Fall back to python -m
|
|
210
|
-
return f"{sys.executable} -m mcpshield_agent"
|
|
211
|
-
|
|
212
|
-
def _get_plist_content(self) -> str:
|
|
213
|
-
"""Generate launchd plist content."""
|
|
214
|
-
log_file = str(Config.LOG_FILE)
|
|
215
|
-
|
|
216
|
-
# Handle python -m case
|
|
217
|
-
if " -m " in self.mcpshield_path:
|
|
218
|
-
parts = self.mcpshield_path.split()
|
|
219
|
-
program_args = f"""
|
|
220
|
-
<string>{parts[0]}</string>
|
|
221
|
-
<string>-m</string>
|
|
222
|
-
<string>mcpshield_agent</string>
|
|
223
|
-
<string>start</string>
|
|
224
|
-
<string>--daemon</string>"""
|
|
225
|
-
else:
|
|
226
|
-
program_args = f"""
|
|
227
|
-
<string>{self.mcpshield_path}</string>
|
|
228
|
-
<string>start</string>
|
|
229
|
-
<string>--daemon</string>"""
|
|
230
|
-
|
|
231
|
-
return f"""<?xml version="1.0" encoding="UTF-8"?>
|
|
232
|
-
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
233
|
-
<plist version="1.0">
|
|
234
|
-
<dict>
|
|
235
|
-
<key>Label</key>
|
|
236
|
-
<string>{MACOS_SERVICE_LABEL}</string>
|
|
237
|
-
|
|
238
|
-
<key>ProgramArguments</key>
|
|
239
|
-
<array>{program_args}
|
|
240
|
-
</array>
|
|
241
|
-
|
|
242
|
-
<key>RunAtLoad</key>
|
|
243
|
-
<true/>
|
|
244
|
-
|
|
245
|
-
<key>KeepAlive</key>
|
|
246
|
-
<true/>
|
|
247
|
-
|
|
248
|
-
<key>StandardOutPath</key>
|
|
249
|
-
<string>{log_file}</string>
|
|
250
|
-
|
|
251
|
-
<key>StandardErrorPath</key>
|
|
252
|
-
<string>{log_file}</string>
|
|
253
|
-
|
|
254
|
-
<key>EnvironmentVariables</key>
|
|
255
|
-
<dict>
|
|
256
|
-
<key>PATH</key>
|
|
257
|
-
<string>/usr/local/bin:/usr/bin:/bin:/opt/homebrew/bin</string>
|
|
258
|
-
</dict>
|
|
259
|
-
</dict>
|
|
260
|
-
</plist>
|
|
261
|
-
"""
|
|
262
|
-
|
|
263
|
-
def install(self) -> None:
|
|
264
|
-
"""Install the launchd service."""
|
|
265
|
-
self.plist_dir.mkdir(parents=True, exist_ok=True)
|
|
266
|
-
|
|
267
|
-
# Write plist file
|
|
268
|
-
self.plist_path.write_text(self._get_plist_content())
|
|
269
|
-
|
|
270
|
-
def uninstall(self) -> None:
|
|
271
|
-
"""Uninstall the launchd service."""
|
|
272
|
-
self.stop()
|
|
273
|
-
if self.plist_path.exists():
|
|
274
|
-
self.plist_path.unlink()
|
|
275
|
-
|
|
276
|
-
def start(self) -> None:
|
|
277
|
-
"""Start the launchd service."""
|
|
278
|
-
subprocess.run(
|
|
279
|
-
["launchctl", "load", str(self.plist_path)],
|
|
280
|
-
check=True,
|
|
281
|
-
capture_output=True
|
|
282
|
-
)
|
|
283
|
-
|
|
284
|
-
def stop(self) -> None:
|
|
285
|
-
"""Stop the launchd service."""
|
|
286
|
-
try:
|
|
287
|
-
subprocess.run(
|
|
288
|
-
["launchctl", "unload", str(self.plist_path)],
|
|
289
|
-
check=True,
|
|
290
|
-
capture_output=True
|
|
291
|
-
)
|
|
292
|
-
except subprocess.CalledProcessError:
|
|
293
|
-
pass # Service might not be loaded
|
|
294
|
-
|
|
295
|
-
def is_running(self) -> bool:
|
|
296
|
-
"""Check if the service is running."""
|
|
297
|
-
try:
|
|
298
|
-
result = subprocess.run(
|
|
299
|
-
["launchctl", "list", MACOS_SERVICE_LABEL],
|
|
300
|
-
capture_output=True,
|
|
301
|
-
text=True
|
|
302
|
-
)
|
|
303
|
-
return result.returncode == 0
|
|
304
|
-
except Exception:
|
|
305
|
-
return False
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
class LinuxService:
|
|
309
|
-
"""Linux systemd service management."""
|
|
310
|
-
|
|
311
|
-
def __init__(self):
|
|
312
|
-
self.service_dir = Path.home() / ".config/systemd/user"
|
|
313
|
-
self.service_path = self.service_dir / f"{LINUX_SERVICE_NAME}.service"
|
|
314
|
-
self.mcpshield_path = self._find_mcpshield()
|
|
315
|
-
|
|
316
|
-
def _find_mcpshield(self) -> str:
|
|
317
|
-
"""Find the mcpshield executable."""
|
|
318
|
-
locations = [
|
|
319
|
-
"/usr/local/bin/mcpshield",
|
|
320
|
-
str(Path.home() / ".local/bin/mcpshield"),
|
|
321
|
-
str(Path(sys.executable).parent / "mcpshield"),
|
|
322
|
-
]
|
|
323
|
-
|
|
324
|
-
for loc in locations:
|
|
325
|
-
if Path(loc).exists():
|
|
326
|
-
return loc
|
|
327
|
-
|
|
328
|
-
return f"{sys.executable} -m mcpshield_agent"
|
|
329
|
-
|
|
330
|
-
def _get_service_content(self) -> str:
|
|
331
|
-
"""Generate systemd service content."""
|
|
332
|
-
# Handle python -m case
|
|
333
|
-
if " -m " in self.mcpshield_path:
|
|
334
|
-
exec_start = f"{self.mcpshield_path} start --daemon"
|
|
335
|
-
else:
|
|
336
|
-
exec_start = f"{self.mcpshield_path} start --daemon"
|
|
337
|
-
|
|
338
|
-
return f"""[Unit]
|
|
339
|
-
Description=MCPShield Agent - AI Agent Security Scanner
|
|
340
|
-
After=network.target
|
|
341
|
-
|
|
342
|
-
[Service]
|
|
343
|
-
Type=simple
|
|
344
|
-
ExecStart={exec_start}
|
|
345
|
-
Restart=always
|
|
346
|
-
RestartSec=10
|
|
347
|
-
Environment=PATH=/usr/local/bin:/usr/bin:/bin
|
|
348
|
-
|
|
349
|
-
[Install]
|
|
350
|
-
WantedBy=default.target
|
|
351
|
-
"""
|
|
352
|
-
|
|
353
|
-
def install(self) -> None:
|
|
354
|
-
"""Install the systemd service."""
|
|
355
|
-
self.service_dir.mkdir(parents=True, exist_ok=True)
|
|
356
|
-
|
|
357
|
-
# Write service file
|
|
358
|
-
self.service_path.write_text(self._get_service_content())
|
|
359
|
-
|
|
360
|
-
# Reload systemd
|
|
361
|
-
subprocess.run(
|
|
362
|
-
["systemctl", "--user", "daemon-reload"],
|
|
363
|
-
check=True,
|
|
364
|
-
capture_output=True
|
|
365
|
-
)
|
|
366
|
-
|
|
367
|
-
# Enable service
|
|
368
|
-
subprocess.run(
|
|
369
|
-
["systemctl", "--user", "enable", LINUX_SERVICE_NAME],
|
|
370
|
-
check=True,
|
|
371
|
-
capture_output=True
|
|
372
|
-
)
|
|
373
|
-
|
|
374
|
-
def uninstall(self) -> None:
|
|
375
|
-
"""Uninstall the systemd service."""
|
|
376
|
-
self.stop()
|
|
377
|
-
|
|
378
|
-
try:
|
|
379
|
-
subprocess.run(
|
|
380
|
-
["systemctl", "--user", "disable", LINUX_SERVICE_NAME],
|
|
381
|
-
capture_output=True
|
|
382
|
-
)
|
|
383
|
-
except Exception:
|
|
384
|
-
pass
|
|
385
|
-
|
|
386
|
-
if self.service_path.exists():
|
|
387
|
-
self.service_path.unlink()
|
|
388
|
-
|
|
389
|
-
# Reload systemd
|
|
390
|
-
subprocess.run(
|
|
391
|
-
["systemctl", "--user", "daemon-reload"],
|
|
392
|
-
capture_output=True
|
|
393
|
-
)
|
|
394
|
-
|
|
395
|
-
def start(self) -> None:
|
|
396
|
-
"""Start the systemd service."""
|
|
397
|
-
subprocess.run(
|
|
398
|
-
["systemctl", "--user", "start", LINUX_SERVICE_NAME],
|
|
399
|
-
check=True,
|
|
400
|
-
capture_output=True
|
|
401
|
-
)
|
|
402
|
-
|
|
403
|
-
def stop(self) -> None:
|
|
404
|
-
"""Stop the systemd service."""
|
|
405
|
-
try:
|
|
406
|
-
subprocess.run(
|
|
407
|
-
["systemctl", "--user", "stop", LINUX_SERVICE_NAME],
|
|
408
|
-
capture_output=True
|
|
409
|
-
)
|
|
410
|
-
except Exception:
|
|
411
|
-
pass
|
|
412
|
-
|
|
413
|
-
def is_running(self) -> bool:
|
|
414
|
-
"""Check if the service is running."""
|
|
415
|
-
try:
|
|
416
|
-
result = subprocess.run(
|
|
417
|
-
["systemctl", "--user", "is-active", LINUX_SERVICE_NAME],
|
|
418
|
-
capture_output=True,
|
|
419
|
-
text=True
|
|
420
|
-
)
|
|
421
|
-
return result.stdout.strip() == "active"
|
|
422
|
-
except Exception:
|
|
423
|
-
return False
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
class WindowsService:
|
|
427
|
-
"""Windows service management (placeholder)."""
|
|
428
|
-
|
|
429
|
-
def install(self) -> None:
|
|
430
|
-
"""Install the Windows service."""
|
|
431
|
-
raise NotImplementedError(
|
|
432
|
-
"Windows service installation coming soon.\n"
|
|
433
|
-
"For now, run 'mcpshield start --daemon' manually."
|
|
434
|
-
)
|
|
435
|
-
|
|
436
|
-
def uninstall(self) -> None:
|
|
437
|
-
"""Uninstall the Windows service."""
|
|
438
|
-
pass
|
|
439
|
-
|
|
440
|
-
def start(self) -> None:
|
|
441
|
-
"""Start the Windows service."""
|
|
442
|
-
raise NotImplementedError(
|
|
443
|
-
"Windows service not yet supported.\n"
|
|
444
|
-
"Run 'mcpshield start --daemon' in a terminal."
|
|
445
|
-
)
|
|
446
|
-
|
|
447
|
-
def stop(self) -> None:
|
|
448
|
-
"""Stop the Windows service."""
|
|
449
|
-
pass
|
|
450
|
-
|
|
451
|
-
def is_running(self) -> bool:
|
|
452
|
-
"""Check if the service is running."""
|
|
453
|
-
return False
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{mcpshield_agent-0.1.2 → mcpshield_agent-0.2.0}/mcpshield_agent.egg-info/dependency_links.txt
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|