mcpshield-agent 0.2.0__tar.gz → 0.3.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.
Files changed (23) hide show
  1. {mcpshield_agent-0.2.0 → mcpshield_agent-0.3.0}/PKG-INFO +34 -8
  2. {mcpshield_agent-0.2.0 → mcpshield_agent-0.3.0}/README.md +33 -7
  3. mcpshield_agent-0.3.0/mcpshield_agent/__init__.py +10 -0
  4. {mcpshield_agent-0.2.0 → mcpshield_agent-0.3.0}/mcpshield_agent/cli.py +39 -14
  5. {mcpshield_agent-0.2.0 → mcpshield_agent-0.3.0}/mcpshield_agent/client.py +11 -3
  6. mcpshield_agent-0.3.0/mcpshield_agent/risk_scorer.py +340 -0
  7. {mcpshield_agent-0.2.0 → mcpshield_agent-0.3.0}/mcpshield_agent/tool_scanner.py +6 -0
  8. {mcpshield_agent-0.2.0 → mcpshield_agent-0.3.0}/mcpshield_agent.egg-info/PKG-INFO +34 -8
  9. {mcpshield_agent-0.2.0 → mcpshield_agent-0.3.0}/mcpshield_agent.egg-info/SOURCES.txt +3 -0
  10. mcpshield_agent-0.3.0/tests/test_client.py +62 -0
  11. mcpshield_agent-0.3.0/tests/test_risk_scorer.py +58 -0
  12. mcpshield_agent-0.2.0/mcpshield_agent/__init__.py +0 -5
  13. {mcpshield_agent-0.2.0 → mcpshield_agent-0.3.0}/mcpshield_agent/__main__.py +0 -0
  14. {mcpshield_agent-0.2.0 → mcpshield_agent-0.3.0}/mcpshield_agent/config.py +0 -0
  15. {mcpshield_agent-0.2.0 → mcpshield_agent-0.3.0}/mcpshield_agent/scanner.py +0 -0
  16. {mcpshield_agent-0.2.0 → mcpshield_agent-0.3.0}/mcpshield_agent.egg-info/dependency_links.txt +0 -0
  17. {mcpshield_agent-0.2.0 → mcpshield_agent-0.3.0}/mcpshield_agent.egg-info/entry_points.txt +0 -0
  18. {mcpshield_agent-0.2.0 → mcpshield_agent-0.3.0}/mcpshield_agent.egg-info/requires.txt +0 -0
  19. {mcpshield_agent-0.2.0 → mcpshield_agent-0.3.0}/mcpshield_agent.egg-info/top_level.txt +0 -0
  20. {mcpshield_agent-0.2.0 → mcpshield_agent-0.3.0}/pyproject.toml +0 -0
  21. {mcpshield_agent-0.2.0 → mcpshield_agent-0.3.0}/setup.cfg +0 -0
  22. {mcpshield_agent-0.2.0 → mcpshield_agent-0.3.0}/tests/test_cli.py +0 -0
  23. {mcpshield_agent-0.2.0 → mcpshield_agent-0.3.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.2.0
3
+ Version: 0.3.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
@@ -46,23 +46,49 @@ pip install -e .
46
46
  ## Quick Start
47
47
 
48
48
  ```bash
49
- # 1. Configure with your API key (get from dashboard)
50
- mcpshield configure --api-key mcp_sk_your_key_here
51
-
52
- # 2. Scan for MCP servers
49
+ # Scan your machine and see a local risk score. No account needed.
50
+ pip install mcpshield-agent
53
51
  mcpshield scan
52
+ ```
54
53
 
55
- # 3. Check status
54
+ `mcpshield scan` discovers your MCP servers and prints a 0-100 risk score for
55
+ each, computed locally. Sign up (free) and `configure --api-key` to add CISA KEV
56
+ enrichment, org-wide tracking, history, and alerts:
57
+
58
+ ```bash
59
+ mcpshield configure --api-key mcp_sk_your_key_here
60
+ mcpshield scan # now also reports to the dashboard
56
61
  mcpshield status
57
62
  ```
58
63
 
64
+ ## Embed the scorer
65
+
66
+ The risk scorer is a pure function you can drop into any runtime to score an MCP
67
+ server config in three lines:
68
+
69
+ ```python
70
+ from mcpshield_agent import score_config, risk_level
71
+
72
+ result = score_config({
73
+ "server_type": "@modelcontextprotocol/server-filesystem",
74
+ "command": "npx -y @modelcontextprotocol/server-filesystem /",
75
+ "scope": "/",
76
+ "env_vars": ["AWS_SECRET_ACCESS_KEY"],
77
+ })
78
+ # {"score": 100.0, "level": "critical", "factors": [...], "details": {...}}
79
+ ```
80
+
81
+ It is the same weighted model as the hosted engine (minus CISA KEV enrichment,
82
+ which stays server-side) and has no network dependency.
83
+
59
84
  ## Commands
60
85
 
61
86
  | Command | Description |
62
87
  |---------|-------------|
63
88
  | `mcpshield configure --api-key KEY` | Configure agent with API key |
64
- | `mcpshield scan` | Scan and report MCP servers |
65
- | `mcpshield scan --dry-run` | Scan without reporting |
89
+ | `mcpshield scan` | Scan and score locally; also report if configured |
90
+ | `mcpshield scan --deep` | Also connect to active servers and scan tool descriptions |
91
+ | `mcpshield scan --dry-run` | Scan and score locally, never report |
66
92
  | `mcpshield daemon` | Run continuous scheduled scanning |
67
93
  | `mcpshield status` | Show agent status |
68
94
  | `mcpshield list` | List found servers (no report) |
@@ -15,23 +15,49 @@ pip install -e .
15
15
  ## Quick Start
16
16
 
17
17
  ```bash
18
- # 1. Configure with your API key (get from dashboard)
19
- mcpshield configure --api-key mcp_sk_your_key_here
20
-
21
- # 2. Scan for MCP servers
18
+ # Scan your machine and see a local risk score. No account needed.
19
+ pip install mcpshield-agent
22
20
  mcpshield scan
21
+ ```
23
22
 
24
- # 3. Check status
23
+ `mcpshield scan` discovers your MCP servers and prints a 0-100 risk score for
24
+ each, computed locally. Sign up (free) and `configure --api-key` to add CISA KEV
25
+ enrichment, org-wide tracking, history, and alerts:
26
+
27
+ ```bash
28
+ mcpshield configure --api-key mcp_sk_your_key_here
29
+ mcpshield scan # now also reports to the dashboard
25
30
  mcpshield status
26
31
  ```
27
32
 
33
+ ## Embed the scorer
34
+
35
+ The risk scorer is a pure function you can drop into any runtime to score an MCP
36
+ server config in three lines:
37
+
38
+ ```python
39
+ from mcpshield_agent import score_config, risk_level
40
+
41
+ result = score_config({
42
+ "server_type": "@modelcontextprotocol/server-filesystem",
43
+ "command": "npx -y @modelcontextprotocol/server-filesystem /",
44
+ "scope": "/",
45
+ "env_vars": ["AWS_SECRET_ACCESS_KEY"],
46
+ })
47
+ # {"score": 100.0, "level": "critical", "factors": [...], "details": {...}}
48
+ ```
49
+
50
+ It is the same weighted model as the hosted engine (minus CISA KEV enrichment,
51
+ which stays server-side) and has no network dependency.
52
+
28
53
  ## Commands
29
54
 
30
55
  | Command | Description |
31
56
  |---------|-------------|
32
57
  | `mcpshield configure --api-key KEY` | Configure agent with API key |
33
- | `mcpshield scan` | Scan and report MCP servers |
34
- | `mcpshield scan --dry-run` | Scan without reporting |
58
+ | `mcpshield scan` | Scan and score locally; also report if configured |
59
+ | `mcpshield scan --deep` | Also connect to active servers and scan tool descriptions |
60
+ | `mcpshield scan --dry-run` | Scan and score locally, never report |
35
61
  | `mcpshield daemon` | Run continuous scheduled scanning |
36
62
  | `mcpshield status` | Show agent status |
37
63
  | `mcpshield list` | List found servers (no report) |
@@ -0,0 +1,10 @@
1
+ """MCPShield Agent - AI Agent Security Scanner"""
2
+
3
+ __version__ = "0.3.0"
4
+ __author__ = "David Cooper"
5
+ __email__ = "hello@mcpshield.app"
6
+
7
+ from .risk_scorer import score_config, risk_level
8
+ from .scanner import MCPScanner
9
+
10
+ __all__ = ["score_config", "risk_level", "MCPScanner", "__version__"]
@@ -9,6 +9,7 @@ from .scanner import MCPScanner
9
9
  from .client import MCPShieldClient
10
10
  from .config import Config
11
11
  from .tool_scanner import deep_scan
12
+ from .risk_scorer import score_config
12
13
  from . import __version__
13
14
 
14
15
 
@@ -25,7 +26,7 @@ def cli():
25
26
 
26
27
  @cli.command()
27
28
  @click.option('--api-key', required=True, help='Your MCPShield API key from dashboard')
28
- @click.option('--api-url', default='http://localhost:8000', help='API URL (default: localhost:8000)')
29
+ @click.option('--api-url', default='https://api.mcpshield.app', help='API URL (default: https://api.mcpshield.app)')
29
30
  def configure(api_key: str, api_url: str):
30
31
  """Configure agent with API key"""
31
32
 
@@ -66,14 +67,11 @@ def configure(api_key: str, api_url: str):
66
67
  def scan(dry_run: bool, deep: bool):
67
68
  """Scan for MCP servers and report to API"""
68
69
 
69
- # Load config
70
+ # Load config. A local scan + risk score needs no API key; only reporting
71
+ # to the hosted backend (for KEV enrichment and org-wide tracking) does.
70
72
  config = Config.load()
71
73
  api_key = config.get('api_key')
72
74
 
73
- if not api_key and not dry_run:
74
- click.echo("Error: Not configured. Run: mcpshield configure --api-key YOUR_KEY")
75
- return
76
-
77
75
  # Scan for servers
78
76
  click.echo("Scanning for MCP servers...")
79
77
  scanner = MCPScanner()
@@ -101,6 +99,10 @@ def scan(dry_run: bool, deep: bool):
101
99
  server['scan_error'] = result['scan_error']
102
100
  click.echo("")
103
101
 
102
+ # Score every server locally — no API key required.
103
+ for server in servers:
104
+ server['risk'] = score_config(server)
105
+
104
106
  click.echo(f"Found {len(servers)} MCP server(s):")
105
107
  click.echo("")
106
108
 
@@ -108,6 +110,10 @@ def scan(dry_run: bool, deep: bool):
108
110
  for server in servers:
109
111
  status_icon = "[active]" if server['status'] == 'active' else "[dormant]"
110
112
  click.echo(f" {server['server_name']} {status_icon}")
113
+ risk = server['risk']
114
+ click.echo(f" Risk: {risk['score']} ({risk['level']})")
115
+ if risk['factors']:
116
+ click.echo(f" Why: {'; '.join(risk['factors'][:3])}")
111
117
  click.echo(f" Type: {server['server_type']}")
112
118
  if server.get('scope'):
113
119
  click.echo(f" Scope: {server['scope']}")
@@ -134,8 +140,13 @@ def scan(dry_run: bool, deep: bool):
134
140
  if dry_run:
135
141
  click.echo("(Dry run - not reporting to API)")
136
142
  return
137
-
138
- # Report to API
143
+
144
+ if not api_key:
145
+ click.echo("Not signed in. Local scan only.")
146
+ click.echo("Sign up free at https://mcpshield.app for CISA KEV enrichment, org-wide tracking, history, and alerts.")
147
+ return
148
+
149
+ # Report to API (backend adds CISA KEV enrichment + org-wide correlation)
139
150
  click.echo("Reporting to MCPShield...")
140
151
  client = MCPShieldClient(config['api_url'], api_key)
141
152
 
@@ -151,13 +162,17 @@ def scan(dry_run: bool, deep: bool):
151
162
 
152
163
  # Report servers
153
164
  result = client.report_servers(servers)
154
-
165
+
166
+ skipped = result.get('servers_skipped', 0)
155
167
  click.echo("")
156
- click.echo("Success!")
168
+ if skipped:
169
+ click.echo(f"Reported ({skipped} server(s) not recorded — plan limit reached)")
170
+ else:
171
+ click.echo("Success!")
157
172
  click.echo(f" Created: {result.get('created', 0)}")
158
173
  click.echo(f" Updated: {result.get('updated', 0)}")
159
174
  click.echo(f" Alerts: {result.get('alerts', 0)}")
160
-
175
+
161
176
  # Show risk info if available
162
177
  if 'servers' in result:
163
178
  click.echo("")
@@ -166,7 +181,12 @@ def scan(dry_run: bool, deep: bool):
166
181
  risk = s.get('risk_level', 'unknown')
167
182
  score = s.get('risk_score', 0)
168
183
  click.echo(f" {s['server_name']}: {risk} (score: {score})")
169
-
184
+
185
+ # Surface the backend's upgrade message on a hit tier limit (HTTP 402).
186
+ if skipped and result.get('detail'):
187
+ click.echo("")
188
+ click.echo(result['detail'])
189
+
170
190
  except Exception as e:
171
191
  click.echo(f"Error: Failed to report - {e}")
172
192
 
@@ -324,8 +344,13 @@ def daemon(interval: int):
324
344
 
325
345
  client.heartbeat(hostname, os_type, username, ip, __version__)
326
346
  result = client.report_servers(servers)
327
-
328
- if result:
347
+
348
+ if result and result.get('servers_skipped'):
349
+ click.echo(
350
+ f"[Cycle {cycle}] Reported — {result['servers_skipped']} "
351
+ "server(s) not recorded (plan limit reached)"
352
+ )
353
+ elif result:
329
354
  click.echo(f"[Cycle {cycle}] Reported to backend successfully")
330
355
  else:
331
356
  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
 
@@ -0,0 +1,340 @@
1
+ """
2
+ MCPShield Agent - Local Risk Scoring Engine
3
+
4
+ Computes the base 0-100 risk score for an MCP server locally, with no network
5
+ call and no API key. This is the same weighted model as the canonical backend
6
+ engine (backend/app/utils/risk_scorer.py), minus the CISA KEV / CVE enrichment,
7
+ which stays server-side because it needs a maintained feed.
8
+
9
+ local score = base (server_type + command + scope + tools + env + poisoning)
10
+ hosted score = base + KEV enrichment
11
+
12
+ Kept in parity with the backend engine via test-fixtures/risk_scoring_cases.json.
13
+ Pure stdlib (os, re); safe to embed in any runtime.
14
+
15
+ from mcpshield_agent import score_config, risk_level
16
+ result = score_config(server_dict) # {"score", "level", "factors", "details"}
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import os
21
+ import re
22
+ from typing import Any
23
+
24
+
25
+ def _dedupe_preserving_order(values: list[str]) -> list[str]:
26
+ seen: set = set()
27
+ result: list[str] = []
28
+ for v in values:
29
+ if v not in seen:
30
+ seen.add(v)
31
+ result.append(v)
32
+ return result
33
+
34
+
35
+ # =============================================================================
36
+ # Compiled regex patterns — built once at module load
37
+ # =============================================================================
38
+
39
+ _HIGH_RISK_RE = re.compile(
40
+ r'\b(?:execute|shell|bash|cmd|command|run|eval|script|system|process|spawn|fork|terminal)\b',
41
+ re.IGNORECASE,
42
+ )
43
+
44
+ _FILESYSTEM_WRITE_RE = re.compile(
45
+ r'\b(?:write|delete|remove|create|modify|edit|move|rename|copy|mkdir|rmdir|truncate)\b',
46
+ re.IGNORECASE,
47
+ )
48
+
49
+ _NETWORK_RE = re.compile(
50
+ r'\b(?:http|fetch|request|api|curl|socket|connect|download|upload|send|post|get)\b',
51
+ re.IGNORECASE,
52
+ )
53
+
54
+ _SENSITIVE_ENV_RE = re.compile(
55
+ r'(?:password|secret|key|token|credential|auth|api_key|apikey|private|access)',
56
+ re.IGNORECASE,
57
+ )
58
+
59
+ # Server-type pattern sets (kept as sets for O(1) substring check on short strings)
60
+ _SHELL_TYPE_PATTERNS = frozenset(["shell", "terminal", "command", "exec"])
61
+ _NETWORK_TYPE_PATTERNS = frozenset(["http", "fetch", "api", "browser"])
62
+ _DB_TYPE_PATTERNS = frozenset(["postgres", "mysql", "sqlite", "mongo", "database"])
63
+
64
+ # High-risk exact tool names
65
+ _HIGH_RISK_TOOL_NAMES = frozenset([
66
+ "execute_command", "run_shell", "bash_execute", "powershell",
67
+ "exec", "shell_command", "run_command", "terminal_exec",
68
+ ])
69
+
70
+ # Sensitive paths — kept as a list since order can matter for break-on-first-match
71
+ SENSITIVE_PATHS = [
72
+ "/etc", "/root", "/home", "~/.ssh", "~/.aws", "~/.config",
73
+ "/var/log", "/var/run", "/tmp", "/private",
74
+ "C:\\Windows", "C:\\Users", "C:\\Program Files",
75
+ "%APPDATA%", "%USERPROFILE%", "%SYSTEMROOT%",
76
+ ]
77
+
78
+ # Shell command names for command analysis
79
+ _SHELL_NAMES = frozenset(["bash", "sh", "zsh", "fish", "cmd", "powershell", "pwsh"])
80
+
81
+ # Risk weights (base model — CVE/KEV weights live in the hosted backend)
82
+ WEIGHTS = {
83
+ "shell_command": 35,
84
+ "high_risk_tool": 25,
85
+ "filesystem_write": 15,
86
+ "network_access": 10,
87
+ "sensitive_path": 20,
88
+ "sensitive_env": 15,
89
+ "many_tools": 5,
90
+ "no_description": 3,
91
+ "docker_access": 20,
92
+ "database_access": 15,
93
+ }
94
+
95
+
96
+ # =============================================================================
97
+ # Public API
98
+ # =============================================================================
99
+
100
+ def score_config(server: dict) -> dict:
101
+ """Calculate the local base risk score for an MCP server.
102
+
103
+ Args:
104
+ server: a dict describing the server, as produced by MCPScanner.scan()
105
+ (and deep_scan for `tools`/`tool_findings`). Recognized keys:
106
+ server_type, command, scope, tools (list of {name, description}),
107
+ env_vars (list[str]), tool_findings (list of {tool, score, reasons}).
108
+
109
+ Returns:
110
+ dict with keys: score (0-100 float), level (str), factors (list[str]),
111
+ details (dict).
112
+ """
113
+ score = 0.0
114
+ factors: list[str] = []
115
+ details: dict[str, Any] = {}
116
+
117
+ def _apply(section: str, result: dict[str, Any]) -> None:
118
+ nonlocal score
119
+ score += result["score"]
120
+ factors.extend(result["factors"])
121
+ details[section] = result
122
+
123
+ if server.get("server_type"):
124
+ _apply("server_type", _analyze_server_type(server["server_type"]))
125
+
126
+ if server.get("command"):
127
+ _apply("command", _analyze_command(server["command"]))
128
+
129
+ if server.get("scope"):
130
+ _apply("scope", _analyze_scope(server["scope"]))
131
+
132
+ if server.get("tools"):
133
+ _apply("tools", _analyze_tools(server["tools"]))
134
+
135
+ if server.get("env_vars"):
136
+ _apply("env_vars", _analyze_env_vars(server["env_vars"]))
137
+
138
+ if server.get("tool_findings"):
139
+ _apply("tool_poisoning", _analyze_tool_findings(server["tool_findings"]))
140
+
141
+ score = min(100.0, score)
142
+ rounded = round(score, 1)
143
+
144
+ return {
145
+ "score": rounded,
146
+ "level": risk_level(rounded),
147
+ "factors": _dedupe_preserving_order(factors),
148
+ "details": details,
149
+ }
150
+
151
+
152
+ def risk_level(score: float) -> str:
153
+ """Convert a numeric risk score to a risk level label."""
154
+ if score >= 85:
155
+ return "critical"
156
+ if score >= 60:
157
+ return "high"
158
+ if score >= 30:
159
+ return "medium"
160
+ return "low"
161
+
162
+
163
+ # =============================================================================
164
+ # Private helpers
165
+ # =============================================================================
166
+
167
+ def _analyze_server_type(server_type: str) -> dict[str, Any]:
168
+ score = 0.0
169
+ factors: list[str] = []
170
+ t = server_type.lower()
171
+
172
+ if any(p in t for p in _SHELL_TYPE_PATTERNS):
173
+ score += WEIGHTS["shell_command"]
174
+ factors.append("Shell/command execution capability")
175
+
176
+ if "filesystem" in t or "file" in t:
177
+ score += WEIGHTS["filesystem_write"]
178
+ factors.append("Filesystem access")
179
+
180
+ if any(p in t for p in _DB_TYPE_PATTERNS):
181
+ score += WEIGHTS["database_access"]
182
+ factors.append("Database access")
183
+
184
+ if "docker" in t or "container" in t:
185
+ score += WEIGHTS["docker_access"]
186
+ factors.append("Docker/container access")
187
+
188
+ if any(p in t for p in _NETWORK_TYPE_PATTERNS):
189
+ score += WEIGHTS["network_access"]
190
+ factors.append("Network/HTTP access")
191
+
192
+ return {"score": score, "factors": factors}
193
+
194
+
195
+ def _analyze_command(command: str) -> dict[str, Any]:
196
+ score = 0.0
197
+ factors: list[str] = []
198
+ parts = command.lower().split()
199
+
200
+ # Check first token's basename for shell executables
201
+ if parts:
202
+ basename = os.path.basename(parts[0])
203
+ if basename in _SHELL_NAMES:
204
+ score += WEIGHTS["shell_command"]
205
+ factors.append(f"Direct shell execution ({basename})")
206
+
207
+ if "docker" in command.lower() and "run" in command.lower():
208
+ score += WEIGHTS["docker_access"]
209
+ factors.append("Docker container execution")
210
+
211
+ if "sudo" in command.lower():
212
+ score += 15
213
+ factors.append("Elevated privileges (sudo)")
214
+
215
+ return {"score": score, "factors": factors}
216
+
217
+
218
+ def _analyze_scope(scope: str) -> dict[str, Any]:
219
+ score = 0.0
220
+ factors: list[str] = []
221
+ scope_lower = scope.lower()
222
+
223
+ # Root / drive root
224
+ if scope in ("/", "C:\\", "C:/"):
225
+ score += WEIGHTS["sensitive_path"] * 1.5
226
+ factors.append("Root filesystem access")
227
+ else:
228
+ for sensitive in SENSITIVE_PATHS:
229
+ if sensitive.lower() in scope_lower:
230
+ score += WEIGHTS["sensitive_path"]
231
+ factors.append(f"Access to sensitive path: {sensitive}")
232
+ break
233
+
234
+ # Home directory (only if not already caught above)
235
+ if not factors and (scope.startswith("~") or "/home/" in scope or "/Users/" in scope):
236
+ score += WEIGHTS["sensitive_path"] * 0.5
237
+ factors.append("Home directory access")
238
+
239
+ return {"score": score, "factors": factors}
240
+
241
+
242
+ def _analyze_tools(tools: list) -> dict[str, Any]:
243
+ """Analyse MCP tools for risk signals. Single regex pass per tool."""
244
+ score = 0.0
245
+ high_risk_tools: list[str] = []
246
+ write_tools: list[str] = []
247
+ network_tools: list[str] = []
248
+
249
+ for tool in tools:
250
+ name = tool.get("name") or ""
251
+ name_lower = name.lower()
252
+ desc = tool.get("description") or ""
253
+ text = f"{name_lower} {desc.lower()}"
254
+
255
+ # Exact name match (O(1) set lookup)
256
+ is_high_risk = name_lower in _HIGH_RISK_TOOL_NAMES
257
+
258
+ # Regex match on combined name+description — one pass each
259
+ if not is_high_risk and _HIGH_RISK_RE.search(text):
260
+ is_high_risk = True
261
+
262
+ if is_high_risk:
263
+ score += WEIGHTS["high_risk_tool"]
264
+ high_risk_tools.append(name)
265
+
266
+ if _FILESYSTEM_WRITE_RE.search(text):
267
+ score += WEIGHTS["filesystem_write"]
268
+ write_tools.append(name)
269
+
270
+ if _NETWORK_RE.search(text):
271
+ score += WEIGHTS["network_access"]
272
+ network_tools.append(name)
273
+
274
+ if not desc:
275
+ score += WEIGHTS["no_description"]
276
+
277
+ # Many-tools penalty
278
+ if len(tools) > 10:
279
+ score += ((len(tools) - 10) // 5) * WEIGHTS["many_tools"]
280
+
281
+ # Cap tool-based contribution to prevent over-scoring from many similar tools
282
+ score = min(50.0, score)
283
+
284
+ factors: list[str] = []
285
+ if high_risk_tools:
286
+ factors.append(f"High-risk tools: {', '.join(high_risk_tools[:3])}")
287
+ if write_tools:
288
+ factors.append(f"Filesystem modification: {', '.join(write_tools[:3])}")
289
+ if network_tools:
290
+ factors.append(f"Network access: {', '.join(network_tools[:3])}")
291
+ if len(tools) > 15:
292
+ factors.append(f"Large tool surface ({len(tools)} tools)")
293
+
294
+ return {
295
+ "score": score,
296
+ "factors": factors,
297
+ "high_risk_tools": high_risk_tools,
298
+ "write_tools": write_tools,
299
+ "network_tools": network_tools,
300
+ "total_tools": len(tools),
301
+ }
302
+
303
+
304
+ def _analyze_env_vars(env_vars: list) -> dict[str, Any]:
305
+ """Analyse environment variable names for credential exposure risk."""
306
+ score = 0.0
307
+ sensitive_vars: list[str] = []
308
+
309
+ for var_name in env_vars:
310
+ if _SENSITIVE_ENV_RE.search(var_name):
311
+ score += WEIGHTS["sensitive_env"]
312
+ sensitive_vars.append(var_name)
313
+
314
+ factors: list[str] = []
315
+ if sensitive_vars:
316
+ factors.append(f"Sensitive env vars: {', '.join(sensitive_vars[:3])}")
317
+
318
+ return {"score": score, "factors": factors, "sensitive_vars": sensitive_vars}
319
+
320
+
321
+ def _analyze_tool_findings(findings: list) -> dict[str, Any]:
322
+ """Score tool-poisoning findings from a --deep scan.
323
+
324
+ Each finding: {tool: str, score: float, reasons: list[str]}.
325
+ """
326
+ if not findings:
327
+ return {"score": 0.0, "factors": []}
328
+
329
+ # Weight each finding by its heuristic score; cap total contribution at 40
330
+ raw = sum(min(1.0, f.get("score", 0)) for f in findings) * 30
331
+ score = min(40.0, raw)
332
+
333
+ poisoned_names = [f["tool"] for f in findings if f.get("score", 0) > 0]
334
+ factors: list[str] = [
335
+ f"Tool description poisoning detected: {', '.join(poisoned_names[:3])}"
336
+ ]
337
+ if len(findings) > 1:
338
+ factors.append(f"{len(findings)} tools with injected instructions")
339
+
340
+ return {"score": score, "factors": factors, "poisoned_tools": poisoned_names}
@@ -7,6 +7,12 @@ malicious server hides side-instructions in tool descriptions that the
7
7
  agent ingests as context).
8
8
 
9
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.
10
16
  """
11
17
 
12
18
  import json
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mcpshield-agent
3
- Version: 0.2.0
3
+ Version: 0.3.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
@@ -46,23 +46,49 @@ pip install -e .
46
46
  ## Quick Start
47
47
 
48
48
  ```bash
49
- # 1. Configure with your API key (get from dashboard)
50
- mcpshield configure --api-key mcp_sk_your_key_here
51
-
52
- # 2. Scan for MCP servers
49
+ # Scan your machine and see a local risk score. No account needed.
50
+ pip install mcpshield-agent
53
51
  mcpshield scan
52
+ ```
54
53
 
55
- # 3. Check status
54
+ `mcpshield scan` discovers your MCP servers and prints a 0-100 risk score for
55
+ each, computed locally. Sign up (free) and `configure --api-key` to add CISA KEV
56
+ enrichment, org-wide tracking, history, and alerts:
57
+
58
+ ```bash
59
+ mcpshield configure --api-key mcp_sk_your_key_here
60
+ mcpshield scan # now also reports to the dashboard
56
61
  mcpshield status
57
62
  ```
58
63
 
64
+ ## Embed the scorer
65
+
66
+ The risk scorer is a pure function you can drop into any runtime to score an MCP
67
+ server config in three lines:
68
+
69
+ ```python
70
+ from mcpshield_agent import score_config, risk_level
71
+
72
+ result = score_config({
73
+ "server_type": "@modelcontextprotocol/server-filesystem",
74
+ "command": "npx -y @modelcontextprotocol/server-filesystem /",
75
+ "scope": "/",
76
+ "env_vars": ["AWS_SECRET_ACCESS_KEY"],
77
+ })
78
+ # {"score": 100.0, "level": "critical", "factors": [...], "details": {...}}
79
+ ```
80
+
81
+ It is the same weighted model as the hosted engine (minus CISA KEV enrichment,
82
+ which stays server-side) and has no network dependency.
83
+
59
84
  ## Commands
60
85
 
61
86
  | Command | Description |
62
87
  |---------|-------------|
63
88
  | `mcpshield configure --api-key KEY` | Configure agent with API key |
64
- | `mcpshield scan` | Scan and report MCP servers |
65
- | `mcpshield scan --dry-run` | Scan without reporting |
89
+ | `mcpshield scan` | Scan and score locally; also report if configured |
90
+ | `mcpshield scan --deep` | Also connect to active servers and scan tool descriptions |
91
+ | `mcpshield scan --dry-run` | Scan and score locally, never report |
66
92
  | `mcpshield daemon` | Run continuous scheduled scanning |
67
93
  | `mcpshield status` | Show agent status |
68
94
  | `mcpshield list` | List found servers (no report) |
@@ -5,6 +5,7 @@ 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/risk_scorer.py
8
9
  mcpshield_agent/scanner.py
9
10
  mcpshield_agent/tool_scanner.py
10
11
  mcpshield_agent.egg-info/PKG-INFO
@@ -14,4 +15,6 @@ mcpshield_agent.egg-info/entry_points.txt
14
15
  mcpshield_agent.egg-info/requires.txt
15
16
  mcpshield_agent.egg-info/top_level.txt
16
17
  tests/test_cli.py
18
+ tests/test_client.py
19
+ tests/test_risk_scorer.py
17
20
  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
@@ -0,0 +1,58 @@
1
+ """
2
+ MCPShield Agent - Local risk scorer tests.
3
+
4
+ Covers the public embed API (score_config / risk_level) and confirms the local
5
+ base scorer reproduces the shared cross-runtime fixtures.
6
+ """
7
+ import json
8
+ from pathlib import Path
9
+
10
+ import pytest
11
+
12
+ from mcpshield_agent import score_config, risk_level
13
+
14
+ _FIXTURES = Path(__file__).resolve().parents[2] / "test-fixtures" / "risk_scoring_cases.json"
15
+
16
+
17
+ def _load_cases():
18
+ return json.loads(_FIXTURES.read_text(encoding="utf-8"))
19
+
20
+
21
+ @pytest.mark.parametrize("case", _load_cases(), ids=lambda c: c["name"])
22
+ def test_matches_shared_fixtures(case):
23
+ """Local base scorer must match the canonical (KEV-free) fixture scores."""
24
+ result = score_config(case)
25
+ assert result["score"] == case["expected_score"]
26
+ assert result["level"] == case["expected_level"]
27
+
28
+
29
+ def test_return_shape():
30
+ result = score_config({"server_type": "custom-notes"})
31
+ assert set(result) == {"score", "level", "factors", "details"}
32
+ assert isinstance(result["score"], float)
33
+ assert isinstance(result["factors"], list)
34
+
35
+
36
+ def test_empty_server_is_low_risk():
37
+ result = score_config({})
38
+ assert result["score"] == 0.0
39
+ assert result["level"] == "low"
40
+
41
+
42
+ def test_shell_server_is_flagged():
43
+ result = score_config({"server_type": "shell", "command": "bash -c 'echo hi'"})
44
+ assert result["score"] > 0
45
+ assert any("shell" in f.lower() for f in result["factors"])
46
+
47
+
48
+ def test_missing_keys_do_not_raise():
49
+ # A partial dict (e.g. config-only scan, no tools/env) must score fine.
50
+ score_config({"command": "npx -y @modelcontextprotocol/server-filesystem /home/user"})
51
+
52
+
53
+ @pytest.mark.parametrize(
54
+ "score,level",
55
+ [(0, "low"), (29.9, "low"), (30, "medium"), (60, "high"), (85, "critical"), (100, "critical")],
56
+ )
57
+ def test_risk_level_thresholds(score, level):
58
+ assert risk_level(score) == level
@@ -1,5 +0,0 @@
1
- """MCPShield Agent - AI Agent Security Scanner"""
2
-
3
- __version__ = "0.2.0"
4
- __author__ = "David Cooper"
5
- __email__ = "hello@mcpshield.app"