mcpcheck-cli 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mcpcheck/__init__.py +3 -0
- mcpcheck/cli.py +404 -0
- mcpcheck/config.py +183 -0
- mcpcheck/doctor.py +245 -0
- mcpcheck/lockfile.py +138 -0
- mcpcheck/probe.py +170 -0
- mcpcheck/protocol.py +303 -0
- mcpcheck_cli-0.1.0.dist-info/METADATA +167 -0
- mcpcheck_cli-0.1.0.dist-info/RECORD +13 -0
- mcpcheck_cli-0.1.0.dist-info/WHEEL +5 -0
- mcpcheck_cli-0.1.0.dist-info/entry_points.txt +2 -0
- mcpcheck_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
- mcpcheck_cli-0.1.0.dist-info/top_level.txt +1 -0
mcpcheck/doctor.py
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
"""Doctor findings: aggregate probe results and flag risky configurations.
|
|
2
|
+
|
|
3
|
+
Pure logic: every function takes plain data and returns plain data, no I/O.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import re
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
SEVERITIES = ("error", "warn", "info")
|
|
12
|
+
TOOL_LIMIT = 30
|
|
13
|
+
SECURITY_NAME_PATTERN = re.compile(
|
|
14
|
+
r"exec|shell|run_command|write_file|delete|remove|eval|spawn|kill",
|
|
15
|
+
re.IGNORECASE,
|
|
16
|
+
)
|
|
17
|
+
INJECTION_PHRASES = (
|
|
18
|
+
"ignore previous",
|
|
19
|
+
"do not tell",
|
|
20
|
+
"system prompt",
|
|
21
|
+
"you must",
|
|
22
|
+
"never mention",
|
|
23
|
+
)
|
|
24
|
+
SECURITY_HINT = "Treat this as a signal, not a verdict: heuristic, review manually."
|
|
25
|
+
|
|
26
|
+
HINTS = {
|
|
27
|
+
"DOC001": "Fix the config file or drop it from discovery, then rerun `mcpcheck doctor`.",
|
|
28
|
+
"DOC002": "Check the command, arguments and required env vars; "
|
|
29
|
+
"`mcpcheck probe --only NAME` shows the error.",
|
|
30
|
+
"DOC003": "Rename one of the tools or keep only one server exposing it, "
|
|
31
|
+
"so the model has an unambiguous choice.",
|
|
32
|
+
"DOC004": "Find out why startup is slow or raise the limit with --slow-ms "
|
|
33
|
+
"if the delay is expected.",
|
|
34
|
+
"DOC005": "Remove the duplicate definition so the server exposes each name once.",
|
|
35
|
+
"DOC006": f"Disable this tool for untrusted models or scope what it can reach. {SECURITY_HINT}",
|
|
36
|
+
"DOC007": f"Inspect the description and consider pinning the server version. {SECURITY_HINT}",
|
|
37
|
+
"DOC008": "Use a stdio server for now; HTTP transport is planned for v0.2.",
|
|
38
|
+
"DOC009": "Split the server or filter tools in the client to keep the context small.",
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _finding(
|
|
43
|
+
doc_id: str,
|
|
44
|
+
severity: str,
|
|
45
|
+
server: str | None,
|
|
46
|
+
tool: str | None,
|
|
47
|
+
message: str,
|
|
48
|
+
path: str | None = None,
|
|
49
|
+
) -> dict[str, Any]:
|
|
50
|
+
return {
|
|
51
|
+
"id": doc_id,
|
|
52
|
+
"severity": severity,
|
|
53
|
+
"server": server,
|
|
54
|
+
"tool": tool,
|
|
55
|
+
"path": path,
|
|
56
|
+
"message": message,
|
|
57
|
+
"hint": HINTS[doc_id],
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _config_findings(errors: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
|
62
|
+
findings = []
|
|
63
|
+
for err in errors:
|
|
64
|
+
key = err.get("key")
|
|
65
|
+
path = err.get("path")
|
|
66
|
+
message = err.get("message", "")
|
|
67
|
+
if key:
|
|
68
|
+
target = key
|
|
69
|
+
detail = f"{path}: {message}" if path else message
|
|
70
|
+
else:
|
|
71
|
+
target = path
|
|
72
|
+
detail = message
|
|
73
|
+
findings.append(_finding("DOC001", "error", target, None, detail, path=path))
|
|
74
|
+
return findings
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _tool_collisions(results: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
|
78
|
+
owners: dict[str, dict[str, str | None]] = {}
|
|
79
|
+
for result in results:
|
|
80
|
+
for tool in result["tools"]:
|
|
81
|
+
owners.setdefault(tool["name"], {})[result["name"]] = result.get("config_path")
|
|
82
|
+
findings = []
|
|
83
|
+
for name in sorted(owners):
|
|
84
|
+
servers = sorted(owners[name])
|
|
85
|
+
if len(servers) < 2:
|
|
86
|
+
continue
|
|
87
|
+
findings.append(
|
|
88
|
+
_finding(
|
|
89
|
+
"DOC003",
|
|
90
|
+
"warn",
|
|
91
|
+
servers[0],
|
|
92
|
+
name,
|
|
93
|
+
f"tool name used by {len(servers)} servers: {', '.join(servers)}",
|
|
94
|
+
path=owners[name][servers[0]],
|
|
95
|
+
)
|
|
96
|
+
)
|
|
97
|
+
return findings
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _security_findings(results: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
|
101
|
+
findings = []
|
|
102
|
+
for result in sorted(results, key=lambda item: item["name"]):
|
|
103
|
+
for tool in sorted(result["tools"], key=lambda item: item["name"]):
|
|
104
|
+
server = result["name"]
|
|
105
|
+
name = tool["name"]
|
|
106
|
+
if SECURITY_NAME_PATTERN.search(name):
|
|
107
|
+
findings.append(
|
|
108
|
+
_finding(
|
|
109
|
+
"DOC006",
|
|
110
|
+
"info",
|
|
111
|
+
server,
|
|
112
|
+
name,
|
|
113
|
+
f"tool name looks like it executes or writes: {name}",
|
|
114
|
+
path=result.get("config_path"),
|
|
115
|
+
)
|
|
116
|
+
)
|
|
117
|
+
description = tool.get("description") or ""
|
|
118
|
+
lowered = description.lower()
|
|
119
|
+
for phrase in INJECTION_PHRASES:
|
|
120
|
+
if phrase in lowered:
|
|
121
|
+
findings.append(
|
|
122
|
+
_finding(
|
|
123
|
+
"DOC007",
|
|
124
|
+
"info",
|
|
125
|
+
server,
|
|
126
|
+
name,
|
|
127
|
+
f'description contains "{phrase}": {name}',
|
|
128
|
+
path=result.get("config_path"),
|
|
129
|
+
)
|
|
130
|
+
)
|
|
131
|
+
break
|
|
132
|
+
return findings
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def build_findings(
|
|
136
|
+
servers: list[dict[str, Any]],
|
|
137
|
+
results: list[dict[str, Any]],
|
|
138
|
+
errors: list[dict[str, Any]] | None = None,
|
|
139
|
+
security: bool = False,
|
|
140
|
+
slow_ms: int = 1000,
|
|
141
|
+
) -> list[dict[str, Any]]:
|
|
142
|
+
"""Apply DOC001-DOC009 to config servers, probe results and config errors."""
|
|
143
|
+
findings = _config_findings(errors or [])
|
|
144
|
+
transports = {server["name"]: server["transport"] for server in servers}
|
|
145
|
+
for result in results:
|
|
146
|
+
name = result["name"]
|
|
147
|
+
status = result["status"]
|
|
148
|
+
if status in {"error", "timeout"}:
|
|
149
|
+
detail = result.get("error") or f"status {status}"
|
|
150
|
+
findings.append(
|
|
151
|
+
_finding(
|
|
152
|
+
"DOC002",
|
|
153
|
+
"error",
|
|
154
|
+
name,
|
|
155
|
+
None,
|
|
156
|
+
detail,
|
|
157
|
+
path=result.get("config_path"),
|
|
158
|
+
)
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
if result["startup_ms"] > slow_ms:
|
|
162
|
+
findings.append(
|
|
163
|
+
_finding(
|
|
164
|
+
"DOC004",
|
|
165
|
+
"warn",
|
|
166
|
+
name,
|
|
167
|
+
None,
|
|
168
|
+
f"startup took {result['startup_ms']} ms (limit {slow_ms} ms)",
|
|
169
|
+
path=result.get("config_path"),
|
|
170
|
+
)
|
|
171
|
+
)
|
|
172
|
+
for tool_name in result["duplicate_tools"]:
|
|
173
|
+
findings.append(
|
|
174
|
+
_finding(
|
|
175
|
+
"DOC005",
|
|
176
|
+
"info",
|
|
177
|
+
name,
|
|
178
|
+
tool_name,
|
|
179
|
+
f"tool name defined more than once in this server: {tool_name}",
|
|
180
|
+
path=result.get("config_path"),
|
|
181
|
+
)
|
|
182
|
+
)
|
|
183
|
+
if len(result["tools"]) > TOOL_LIMIT:
|
|
184
|
+
findings.append(
|
|
185
|
+
_finding(
|
|
186
|
+
"DOC009",
|
|
187
|
+
"info",
|
|
188
|
+
name,
|
|
189
|
+
None,
|
|
190
|
+
f"server exposes {len(result['tools'])} tools (limit {TOOL_LIMIT})",
|
|
191
|
+
path=result.get("config_path"),
|
|
192
|
+
)
|
|
193
|
+
)
|
|
194
|
+
if transports.get(name) == "http":
|
|
195
|
+
findings.append(
|
|
196
|
+
_finding(
|
|
197
|
+
"DOC008",
|
|
198
|
+
"info",
|
|
199
|
+
name,
|
|
200
|
+
None,
|
|
201
|
+
"HTTP transport is not supported until v0.2",
|
|
202
|
+
path=result.get("config_path"),
|
|
203
|
+
)
|
|
204
|
+
)
|
|
205
|
+
findings.extend(_tool_collisions(results))
|
|
206
|
+
if security:
|
|
207
|
+
findings.extend(_security_findings(results))
|
|
208
|
+
return sorted(
|
|
209
|
+
findings,
|
|
210
|
+
key=lambda item: (
|
|
211
|
+
item["severity"],
|
|
212
|
+
item["id"],
|
|
213
|
+
item["server"] or "",
|
|
214
|
+
item["tool"] or "",
|
|
215
|
+
item.get("path") or "",
|
|
216
|
+
),
|
|
217
|
+
)
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def summarize(findings: list[dict[str, Any]]) -> dict[str, int]:
|
|
221
|
+
counts: dict[str, int] = dict.fromkeys(SEVERITIES, 0)
|
|
222
|
+
for finding in findings:
|
|
223
|
+
counts[finding["severity"]] += 1
|
|
224
|
+
return counts
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def fails(findings: list[dict[str, Any]], strict: bool = False) -> bool:
|
|
228
|
+
if any(finding["severity"] == "error" for finding in findings):
|
|
229
|
+
return True
|
|
230
|
+
return strict and any(finding["severity"] == "warn" for finding in findings)
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def format_findings(findings: list[dict[str, Any]]) -> list[str]:
|
|
234
|
+
lines = []
|
|
235
|
+
for finding in findings:
|
|
236
|
+
target = finding["server"] or "config"
|
|
237
|
+
if finding["tool"] is not None:
|
|
238
|
+
target = f"{target}.{finding['tool']}"
|
|
239
|
+
if finding.get("path"):
|
|
240
|
+
target = f"{target} ({finding['path']})"
|
|
241
|
+
lines.append(
|
|
242
|
+
f"{finding['severity']} {finding['id']} {target}: {finding['message']}"
|
|
243
|
+
)
|
|
244
|
+
lines.append(f" hint: {finding['hint']}")
|
|
245
|
+
return lines
|
mcpcheck/lockfile.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
"""Lockfile building and diffing. Pure logic: no file or network I/O."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from mcpcheck import __version__
|
|
10
|
+
|
|
11
|
+
LOCKFILE_VERSION = 1
|
|
12
|
+
EMPTY_SHA256 = hashlib.sha256(b"").hexdigest()
|
|
13
|
+
FAIL_ON_CHOICES = ("any", "added", "removed", "changed")
|
|
14
|
+
_SERVER_KIND = {"server_added": "added", "server_removed": "removed"}
|
|
15
|
+
_MARKER = {
|
|
16
|
+
"added": "+",
|
|
17
|
+
"removed": "-",
|
|
18
|
+
"changed": "~",
|
|
19
|
+
"server_added": "+",
|
|
20
|
+
"server_removed": "-",
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class LockError(Exception):
|
|
25
|
+
"""A lockfile that cannot be trusted for comparison."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def description_sha256(description: str | None) -> str:
|
|
29
|
+
text = description if description is not None else ""
|
|
30
|
+
return hashlib.sha256(text.encode("utf-8")).hexdigest()
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def build_lock(results: list[dict[str, Any]], version: str = __version__) -> dict[str, Any]:
|
|
34
|
+
"""Keep only servers that answered; the lock has no timestamps."""
|
|
35
|
+
servers: dict[str, Any] = {}
|
|
36
|
+
for result in results:
|
|
37
|
+
if result.get("status") != "ok":
|
|
38
|
+
continue
|
|
39
|
+
tools: dict[str, Any] = {}
|
|
40
|
+
for tool in result["tools"]:
|
|
41
|
+
tools[tool["name"]] = {
|
|
42
|
+
"schema_sha256": tool["schema_sha256"],
|
|
43
|
+
"description_sha256": description_sha256(tool.get("description")),
|
|
44
|
+
}
|
|
45
|
+
servers[result["name"]] = {"transport": "stdio", "tools": tools}
|
|
46
|
+
return {
|
|
47
|
+
"lockfile_version": LOCKFILE_VERSION,
|
|
48
|
+
"generated_by": f"mcpcheck {version}",
|
|
49
|
+
"servers": servers,
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def render_lock(lock: dict[str, Any]) -> str:
|
|
54
|
+
return json.dumps(lock, sort_keys=True, indent=2) + "\n"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def parse_lock(text: str) -> dict[str, Any]:
|
|
58
|
+
try:
|
|
59
|
+
lock = json.loads(text)
|
|
60
|
+
except json.JSONDecodeError as exc:
|
|
61
|
+
raise LockError("invalid lockfile: not JSON") from exc
|
|
62
|
+
if not isinstance(lock, dict) or lock.get("lockfile_version") != LOCKFILE_VERSION:
|
|
63
|
+
raise LockError("invalid lockfile: unsupported version")
|
|
64
|
+
servers = lock.get("servers")
|
|
65
|
+
if not isinstance(servers, dict):
|
|
66
|
+
raise LockError("invalid lockfile: missing servers")
|
|
67
|
+
for name, entry in servers.items():
|
|
68
|
+
if not isinstance(entry, dict) or not isinstance(entry.get("tools"), dict):
|
|
69
|
+
raise LockError(f"invalid lockfile: bad server {name}")
|
|
70
|
+
return lock
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def failed_servers(results: list[dict[str, Any]]) -> list[str]:
|
|
74
|
+
return sorted(
|
|
75
|
+
result["name"] for result in results if result.get("status") in {"error", "timeout"}
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def skipped_servers(results: list[dict[str, Any]]) -> list[str]:
|
|
80
|
+
return sorted(
|
|
81
|
+
result["name"] for result in results if result.get("status") == "unsupported"
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def diff_locks(
|
|
86
|
+
old: dict[str, Any],
|
|
87
|
+
current: dict[str, Any],
|
|
88
|
+
skip: set[str] | frozenset[str] = frozenset(),
|
|
89
|
+
) -> list[dict[str, Any]]:
|
|
90
|
+
"""Changes ordered by server then tool; server-level kinds are separate."""
|
|
91
|
+
changes: list[dict[str, Any]] = []
|
|
92
|
+
old_servers = {k: v for k, v in old["servers"].items() if k not in skip}
|
|
93
|
+
new_servers = {k: v for k, v in current["servers"].items() if k not in skip}
|
|
94
|
+
for name in sorted(set(old_servers) | set(new_servers)):
|
|
95
|
+
if name not in old_servers:
|
|
96
|
+
changes.append({"kind": "server_added", "server": name, "tool": None})
|
|
97
|
+
continue
|
|
98
|
+
if name not in new_servers:
|
|
99
|
+
changes.append({"kind": "server_removed", "server": name, "tool": None})
|
|
100
|
+
continue
|
|
101
|
+
old_tools = old_servers[name]["tools"]
|
|
102
|
+
new_tools = new_servers[name]["tools"]
|
|
103
|
+
for tool in sorted(set(old_tools) | set(new_tools)):
|
|
104
|
+
if tool not in old_tools:
|
|
105
|
+
changes.append({"kind": "added", "server": name, "tool": tool})
|
|
106
|
+
elif tool not in new_tools:
|
|
107
|
+
changes.append({"kind": "removed", "server": name, "tool": tool})
|
|
108
|
+
elif old_tools[tool] != new_tools[tool]:
|
|
109
|
+
changes.append({"kind": "changed", "server": name, "tool": tool})
|
|
110
|
+
return changes
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _effective_kind(change: dict[str, Any]) -> str:
|
|
114
|
+
kind: str = change["kind"]
|
|
115
|
+
return _SERVER_KIND.get(kind, kind)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def summarize(changes: list[dict[str, Any]]) -> dict[str, int]:
|
|
119
|
+
counts = {"added": 0, "removed": 0, "changed": 0}
|
|
120
|
+
for change in changes:
|
|
121
|
+
counts[_effective_kind(change)] += 1
|
|
122
|
+
return counts
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def fails_policy(changes: list[dict[str, Any]], fail_on: str) -> bool:
|
|
126
|
+
if fail_on == "any":
|
|
127
|
+
return bool(changes)
|
|
128
|
+
return any(_effective_kind(change) == fail_on for change in changes)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def format_changes(changes: list[dict[str, Any]]) -> list[str]:
|
|
132
|
+
lines = []
|
|
133
|
+
for change in changes:
|
|
134
|
+
target = change["server"]
|
|
135
|
+
if change["tool"] is not None:
|
|
136
|
+
target = f"{target}.{change['tool']}"
|
|
137
|
+
lines.append(f"{_MARKER[change['kind']]} {target}")
|
|
138
|
+
return lines
|
mcpcheck/probe.py
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
"""Probe MCP servers: handshake, tool list with schemas, resource count."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from mcpcheck.protocol import Session, TransportError
|
|
11
|
+
|
|
12
|
+
PAGINATION_LIMIT = 50
|
|
13
|
+
DESCRIPTION_LIMIT = 200
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _schema_hash(schema: Any) -> str:
|
|
17
|
+
canonical = json.dumps(
|
|
18
|
+
schema if isinstance(schema, dict) else {},
|
|
19
|
+
sort_keys=True,
|
|
20
|
+
separators=(",", ":"),
|
|
21
|
+
)
|
|
22
|
+
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _description(value: Any) -> str | None:
|
|
26
|
+
if not isinstance(value, str):
|
|
27
|
+
return None
|
|
28
|
+
return value[:DESCRIPTION_LIMIT]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _tool_entry(tool: dict[str, Any]) -> dict[str, Any]:
|
|
32
|
+
name = tool.get("name")
|
|
33
|
+
return {
|
|
34
|
+
"name": name if isinstance(name, str) else "",
|
|
35
|
+
"description": _description(tool.get("description")),
|
|
36
|
+
"schema_sha256": _schema_hash(tool.get("inputSchema", {})),
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _empty_result(name: str, config_path: str | None = None) -> dict[str, Any]:
|
|
41
|
+
return {
|
|
42
|
+
"name": name,
|
|
43
|
+
"config_path": config_path,
|
|
44
|
+
"status": "error",
|
|
45
|
+
"startup_ms": 0,
|
|
46
|
+
"protocol_version": None,
|
|
47
|
+
"server_info": {},
|
|
48
|
+
"tools": [],
|
|
49
|
+
"resource_count": 0,
|
|
50
|
+
"skipped_lines": 0,
|
|
51
|
+
"duplicate_tools": [],
|
|
52
|
+
"error": None,
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _collect_tools(
|
|
57
|
+
session: Session, timeout: float
|
|
58
|
+
) -> tuple[list[dict[str, Any]], list[str], str | None]:
|
|
59
|
+
"""Merge paginated tools/list pages; return tools, duplicate names, limit error."""
|
|
60
|
+
tools: list[dict[str, Any]] = []
|
|
61
|
+
seen: set[str] = set()
|
|
62
|
+
duplicates: set[str] = set()
|
|
63
|
+
cursor: str | None = None
|
|
64
|
+
pages = 0
|
|
65
|
+
while True:
|
|
66
|
+
params = {"cursor": cursor} if cursor is not None else None
|
|
67
|
+
result = session.request("tools/list", params, timeout=timeout)
|
|
68
|
+
raw = result.get("tools")
|
|
69
|
+
for tool in raw if isinstance(raw, list) else []:
|
|
70
|
+
if not isinstance(tool, dict):
|
|
71
|
+
continue
|
|
72
|
+
entry = _tool_entry(tool)
|
|
73
|
+
if entry["name"] in seen:
|
|
74
|
+
duplicates.add(entry["name"])
|
|
75
|
+
continue
|
|
76
|
+
seen.add(entry["name"])
|
|
77
|
+
tools.append(entry)
|
|
78
|
+
pages += 1
|
|
79
|
+
cursor = result.get("nextCursor")
|
|
80
|
+
if not cursor:
|
|
81
|
+
return tools, sorted(duplicates), None
|
|
82
|
+
if pages >= PAGINATION_LIMIT:
|
|
83
|
+
return tools, sorted(duplicates), "pagination limit"
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _resource_count(session: Session, timeout: float) -> int:
|
|
87
|
+
"""Best-effort resources/list: any failure just means zero resources."""
|
|
88
|
+
try:
|
|
89
|
+
result = session.request("resources/list", timeout=timeout)
|
|
90
|
+
except TransportError:
|
|
91
|
+
return 0
|
|
92
|
+
resources = result.get("resources")
|
|
93
|
+
return len(resources) if isinstance(resources, list) else 0
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def probe_server(server: dict[str, Any], timeout: float = 5.0) -> dict[str, Any]:
|
|
97
|
+
name = server.get("name")
|
|
98
|
+
config_path = server.get("config_path")
|
|
99
|
+
result = _empty_result(
|
|
100
|
+
name if isinstance(name, str) else "",
|
|
101
|
+
config_path if isinstance(config_path, str) else None,
|
|
102
|
+
)
|
|
103
|
+
if server.get("transport") != "stdio":
|
|
104
|
+
result["status"] = "unsupported"
|
|
105
|
+
result["error"] = server.get("error")
|
|
106
|
+
return result
|
|
107
|
+
command = server.get("command")
|
|
108
|
+
if not command:
|
|
109
|
+
result["error"] = "no command"
|
|
110
|
+
return result
|
|
111
|
+
args = server.get("args")
|
|
112
|
+
env = server.get("env")
|
|
113
|
+
session = Session(
|
|
114
|
+
[command, *(args if isinstance(args, list) else [])],
|
|
115
|
+
env if isinstance(env, dict) else {},
|
|
116
|
+
)
|
|
117
|
+
try:
|
|
118
|
+
session.start(timeout=timeout)
|
|
119
|
+
result["status"] = "ok"
|
|
120
|
+
result["startup_ms"] = int(session.startup_ms)
|
|
121
|
+
result["protocol_version"] = session.protocol_version
|
|
122
|
+
result["server_info"] = session.server_info
|
|
123
|
+
tools, duplicates, limit_error = _collect_tools(session, timeout)
|
|
124
|
+
result["tools"] = tools
|
|
125
|
+
result["duplicate_tools"] = duplicates
|
|
126
|
+
if limit_error is not None:
|
|
127
|
+
result["status"] = "error"
|
|
128
|
+
result["error"] = limit_error
|
|
129
|
+
return result
|
|
130
|
+
result["resource_count"] = _resource_count(session, timeout)
|
|
131
|
+
except TransportError as exc:
|
|
132
|
+
result["status"] = "timeout" if exc.kind == "timeout" else "error"
|
|
133
|
+
result["error"] = str(exc)
|
|
134
|
+
result["startup_ms"] = int(session.startup_ms)
|
|
135
|
+
result["protocol_version"] = session.protocol_version
|
|
136
|
+
result["server_info"] = session.server_info
|
|
137
|
+
finally:
|
|
138
|
+
session.close()
|
|
139
|
+
result["skipped_lines"] = session.skipped_lines
|
|
140
|
+
return result
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def public_result(result: dict[str, Any]) -> dict[str, Any]:
|
|
144
|
+
"""Result without the internal config path (keeps the probe JSON schema stable)."""
|
|
145
|
+
return {key: value for key, value in result.items() if key != "config_path"}
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def probe_all(
|
|
149
|
+
servers: list[dict[str, Any]], timeout: float = 5.0, concurrency: int = 4
|
|
150
|
+
) -> list[dict[str, Any]]:
|
|
151
|
+
results: list[dict[str, Any]] = []
|
|
152
|
+
with ThreadPoolExecutor(max_workers=max(1, concurrency)) as executor:
|
|
153
|
+
futures = {
|
|
154
|
+
executor.submit(probe_server, server, timeout): server for server in servers
|
|
155
|
+
}
|
|
156
|
+
for future in as_completed(futures):
|
|
157
|
+
try:
|
|
158
|
+
results.append(future.result())
|
|
159
|
+
except Exception as exc: # noqa: BLE001 - one bad server must not sink the run
|
|
160
|
+
server = futures[future]
|
|
161
|
+
name = server.get("name")
|
|
162
|
+
failed = _empty_result(
|
|
163
|
+
name if isinstance(name, str) else "",
|
|
164
|
+
server.get("config_path")
|
|
165
|
+
if isinstance(server.get("config_path"), str)
|
|
166
|
+
else None,
|
|
167
|
+
)
|
|
168
|
+
failed["error"] = str(exc)
|
|
169
|
+
results.append(failed)
|
|
170
|
+
return sorted(results, key=lambda item: item["name"])
|