Skip to content

Commit 2b85712

Browse files
authored
fix(mcp-rug-pull): inspect npx commands in JSON configs (#776)
* fix(mcp-rug-pull): scan configured npx commands Signed-off-by: Efe <[email protected]> * fix(mcp-rug-pull): locate each server command Signed-off-by: Efe Gökdemir <[email protected]> --------- Signed-off-by: Efe <[email protected]> Signed-off-by: Efe Gökdemir <[email protected]>
1 parent ff0e77e commit 2b85712

2 files changed

Lines changed: 141 additions & 34 deletions

File tree

‎src/skillspector/nodes/analyzers/mcp_rug_pull.py‎

Lines changed: 86 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,10 @@
2222

2323
from __future__ import annotations
2424

25+
import json
2526
import re
2627
import time
28+
from collections.abc import Iterator
2729
from dataclasses import dataclass, field
2830

2931
from skillspector.inspection_ledger import (
@@ -217,6 +219,78 @@ def _operand_has_version_pin(line_remainder: str) -> bool:
217219
return _VERSION_PIN_RE.search(operand_suffix) is not None
218220

219221

222+
def _iter_config_commands(
223+
config: object, budget: _RugPullBudget, path: str, content: str
224+
) -> Iterator[tuple[str, int]]:
225+
"""Yield JSON command lines with the line of each command key."""
226+
command_keys = iter(re.finditer(r'(?<!\\)"command"\s*:', content))
227+
pending = [(iter(((None, config),)), None)]
228+
while pending:
229+
budget.check_runtime(path)
230+
items, owner = pending[-1]
231+
try:
232+
key, item = next(items)
233+
except StopIteration:
234+
pending.pop()
235+
continue
236+
237+
if key == "command" and owner is not None:
238+
key_match = next(command_keys, None)
239+
args = owner.get("args")
240+
if (
241+
isinstance(item, str)
242+
and isinstance(args, list)
243+
and all(isinstance(argument, str) for argument in args)
244+
):
245+
line = _find_line(content, key_match.start()) if key_match else 1
246+
yield " ".join([item, *args]), line
247+
248+
if isinstance(item, dict):
249+
pending.append((iter(item.items()), item))
250+
elif isinstance(item, list):
251+
pending.append((iter((None, value) for value in item), None))
252+
253+
254+
def _check_rp1_npx(
255+
content: str,
256+
file_path: str,
257+
budget: _RugPullBudget,
258+
line_number: int | None = None,
259+
) -> None:
260+
"""Report unpinned npx invocations in text or reconstructed config commands."""
261+
for match in _RP1_NPX_CMD.finditer(content):
262+
budget.check_runtime(file_path)
263+
full_match = match.group(0)
264+
line_end = content.find("\n", match.end())
265+
if line_end == -1:
266+
line_end = len(content)
267+
line_remainder = content[match.end() : min(line_end, match.end() + 256)]
268+
if _VERSION_PIN_RE.search(full_match) or _operand_has_version_pin(line_remainder):
269+
continue
270+
budget.emit(
271+
Finding(
272+
rule_id="RP1",
273+
message=(
274+
f"MCP server referenced without pinned version: '{full_match.strip()[:200]}'."
275+
),
276+
severity="MEDIUM",
277+
confidence=0.70,
278+
file=file_path,
279+
start_line=line_number or _find_line(content, match.start()),
280+
category=_CATEGORY,
281+
tags=list(_TAGS),
282+
matched_text=full_match[:200],
283+
match_fingerprint=compute_match_fingerprint("RP1", full_match),
284+
explanation=(
285+
"npx commands without a version suffix (e.g. @1.0.0) "
286+
"create a rug-pull risk if the upstream server is "
287+
"compromised and publishes a malicious update."
288+
),
289+
remediation="Pin the version: npx @scope/[email protected]",
290+
)
291+
)
292+
293+
220294
def _check_rp1(
221295
manifest: dict,
222296
file_cache: dict[str, str],
@@ -225,40 +299,18 @@ def _check_rp1(
225299
"""Detect unpinned MCP server command references in skill files."""
226300
for file_path, content in file_cache.items():
227301
budget.check_runtime(file_path)
228-
# npx without @version
229-
for m in _RP1_NPX_CMD.finditer(content):
230-
budget.check_runtime(file_path)
231-
full_match = m.group(0)
232-
line_end = content.find("\n", m.end())
233-
if line_end == -1:
234-
line_end = len(content)
235-
line_remainder = content[m.end() : min(line_end, m.end() + 256)]
236-
if _VERSION_PIN_RE.search(full_match) or _operand_has_version_pin(line_remainder):
237-
continue
238-
line_num = _find_line(content, m.start())
239-
budget.emit(
240-
Finding(
241-
rule_id="RP1",
242-
message=(
243-
"MCP server referenced without pinned version: "
244-
f"'{full_match.strip()[:200]}'."
245-
),
246-
severity="MEDIUM",
247-
confidence=0.70,
248-
file=file_path,
249-
start_line=line_num,
250-
category=_CATEGORY,
251-
tags=list(_TAGS),
252-
matched_text=full_match[:200],
253-
match_fingerprint=compute_match_fingerprint("RP1", full_match),
254-
explanation=(
255-
"npx commands without a version suffix (e.g. @1.0.0) "
256-
"create a rug-pull risk if the upstream server is "
257-
"compromised and publishes a malicious update."
258-
),
259-
remediation="Pin the version: npx @scope/[email protected]",
260-
)
261-
)
302+
_check_rp1_npx(content, file_path, budget)
303+
304+
if file_path.lower().endswith(".json"):
305+
try:
306+
config = json.loads(content)
307+
except (json.JSONDecodeError, RecursionError):
308+
config = None
309+
if config is not None:
310+
for command_line, command_line_number in _iter_config_commands(
311+
config, budget, file_path, content
312+
):
313+
_check_rp1_npx(command_line, file_path, budget, command_line_number)
262314

263315
# uvx without ==version
264316
for m in _RP1_UVX_CMD.finditer(content):

‎tests/nodes/analyzers/test_mcp_rug_pull.py‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,61 @@
2626
class TestMcpRugPullNode:
2727
"""Tests for the MCP rug-pull comparison logic."""
2828

29+
def test_rp1_unpinned_npx_in_mcp_server_config(self) -> None:
30+
"""RP1 inspects executable MCP command and args in JSON configs."""
31+
result = node(
32+
{
33+
"file_cache": {
34+
"mcp.json": (
35+
'{\n "mcpServers": {\n "context7": {\n'
36+
' "command": "npx",\n'
37+
' "args": ["-y", "@upstash/context7-mcp@latest"]\n'
38+
" }\n }\n}"
39+
)
40+
}
41+
}
42+
)
43+
44+
findings = [finding for finding in result["findings"] if finding.rule_id == "RP1"]
45+
assert len(findings) == 1
46+
assert findings[0].file == "mcp.json"
47+
assert findings[0].start_line == 4
48+
assert findings[0].matched_text == "npx -y @upstash/context7-mcp"
49+
50+
def test_rp1_pinned_npx_in_mcp_server_config(self) -> None:
51+
"""RP1 accepts an MCP command whose package operand is version-pinned."""
52+
result = node(
53+
{
54+
"file_cache": {
55+
"mcp.json": '{"mcpServers":{"context7":{"command":"npx",'
56+
'"args":["-y","@upstash/[email protected]"]}}}'
57+
}
58+
}
59+
)
60+
61+
assert not [finding for finding in result["findings"] if finding.rule_id == "RP1"]
62+
63+
def test_rp1_json_config_attributes_finding_to_matching_server(self) -> None:
64+
"""RP1 points to the npx server when it is not the first configured server."""
65+
result = node(
66+
{
67+
"file_cache": {
68+
"mcp.json": (
69+
'{\n "mcpServers": {\n "local": {\n'
70+
' "command": "node",\n "args": ["server.js"]\n'
71+
' },\n "context7": {\n "command": "npx",\n'
72+
' "args": ["-y", "@upstash/context7-mcp"]\n'
73+
" }\n }\n}"
74+
)
75+
}
76+
}
77+
)
78+
79+
findings = [finding for finding in result["findings"] if finding.rule_id == "RP1"]
80+
assert len(findings) == 1
81+
assert findings[0].start_line == 8
82+
assert findings[0].matched_text == "npx -y @upstash/context7-mcp"
83+
2984
def test_no_previous_manifest_skips(self) -> None:
3085
"""Returns empty findings when previous_manifest is absent."""
3186
state = {

0 commit comments

Comments
 (0)