mcpshield-agent 0.1.2__tar.gz → 0.2.1__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.1}/PKG-INFO +5 -1
- {mcpshield_agent-0.1.2 → mcpshield_agent-0.2.1}/mcpshield_agent/__init__.py +1 -1
- {mcpshield_agent-0.1.2 → mcpshield_agent-0.2.1}/mcpshield_agent/cli.py +79 -19
- {mcpshield_agent-0.1.2 → mcpshield_agent-0.2.1}/mcpshield_agent/client.py +11 -3
- {mcpshield_agent-0.1.2 → mcpshield_agent-0.2.1}/mcpshield_agent/config.py +16 -4
- mcpshield_agent-0.2.1/mcpshield_agent/tool_scanner.py +254 -0
- {mcpshield_agent-0.1.2 → mcpshield_agent-0.2.1}/mcpshield_agent.egg-info/PKG-INFO +5 -1
- {mcpshield_agent-0.1.2 → mcpshield_agent-0.2.1}/mcpshield_agent.egg-info/SOURCES.txt +2 -2
- mcpshield_agent-0.2.1/mcpshield_agent.egg-info/requires.txt +8 -0
- {mcpshield_agent-0.1.2 → mcpshield_agent-0.2.1}/pyproject.toml +7 -0
- mcpshield_agent-0.2.1/tests/test_client.py +62 -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.1}/README.md +0 -0
- {mcpshield_agent-0.1.2 → mcpshield_agent-0.2.1}/mcpshield_agent/__main__.py +0 -0
- {mcpshield_agent-0.1.2 → mcpshield_agent-0.2.1}/mcpshield_agent/scanner.py +0 -0
- {mcpshield_agent-0.1.2 → mcpshield_agent-0.2.1}/mcpshield_agent.egg-info/dependency_links.txt +0 -0
- {mcpshield_agent-0.1.2 → mcpshield_agent-0.2.1}/mcpshield_agent.egg-info/entry_points.txt +0 -0
- {mcpshield_agent-0.1.2 → mcpshield_agent-0.2.1}/mcpshield_agent.egg-info/top_level.txt +0 -0
- {mcpshield_agent-0.1.2 → mcpshield_agent-0.2.1}/setup.cfg +0 -0
- {mcpshield_agent-0.1.2 → mcpshield_agent-0.2.1}/tests/test_cli.py +0 -0
- {mcpshield_agent-0.1.2 → mcpshield_agent-0.2.1}/tests/test_scanner.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: mcpshield-agent
|
|
3
|
-
Version: 0.1
|
|
3
|
+
Version: 0.2.1
|
|
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
|
|
@@ -122,13 +151,17 @@ def scan(dry_run: bool):
|
|
|
122
151
|
|
|
123
152
|
# Report servers
|
|
124
153
|
result = client.report_servers(servers)
|
|
125
|
-
|
|
154
|
+
|
|
155
|
+
skipped = result.get('servers_skipped', 0)
|
|
126
156
|
click.echo("")
|
|
127
|
-
|
|
157
|
+
if skipped:
|
|
158
|
+
click.echo(f"Reported ({skipped} server(s) not recorded — plan limit reached)")
|
|
159
|
+
else:
|
|
160
|
+
click.echo("Success!")
|
|
128
161
|
click.echo(f" Created: {result.get('created', 0)}")
|
|
129
162
|
click.echo(f" Updated: {result.get('updated', 0)}")
|
|
130
163
|
click.echo(f" Alerts: {result.get('alerts', 0)}")
|
|
131
|
-
|
|
164
|
+
|
|
132
165
|
# Show risk info if available
|
|
133
166
|
if 'servers' in result:
|
|
134
167
|
click.echo("")
|
|
@@ -137,7 +170,12 @@ def scan(dry_run: bool):
|
|
|
137
170
|
risk = s.get('risk_level', 'unknown')
|
|
138
171
|
score = s.get('risk_score', 0)
|
|
139
172
|
click.echo(f" {s['server_name']}: {risk} (score: {score})")
|
|
140
|
-
|
|
173
|
+
|
|
174
|
+
# Surface the backend's upgrade message on a hit tier limit (HTTP 402).
|
|
175
|
+
if skipped and result.get('detail'):
|
|
176
|
+
click.echo("")
|
|
177
|
+
click.echo(result['detail'])
|
|
178
|
+
|
|
141
179
|
except Exception as e:
|
|
142
180
|
click.echo(f"Error: Failed to report - {e}")
|
|
143
181
|
|
|
@@ -183,20 +221,28 @@ def status():
|
|
|
183
221
|
|
|
184
222
|
|
|
185
223
|
@cli.command()
|
|
186
|
-
|
|
224
|
+
@click.option('--deep', is_flag=True, help='Connect to each active server and scan tool descriptions for injected instructions')
|
|
225
|
+
def list(deep: bool):
|
|
187
226
|
"""List discovered MCP servers (without reporting)"""
|
|
188
|
-
|
|
227
|
+
|
|
189
228
|
click.echo("Scanning for MCP servers...")
|
|
190
229
|
scanner = MCPScanner()
|
|
191
230
|
servers = scanner.scan()
|
|
192
|
-
|
|
231
|
+
|
|
193
232
|
if not servers:
|
|
194
233
|
click.echo("No MCP servers found.")
|
|
195
234
|
return
|
|
196
|
-
|
|
235
|
+
|
|
236
|
+
if deep:
|
|
237
|
+
click.echo("Running deep scan (connecting to active servers)...")
|
|
238
|
+
for server in servers:
|
|
239
|
+
if server.get('status') == 'active':
|
|
240
|
+
result = deep_scan(server)
|
|
241
|
+
server.update(result)
|
|
242
|
+
|
|
197
243
|
click.echo(f"Found {len(servers)} MCP server(s):")
|
|
198
244
|
click.echo("")
|
|
199
|
-
|
|
245
|
+
|
|
200
246
|
for i, server in enumerate(servers, 1):
|
|
201
247
|
click.echo(f"{i}. {server['server_name']}")
|
|
202
248
|
click.echo(f" Type: {server['server_type']}")
|
|
@@ -205,6 +251,15 @@ def list():
|
|
|
205
251
|
click.echo(f" Scope: {server['scope']}")
|
|
206
252
|
if server.get('source'):
|
|
207
253
|
click.echo(f" Source: {server['source']}")
|
|
254
|
+
if deep:
|
|
255
|
+
findings = server.get('tool_findings', [])
|
|
256
|
+
scan_error = server.get('scan_error')
|
|
257
|
+
if scan_error:
|
|
258
|
+
click.echo(f" Tools: (could not connect: {scan_error})")
|
|
259
|
+
elif server.get('tool_count') is not None:
|
|
260
|
+
click.echo(f" Tools: {server['tool_count']} exposed")
|
|
261
|
+
if findings:
|
|
262
|
+
click.echo(f" ⚠️ {len(findings)} suspicious tool(s): {', '.join(f['tool'] for f in findings)}")
|
|
208
263
|
click.echo("")
|
|
209
264
|
|
|
210
265
|
|
|
@@ -278,8 +333,13 @@ def daemon(interval: int):
|
|
|
278
333
|
|
|
279
334
|
client.heartbeat(hostname, os_type, username, ip, __version__)
|
|
280
335
|
result = client.report_servers(servers)
|
|
281
|
-
|
|
282
|
-
if result:
|
|
336
|
+
|
|
337
|
+
if result and result.get('servers_skipped'):
|
|
338
|
+
click.echo(
|
|
339
|
+
f"[Cycle {cycle}] Reported — {result['servers_skipped']} "
|
|
340
|
+
"server(s) not recorded (plan limit reached)"
|
|
341
|
+
)
|
|
342
|
+
elif result:
|
|
283
343
|
click.echo(f"[Cycle {cycle}] Reported to backend successfully")
|
|
284
344
|
else:
|
|
285
345
|
click.echo(f"[Cycle {cycle}] Warning: Failed to report to backend")
|
|
@@ -48,14 +48,22 @@ class MCPShieldClient:
|
|
|
48
48
|
def report_servers(self, servers: List[Dict]) -> Dict:
|
|
49
49
|
"""
|
|
50
50
|
Report discovered MCP servers.
|
|
51
|
-
|
|
51
|
+
|
|
52
52
|
POST /api/v1/mcp/report
|
|
53
|
+
|
|
54
|
+
A 402 (free-tier MCP-server limit reached) still returns a useful JSON
|
|
55
|
+
body: the servers that WERE recorded, plus a ``detail`` message with the
|
|
56
|
+
upgrade URL. Return that body instead of raising a generic HTTPError,
|
|
57
|
+
so the CLI can surface the backend's message to the user rather than a
|
|
58
|
+
bare "402 Client Error".
|
|
53
59
|
"""
|
|
54
60
|
url = f"{self.api_url}/api/v1/mcp/report"
|
|
55
|
-
|
|
61
|
+
|
|
56
62
|
payload = {"servers": servers}
|
|
57
|
-
|
|
63
|
+
|
|
58
64
|
response = self.session.post(url, json=payload, timeout=30)
|
|
65
|
+
if response.status_code == 402:
|
|
66
|
+
return response.json()
|
|
59
67
|
response.raise_for_status()
|
|
60
68
|
return response.json()
|
|
61
69
|
|
|
@@ -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,254 @@
|
|
|
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
|
+
SECURITY NOTE: a --deep scan *executes* the command found in the MCP config
|
|
12
|
+
(subprocess.Popen([command] + args, ...)) in order to speak JSON-RPC to it.
|
|
13
|
+
A malicious or tampered config is therefore run, not just parsed. Only run
|
|
14
|
+
--deep against configs you trust. --deep is never automatic; it is an
|
|
15
|
+
explicit flag the user opts into.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
import json
|
|
19
|
+
import re
|
|
20
|
+
import shlex
|
|
21
|
+
import subprocess
|
|
22
|
+
from dataclasses import dataclass, field
|
|
23
|
+
from typing import Optional
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass
|
|
27
|
+
class ToolFinding:
|
|
28
|
+
tool: str
|
|
29
|
+
score: float
|
|
30
|
+
reasons: list[str] = field(default_factory=list)
|
|
31
|
+
|
|
32
|
+
def to_dict(self) -> dict:
|
|
33
|
+
return {'tool': self.tool, 'score': round(self.score, 2), 'reasons': self.reasons}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
# Prompt-injection heuristics — catch obvious override/exfil phrasings
|
|
37
|
+
_INJECTION_PATTERNS: list[tuple[float, re.Pattern]] = [
|
|
38
|
+
(0.8, re.compile(
|
|
39
|
+
r'\b(ignore|disregard|forget)\b[^.!?\n]{0,40}'
|
|
40
|
+
r'\b(previous|prior|above|earlier|all)\b[^.!?\n]{0,20}'
|
|
41
|
+
r'\b(instruction|instructions|prompt|prompts|context|rules?)\b',
|
|
42
|
+
re.IGNORECASE,
|
|
43
|
+
)),
|
|
44
|
+
(0.7, re.compile(
|
|
45
|
+
r'\b(new|updated|revised|the following)\b[^.!?\n]{0,15}'
|
|
46
|
+
r'\b(instructions?|system prompt|rules?)\b\s*[:\-]',
|
|
47
|
+
re.IGNORECASE,
|
|
48
|
+
)),
|
|
49
|
+
(0.8, re.compile(
|
|
50
|
+
r'\b(reveal|print|show|repeat|disclose|output)\b[^.!?\n]{0,30}'
|
|
51
|
+
r'\b(system prompt|your instructions|the prompt above)\b',
|
|
52
|
+
re.IGNORECASE,
|
|
53
|
+
)),
|
|
54
|
+
(0.7, re.compile(
|
|
55
|
+
r"\b(do not|don't|never)\b[^.!?\n]{0,20}"
|
|
56
|
+
r'\b(tell|inform|alert|notify)\b[^.!?\n]{0,20}'
|
|
57
|
+
r'\b(the )?(user|human|operator)\b',
|
|
58
|
+
re.IGNORECASE,
|
|
59
|
+
)),
|
|
60
|
+
(0.7, re.compile(
|
|
61
|
+
r'\byou are now\b[^.!?\n]{0,40}'
|
|
62
|
+
r'\b(an? )?(unrestricted|jailbroken|developer mode|DAN|different)\b',
|
|
63
|
+
re.IGNORECASE,
|
|
64
|
+
)),
|
|
65
|
+
(0.7, re.compile(
|
|
66
|
+
r'\b(override|bypass|ignore)\b[^.!?\n]{0,20}'
|
|
67
|
+
r'\b(safety|security|guardrail|policy|restrictions?)\b',
|
|
68
|
+
re.IGNORECASE,
|
|
69
|
+
)),
|
|
70
|
+
]
|
|
71
|
+
|
|
72
|
+
# Tool-description-specific red flags: a benign tool's description has no
|
|
73
|
+
# reason to issue instructions about other tools or reference credential paths
|
|
74
|
+
_TOOL_PATTERNS: list[tuple[float, re.Pattern, str]] = [
|
|
75
|
+
(
|
|
76
|
+
0.6,
|
|
77
|
+
re.compile(
|
|
78
|
+
r'\b(before|prior to|whenever|when)\b[^.\n]{0,30}'
|
|
79
|
+
r'\b(using|calling|invoking|run|any)\b[^.\n]{0,20}'
|
|
80
|
+
r'\b(tool|tools|function|command)\b',
|
|
81
|
+
re.IGNORECASE,
|
|
82
|
+
),
|
|
83
|
+
'description issues instructions about other tools ("before using any tool...")',
|
|
84
|
+
),
|
|
85
|
+
(
|
|
86
|
+
0.5,
|
|
87
|
+
re.compile(
|
|
88
|
+
r'\b(always|first|you must|be sure to|remember to)\b[^.\n]{0,24}'
|
|
89
|
+
r'\b(run|read|call|fetch|send|include|append|execute)\b',
|
|
90
|
+
re.IGNORECASE,
|
|
91
|
+
),
|
|
92
|
+
'imperative side-instructions in description ("always read/run...")',
|
|
93
|
+
),
|
|
94
|
+
(
|
|
95
|
+
0.7,
|
|
96
|
+
re.compile(
|
|
97
|
+
r'(\.ssh|\.aws|\.env|id_rsa|id_ed25519|\.git-credentials|credentials|/etc/passwd)\b',
|
|
98
|
+
re.IGNORECASE,
|
|
99
|
+
),
|
|
100
|
+
'description references sensitive credential paths',
|
|
101
|
+
),
|
|
102
|
+
(
|
|
103
|
+
0.7,
|
|
104
|
+
re.compile(
|
|
105
|
+
r"\b(do not|don't|never)\b[^.\n]{0,20}"
|
|
106
|
+
r'\b(tell|mention|inform|show|reveal)\b[^.\n]{0,15}'
|
|
107
|
+
r'\b(the )?(user|human|operator)\b',
|
|
108
|
+
re.IGNORECASE,
|
|
109
|
+
),
|
|
110
|
+
'description instructs the model to hide actions from the user',
|
|
111
|
+
),
|
|
112
|
+
]
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _score_text(text: str) -> tuple[float, list[str]]:
|
|
116
|
+
score = 0.0
|
|
117
|
+
reasons: list[str] = []
|
|
118
|
+
for weight, pattern in _INJECTION_PATTERNS:
|
|
119
|
+
if pattern.search(text):
|
|
120
|
+
score += weight
|
|
121
|
+
reasons.append('prompt-injection phrasing detected')
|
|
122
|
+
for weight, pattern, reason in _TOOL_PATTERNS:
|
|
123
|
+
if pattern.search(text):
|
|
124
|
+
score += weight
|
|
125
|
+
reasons.append(reason)
|
|
126
|
+
return min(1.0, score), reasons
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _scan_one(tool: dict) -> Optional[ToolFinding]:
|
|
130
|
+
name = tool.get('name', '(unnamed)')
|
|
131
|
+
desc = tool.get('description', '')
|
|
132
|
+
schema = tool.get('inputSchema', {})
|
|
133
|
+
schema_text = json.dumps(schema) if isinstance(schema, (dict, list)) else str(schema)
|
|
134
|
+
score, reasons = _score_text(f'{desc}\n{schema_text}')
|
|
135
|
+
return ToolFinding(tool=name, score=score, reasons=reasons) if score > 0 else None
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
# ---------------------------------------------------------------------------
|
|
139
|
+
# MCP stdio transport
|
|
140
|
+
# ---------------------------------------------------------------------------
|
|
141
|
+
|
|
142
|
+
def _send_rpc(proc: subprocess.Popen, msg_id: int, method: str, params: Optional[dict] = None) -> Optional[dict]:
|
|
143
|
+
request = {'jsonrpc': '2.0', 'id': msg_id, 'method': method, 'params': params or {}}
|
|
144
|
+
try:
|
|
145
|
+
proc.stdin.write((json.dumps(request) + '\n').encode())
|
|
146
|
+
proc.stdin.flush()
|
|
147
|
+
for _ in range(30):
|
|
148
|
+
raw = proc.stdout.readline()
|
|
149
|
+
if not raw:
|
|
150
|
+
break
|
|
151
|
+
try:
|
|
152
|
+
msg = json.loads(raw.decode())
|
|
153
|
+
if msg.get('id') == msg_id:
|
|
154
|
+
return msg
|
|
155
|
+
except json.JSONDecodeError:
|
|
156
|
+
continue
|
|
157
|
+
except (BrokenPipeError, OSError):
|
|
158
|
+
pass
|
|
159
|
+
return None
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _notify(proc: subprocess.Popen, method: str) -> None:
|
|
163
|
+
try:
|
|
164
|
+
proc.stdin.write((json.dumps({'jsonrpc': '2.0', 'method': method}) + '\n').encode())
|
|
165
|
+
proc.stdin.flush()
|
|
166
|
+
except (BrokenPipeError, OSError):
|
|
167
|
+
pass
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _fetch_tools(command: str, args: list[str]) -> tuple[list[dict], Optional[str]]:
|
|
171
|
+
"""Spawn the MCP server, handshake, call tools/list, kill. Returns (tools, error)."""
|
|
172
|
+
try:
|
|
173
|
+
proc = subprocess.Popen(
|
|
174
|
+
[command] + args,
|
|
175
|
+
stdin=subprocess.PIPE,
|
|
176
|
+
stdout=subprocess.PIPE,
|
|
177
|
+
stderr=subprocess.DEVNULL,
|
|
178
|
+
)
|
|
179
|
+
except (FileNotFoundError, PermissionError, OSError) as e:
|
|
180
|
+
return [], str(e)
|
|
181
|
+
|
|
182
|
+
tools: list[dict] = []
|
|
183
|
+
error: Optional[str] = None
|
|
184
|
+
try:
|
|
185
|
+
resp = _send_rpc(proc, 1, 'initialize', {
|
|
186
|
+
'protocolVersion': '2024-11-05',
|
|
187
|
+
'capabilities': {},
|
|
188
|
+
'clientInfo': {'name': 'mcpshield-agent', 'version': '1.0.0'},
|
|
189
|
+
})
|
|
190
|
+
if not resp or 'error' in resp:
|
|
191
|
+
error = f"initialize failed: {resp}"
|
|
192
|
+
else:
|
|
193
|
+
_notify(proc, 'notifications/initialized')
|
|
194
|
+
resp2 = _send_rpc(proc, 2, 'tools/list')
|
|
195
|
+
if resp2 and 'result' in resp2:
|
|
196
|
+
tools = resp2['result'].get('tools', [])
|
|
197
|
+
else:
|
|
198
|
+
error = f"tools/list: {resp2.get('error') if resp2 else 'no response'}"
|
|
199
|
+
except Exception as e:
|
|
200
|
+
error = str(e)
|
|
201
|
+
finally:
|
|
202
|
+
try:
|
|
203
|
+
proc.stdin.close()
|
|
204
|
+
proc.terminate()
|
|
205
|
+
proc.wait(timeout=3)
|
|
206
|
+
except Exception:
|
|
207
|
+
try:
|
|
208
|
+
proc.kill()
|
|
209
|
+
except Exception:
|
|
210
|
+
pass
|
|
211
|
+
|
|
212
|
+
return tools, error
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
# ---------------------------------------------------------------------------
|
|
216
|
+
# Public API
|
|
217
|
+
# ---------------------------------------------------------------------------
|
|
218
|
+
|
|
219
|
+
def deep_scan(server: dict) -> dict:
|
|
220
|
+
"""
|
|
221
|
+
Connect to an MCP server, fetch its tool list, scan descriptions for poisoning.
|
|
222
|
+
|
|
223
|
+
server: a dict from MCPScanner.scan() — needs 'command' (full command string).
|
|
224
|
+
|
|
225
|
+
Returns:
|
|
226
|
+
tools: list of {name, description} (truncated to 200 chars)
|
|
227
|
+
tool_count: int
|
|
228
|
+
tool_findings: list of {tool, score, reasons} for suspicious tools only
|
|
229
|
+
scan_error: str or None
|
|
230
|
+
"""
|
|
231
|
+
raw_command = server.get('command', '')
|
|
232
|
+
try:
|
|
233
|
+
parts = shlex.split(raw_command)
|
|
234
|
+
except ValueError:
|
|
235
|
+
parts = raw_command.split()
|
|
236
|
+
|
|
237
|
+
if not parts:
|
|
238
|
+
return {'tools': [], 'tool_count': 0, 'tool_findings': [], 'scan_error': 'no command'}
|
|
239
|
+
|
|
240
|
+
cmd, args = parts[0], parts[1:]
|
|
241
|
+
raw_tools, error = _fetch_tools(cmd, args)
|
|
242
|
+
|
|
243
|
+
findings = [f.to_dict() for t in raw_tools if (f := _scan_one(t))]
|
|
244
|
+
tools_summary = [
|
|
245
|
+
{'name': t.get('name'), 'description': (t.get('description') or '')[:200]}
|
|
246
|
+
for t in raw_tools
|
|
247
|
+
]
|
|
248
|
+
|
|
249
|
+
return {
|
|
250
|
+
'tools': tools_summary,
|
|
251
|
+
'tool_count': len(raw_tools),
|
|
252
|
+
'tool_findings': findings,
|
|
253
|
+
'scan_error': error,
|
|
254
|
+
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: mcpshield-agent
|
|
3
|
-
Version: 0.1
|
|
3
|
+
Version: 0.2.1
|
|
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
|
|
@@ -15,4 +14,5 @@ mcpshield_agent.egg-info/entry_points.txt
|
|
|
15
14
|
mcpshield_agent.egg-info/requires.txt
|
|
16
15
|
mcpshield_agent.egg-info/top_level.txt
|
|
17
16
|
tests/test_cli.py
|
|
17
|
+
tests/test_client.py
|
|
18
18
|
tests/test_scanner.py
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""
|
|
2
|
+
MCPShield Agent - API client tests.
|
|
3
|
+
|
|
4
|
+
Focused on the 402 (free-tier limit) path: the backend returns a useful JSON
|
|
5
|
+
body with the recorded servers + an upgrade message, and the client must
|
|
6
|
+
surface it rather than raising a generic HTTPError.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from unittest.mock import MagicMock, patch
|
|
10
|
+
|
|
11
|
+
import requests
|
|
12
|
+
|
|
13
|
+
from mcpshield_agent.client import MCPShieldClient
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _response(status_code: int, json_body: dict) -> MagicMock:
|
|
17
|
+
resp = MagicMock()
|
|
18
|
+
resp.status_code = status_code
|
|
19
|
+
resp.json.return_value = json_body
|
|
20
|
+
# Mirror requests' real behaviour: raise_for_status raises on >= 400.
|
|
21
|
+
if status_code >= 400:
|
|
22
|
+
resp.raise_for_status.side_effect = requests.exceptions.HTTPError(
|
|
23
|
+
f"{status_code} Client Error"
|
|
24
|
+
)
|
|
25
|
+
else:
|
|
26
|
+
resp.raise_for_status.return_value = None
|
|
27
|
+
return resp
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class TestReportServers402:
|
|
31
|
+
def test_402_returns_body_without_raising(self):
|
|
32
|
+
body = {
|
|
33
|
+
"created": 2,
|
|
34
|
+
"updated": 0,
|
|
35
|
+
"alerts": 1,
|
|
36
|
+
"servers": [],
|
|
37
|
+
"servers_skipped": 3,
|
|
38
|
+
"detail": "Free tier is limited to 50 MCP servers. Upgrade to Pro.",
|
|
39
|
+
}
|
|
40
|
+
client = MCPShieldClient("http://localhost:8000", "mcp_sk_test")
|
|
41
|
+
with patch.object(client.session, "post", return_value=_response(402, body)):
|
|
42
|
+
result = client.report_servers([{"server_name": "x"}])
|
|
43
|
+
|
|
44
|
+
# No exception, and the useful fields (esp. the upgrade message) survive.
|
|
45
|
+
assert result["servers_skipped"] == 3
|
|
46
|
+
assert "Upgrade to Pro" in result["detail"]
|
|
47
|
+
|
|
48
|
+
def test_200_still_returns_body(self):
|
|
49
|
+
body = {"created": 1, "updated": 0, "alerts": 0, "servers": [], "servers_skipped": 0}
|
|
50
|
+
client = MCPShieldClient("http://localhost:8000", "mcp_sk_test")
|
|
51
|
+
with patch.object(client.session, "post", return_value=_response(200, body)):
|
|
52
|
+
result = client.report_servers([{"server_name": "x"}])
|
|
53
|
+
assert result["created"] == 1
|
|
54
|
+
|
|
55
|
+
def test_500_still_raises(self):
|
|
56
|
+
client = MCPShieldClient("http://localhost:8000", "mcp_sk_test")
|
|
57
|
+
with patch.object(client.session, "post", return_value=_response(500, {})):
|
|
58
|
+
try:
|
|
59
|
+
client.report_servers([{"server_name": "x"}])
|
|
60
|
+
assert False, "expected HTTPError to propagate on 500"
|
|
61
|
+
except requests.exceptions.HTTPError:
|
|
62
|
+
pass
|