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/__init__.py
ADDED
mcpcheck/cli.py
ADDED
|
@@ -0,0 +1,404 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
import sys
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from mcpcheck import __version__, doctor
|
|
10
|
+
from mcpcheck.config import (
|
|
11
|
+
ConfigError,
|
|
12
|
+
discover_configs,
|
|
13
|
+
load_config,
|
|
14
|
+
public_server,
|
|
15
|
+
)
|
|
16
|
+
from mcpcheck.lockfile import (
|
|
17
|
+
FAIL_ON_CHOICES,
|
|
18
|
+
LockError,
|
|
19
|
+
build_lock,
|
|
20
|
+
diff_locks,
|
|
21
|
+
failed_servers,
|
|
22
|
+
fails_policy,
|
|
23
|
+
format_changes,
|
|
24
|
+
parse_lock,
|
|
25
|
+
render_lock,
|
|
26
|
+
skipped_servers,
|
|
27
|
+
summarize,
|
|
28
|
+
)
|
|
29
|
+
from mcpcheck.probe import probe_all, public_result
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _add_timeout(parser: argparse.ArgumentParser) -> None:
|
|
33
|
+
parser.add_argument(
|
|
34
|
+
"--timeout",
|
|
35
|
+
type=float,
|
|
36
|
+
default=5.0,
|
|
37
|
+
metavar="SECONDS",
|
|
38
|
+
help="per-request timeout (default 5.0)",
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
43
|
+
parser = argparse.ArgumentParser(
|
|
44
|
+
prog="mcpcheck",
|
|
45
|
+
description="MCP server configuration probe",
|
|
46
|
+
)
|
|
47
|
+
parser.add_argument(
|
|
48
|
+
"--version",
|
|
49
|
+
action="version",
|
|
50
|
+
version=f"mcpcheck {__version__}",
|
|
51
|
+
)
|
|
52
|
+
commands = parser.add_subparsers(dest="command")
|
|
53
|
+
config = commands.add_parser(
|
|
54
|
+
"config", help="discover and validate MCP server configuration"
|
|
55
|
+
)
|
|
56
|
+
config.add_argument(
|
|
57
|
+
"--config",
|
|
58
|
+
action="append",
|
|
59
|
+
dest="configs",
|
|
60
|
+
type=Path,
|
|
61
|
+
metavar="PATH",
|
|
62
|
+
help="config file to read instead of discovery (repeatable)",
|
|
63
|
+
)
|
|
64
|
+
config.add_argument(
|
|
65
|
+
"--json", action="store_true", dest="as_json", help="machine-readable output"
|
|
66
|
+
)
|
|
67
|
+
probe = commands.add_parser("probe", help="start servers and list their tools")
|
|
68
|
+
probe.add_argument(
|
|
69
|
+
"--config",
|
|
70
|
+
action="append",
|
|
71
|
+
dest="configs",
|
|
72
|
+
type=Path,
|
|
73
|
+
metavar="PATH",
|
|
74
|
+
help="config file to read instead of discovery (repeatable)",
|
|
75
|
+
)
|
|
76
|
+
probe.add_argument(
|
|
77
|
+
"--discover",
|
|
78
|
+
action="store_true",
|
|
79
|
+
help="use config discovery (the default when --config is absent)",
|
|
80
|
+
)
|
|
81
|
+
probe.add_argument(
|
|
82
|
+
"--only",
|
|
83
|
+
action="append",
|
|
84
|
+
dest="only",
|
|
85
|
+
metavar="NAME",
|
|
86
|
+
help="probe only this server name (repeatable)",
|
|
87
|
+
)
|
|
88
|
+
_add_timeout(probe)
|
|
89
|
+
probe.add_argument(
|
|
90
|
+
"--concurrency",
|
|
91
|
+
type=int,
|
|
92
|
+
default=4,
|
|
93
|
+
metavar="N",
|
|
94
|
+
help="servers probed in parallel (default 4)",
|
|
95
|
+
)
|
|
96
|
+
probe.add_argument(
|
|
97
|
+
"--json", action="store_true", dest="as_json", help="machine-readable output"
|
|
98
|
+
)
|
|
99
|
+
lock = commands.add_parser("lock", help="probe servers and write mcp.lock.json")
|
|
100
|
+
lock.add_argument(
|
|
101
|
+
"--config",
|
|
102
|
+
action="append",
|
|
103
|
+
dest="configs",
|
|
104
|
+
type=Path,
|
|
105
|
+
metavar="PATH",
|
|
106
|
+
help="config file to read instead of discovery (repeatable)",
|
|
107
|
+
)
|
|
108
|
+
lock.add_argument(
|
|
109
|
+
"-o",
|
|
110
|
+
"--output",
|
|
111
|
+
type=Path,
|
|
112
|
+
default=Path("mcp.lock.json"),
|
|
113
|
+
metavar="PATH",
|
|
114
|
+
help="lockfile to write (default mcp.lock.json)",
|
|
115
|
+
)
|
|
116
|
+
lock.add_argument(
|
|
117
|
+
"--concurrency",
|
|
118
|
+
type=int,
|
|
119
|
+
default=4,
|
|
120
|
+
metavar="N",
|
|
121
|
+
help="servers probed in parallel (default 4)",
|
|
122
|
+
)
|
|
123
|
+
lock.add_argument(
|
|
124
|
+
"--allow-partial",
|
|
125
|
+
action="store_true",
|
|
126
|
+
help="write the lock even when some servers failed",
|
|
127
|
+
)
|
|
128
|
+
_add_timeout(lock)
|
|
129
|
+
verify = commands.add_parser("verify", help="compare live tools with the lockfile")
|
|
130
|
+
verify.add_argument(
|
|
131
|
+
"--config",
|
|
132
|
+
action="append",
|
|
133
|
+
dest="configs",
|
|
134
|
+
type=Path,
|
|
135
|
+
metavar="PATH",
|
|
136
|
+
help="config file to read instead of discovery (repeatable)",
|
|
137
|
+
)
|
|
138
|
+
verify.add_argument(
|
|
139
|
+
"--lock",
|
|
140
|
+
type=Path,
|
|
141
|
+
default=Path("mcp.lock.json"),
|
|
142
|
+
metavar="PATH",
|
|
143
|
+
help="lockfile to verify against (default mcp.lock.json)",
|
|
144
|
+
)
|
|
145
|
+
verify.add_argument(
|
|
146
|
+
"--fail-on",
|
|
147
|
+
choices=FAIL_ON_CHOICES,
|
|
148
|
+
default="any",
|
|
149
|
+
help="which changes make the command fail (default any)",
|
|
150
|
+
)
|
|
151
|
+
verify.add_argument(
|
|
152
|
+
"--json", action="store_true", dest="as_json", help="machine-readable output"
|
|
153
|
+
)
|
|
154
|
+
_add_timeout(verify)
|
|
155
|
+
doctor = commands.add_parser("doctor", help="aggregate findings and security hints")
|
|
156
|
+
doctor.add_argument(
|
|
157
|
+
"--config",
|
|
158
|
+
action="append",
|
|
159
|
+
dest="configs",
|
|
160
|
+
type=Path,
|
|
161
|
+
metavar="PATH",
|
|
162
|
+
help="config file to read instead of discovery (repeatable)",
|
|
163
|
+
)
|
|
164
|
+
doctor.add_argument(
|
|
165
|
+
"--discover",
|
|
166
|
+
action="store_true",
|
|
167
|
+
help="use config discovery (the default when --config is absent)",
|
|
168
|
+
)
|
|
169
|
+
doctor.add_argument(
|
|
170
|
+
"--security",
|
|
171
|
+
action="store_true",
|
|
172
|
+
help="add heuristic DOC006/DOC007 findings",
|
|
173
|
+
)
|
|
174
|
+
doctor.add_argument(
|
|
175
|
+
"--strict", action="store_true", help="exit 1 on warnings as well as errors"
|
|
176
|
+
)
|
|
177
|
+
doctor.add_argument(
|
|
178
|
+
"--slow-ms",
|
|
179
|
+
type=int,
|
|
180
|
+
default=1000,
|
|
181
|
+
metavar="MS",
|
|
182
|
+
help="startup slower than this is a DOC004 warning (default 1000)",
|
|
183
|
+
)
|
|
184
|
+
doctor.add_argument(
|
|
185
|
+
"--concurrency",
|
|
186
|
+
type=int,
|
|
187
|
+
default=4,
|
|
188
|
+
metavar="N",
|
|
189
|
+
help="servers probed in parallel (default 4)",
|
|
190
|
+
)
|
|
191
|
+
_add_timeout(doctor)
|
|
192
|
+
doctor.add_argument(
|
|
193
|
+
"--json", action="store_true", dest="as_json", help="machine-readable output"
|
|
194
|
+
)
|
|
195
|
+
return parser
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _error_entry(exc: ConfigError, path: Path) -> dict[str, Any]:
|
|
199
|
+
return {
|
|
200
|
+
"path": str(exc.path if exc.path is not None else path),
|
|
201
|
+
"key": exc.key,
|
|
202
|
+
"message": exc.message,
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _load_documents(
|
|
207
|
+
paths: list[Path],
|
|
208
|
+
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
|
|
209
|
+
seen: set[Path] = set()
|
|
210
|
+
documents: list[dict[str, Any]] = []
|
|
211
|
+
errors: list[dict[str, Any]] = []
|
|
212
|
+
for path in paths:
|
|
213
|
+
path = path.expanduser()
|
|
214
|
+
identity = path.resolve()
|
|
215
|
+
if identity in seen:
|
|
216
|
+
continue
|
|
217
|
+
seen.add(identity)
|
|
218
|
+
try:
|
|
219
|
+
documents.append(load_config(path))
|
|
220
|
+
except ConfigError as exc:
|
|
221
|
+
errors.append(_error_entry(exc, path))
|
|
222
|
+
return documents, errors
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _print_human(document: dict[str, Any]) -> None:
|
|
226
|
+
for cfg in document["configs"]:
|
|
227
|
+
print(f"{cfg['path']} ({cfg['format']})")
|
|
228
|
+
for server in cfg["servers"]:
|
|
229
|
+
status = server["error"] or server["transport"]
|
|
230
|
+
print(f" {server['name']}: {status}")
|
|
231
|
+
for err in document["errors"]:
|
|
232
|
+
print(f"{err['path']}: {err['message']}", file=sys.stderr)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _cmd_config(configs: list[Path] | None, as_json: bool) -> int:
|
|
236
|
+
paths = configs if configs is not None else discover_configs()
|
|
237
|
+
documents, errors = _load_documents(paths)
|
|
238
|
+
public = [
|
|
239
|
+
{**cfg, "servers": [public_server(server) for server in cfg["servers"]]}
|
|
240
|
+
for cfg in documents
|
|
241
|
+
]
|
|
242
|
+
output: dict[str, Any] = {"schema": 1, "configs": public, "errors": errors}
|
|
243
|
+
if as_json:
|
|
244
|
+
print(json.dumps(output, sort_keys=True, indent=2))
|
|
245
|
+
else:
|
|
246
|
+
_print_human(output)
|
|
247
|
+
return 1 if errors else 0
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def _print_probe_table(results: list[dict[str, Any]]) -> None:
|
|
251
|
+
print(f"{'name':<20} {'status':<12} {'startup':>8} {'tools':>6}")
|
|
252
|
+
for result in results:
|
|
253
|
+
print(
|
|
254
|
+
f"{result['name']:<20} {result['status']:<12} "
|
|
255
|
+
f"{result['startup_ms']:>6}ms {len(result['tools']):>6}"
|
|
256
|
+
)
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _servers_from(
|
|
260
|
+
configs: list[Path] | None,
|
|
261
|
+
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
|
|
262
|
+
paths = configs if configs is not None else discover_configs()
|
|
263
|
+
documents, errors = _load_documents(paths)
|
|
264
|
+
servers = [
|
|
265
|
+
{**server, "config_path": cfg["path"]}
|
|
266
|
+
for cfg in documents
|
|
267
|
+
for server in cfg["servers"]
|
|
268
|
+
]
|
|
269
|
+
return servers, errors
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _cmd_probe(args: argparse.Namespace) -> int:
|
|
273
|
+
servers, errors = _servers_from(args.configs)
|
|
274
|
+
for err in errors:
|
|
275
|
+
print(f"{err['path']}: {err['message']}", file=sys.stderr)
|
|
276
|
+
if args.only:
|
|
277
|
+
known = {server["name"] for server in servers}
|
|
278
|
+
unknown = [name for name in args.only if name not in known]
|
|
279
|
+
if unknown:
|
|
280
|
+
print(f"unknown server: {', '.join(unknown)}", file=sys.stderr)
|
|
281
|
+
return 2
|
|
282
|
+
wanted = set(args.only)
|
|
283
|
+
servers = [server for server in servers if server["name"] in wanted]
|
|
284
|
+
results = probe_all(servers, timeout=args.timeout, concurrency=args.concurrency)
|
|
285
|
+
public = [public_result(result) for result in results]
|
|
286
|
+
if args.as_json:
|
|
287
|
+
print(json.dumps({"schema": 1, "servers": public}, sort_keys=True, indent=2))
|
|
288
|
+
else:
|
|
289
|
+
_print_probe_table(public)
|
|
290
|
+
failed = any(result["status"] in {"error", "timeout"} for result in results)
|
|
291
|
+
return 1 if failed or errors else 0
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def _cmd_lock(args: argparse.Namespace) -> int:
|
|
295
|
+
servers, errors = _servers_from(args.configs)
|
|
296
|
+
for err in errors:
|
|
297
|
+
print(f"{err['path']}: {err['message']}", file=sys.stderr)
|
|
298
|
+
if errors:
|
|
299
|
+
return 2
|
|
300
|
+
results = probe_all(servers, timeout=args.timeout, concurrency=args.concurrency)
|
|
301
|
+
for name in skipped_servers(results):
|
|
302
|
+
print(f"skipped {name}", file=sys.stderr)
|
|
303
|
+
failed = failed_servers(results)
|
|
304
|
+
if failed and not args.allow_partial:
|
|
305
|
+
print(f"failed servers: {', '.join(failed)}", file=sys.stderr)
|
|
306
|
+
return 3
|
|
307
|
+
args.output.write_text(render_lock(build_lock(results)), encoding="utf-8")
|
|
308
|
+
print(f"wrote {args.output}")
|
|
309
|
+
return 0
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def _cmd_verify(args: argparse.Namespace) -> int:
|
|
313
|
+
if not args.lock.is_file():
|
|
314
|
+
print('run "mcpcheck lock" first', file=sys.stderr)
|
|
315
|
+
return 2
|
|
316
|
+
try:
|
|
317
|
+
lock = parse_lock(args.lock.read_text(encoding="utf-8"))
|
|
318
|
+
except (OSError, LockError) as exc:
|
|
319
|
+
print(f"{args.lock}: {exc}", file=sys.stderr)
|
|
320
|
+
return 2
|
|
321
|
+
servers, errors = _servers_from(args.configs)
|
|
322
|
+
for err in errors:
|
|
323
|
+
print(f"{err['path']}: {err['message']}", file=sys.stderr)
|
|
324
|
+
if errors:
|
|
325
|
+
return 2
|
|
326
|
+
results = probe_all(servers, timeout=args.timeout)
|
|
327
|
+
for name in skipped_servers(results):
|
|
328
|
+
print(f"skipped {name}", file=sys.stderr)
|
|
329
|
+
failed = failed_servers(results)
|
|
330
|
+
if failed:
|
|
331
|
+
print(f"failed servers: {', '.join(failed)}", file=sys.stderr)
|
|
332
|
+
if args.as_json:
|
|
333
|
+
output = {
|
|
334
|
+
"schema": 1,
|
|
335
|
+
"changes": [],
|
|
336
|
+
"summary": {"added": 0, "removed": 0, "changed": 0},
|
|
337
|
+
"errors": [f"server did not respond: {name}" for name in failed],
|
|
338
|
+
}
|
|
339
|
+
print(json.dumps(output, sort_keys=True, indent=2))
|
|
340
|
+
return 3
|
|
341
|
+
changes = diff_locks(
|
|
342
|
+
lock,
|
|
343
|
+
build_lock(results),
|
|
344
|
+
skip=frozenset(skipped_servers(results)),
|
|
345
|
+
)
|
|
346
|
+
summary = summarize(changes)
|
|
347
|
+
if args.as_json:
|
|
348
|
+
output = {"schema": 1, "changes": changes, "summary": summary, "errors": []}
|
|
349
|
+
print(json.dumps(output, sort_keys=True, indent=2))
|
|
350
|
+
else:
|
|
351
|
+
for line in format_changes(changes):
|
|
352
|
+
print(line)
|
|
353
|
+
if changes:
|
|
354
|
+
print(
|
|
355
|
+
f"{summary['added']} added, {summary['removed']} removed, "
|
|
356
|
+
f"{summary['changed']} changed"
|
|
357
|
+
)
|
|
358
|
+
else:
|
|
359
|
+
print("no changes")
|
|
360
|
+
return 1 if fails_policy(changes, args.fail_on) else 0
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def _cmd_doctor(args: argparse.Namespace) -> int:
|
|
364
|
+
servers, errors = _servers_from(args.configs)
|
|
365
|
+
for err in errors:
|
|
366
|
+
print(f"{err['path']}: {err['message']}", file=sys.stderr)
|
|
367
|
+
results = probe_all(servers, timeout=args.timeout, concurrency=args.concurrency)
|
|
368
|
+
findings = doctor.build_findings(
|
|
369
|
+
servers, results, errors, security=args.security, slow_ms=args.slow_ms
|
|
370
|
+
)
|
|
371
|
+
summary = doctor.summarize(findings)
|
|
372
|
+
if args.as_json:
|
|
373
|
+
output = {"schema": 1, "findings": findings, "summary": summary}
|
|
374
|
+
print(json.dumps(output, sort_keys=True, indent=2))
|
|
375
|
+
elif findings:
|
|
376
|
+
for line in doctor.format_findings(findings):
|
|
377
|
+
print(line)
|
|
378
|
+
print(
|
|
379
|
+
f"{summary['error']} errors, {summary['warn']} warnings, {summary['info']} info"
|
|
380
|
+
)
|
|
381
|
+
else:
|
|
382
|
+
print("no findings")
|
|
383
|
+
return 1 if doctor.fails(findings, strict=args.strict) else 0
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def main(argv: list[str] | None = None) -> int:
|
|
387
|
+
parser = _build_parser()
|
|
388
|
+
args = parser.parse_args(argv)
|
|
389
|
+
if args.command == "config":
|
|
390
|
+
return _cmd_config(args.configs, args.as_json)
|
|
391
|
+
if args.command == "probe":
|
|
392
|
+
return _cmd_probe(args)
|
|
393
|
+
if args.command == "lock":
|
|
394
|
+
return _cmd_lock(args)
|
|
395
|
+
if args.command == "verify":
|
|
396
|
+
return _cmd_verify(args)
|
|
397
|
+
if args.command == "doctor":
|
|
398
|
+
return _cmd_doctor(args)
|
|
399
|
+
parser.print_help()
|
|
400
|
+
return 2
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
if __name__ == "__main__":
|
|
404
|
+
raise SystemExit(main())
|
mcpcheck/config.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import re
|
|
6
|
+
import sys
|
|
7
|
+
import tomllib
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
ENV_PATTERN = re.compile(r"\$\{([^}:]+)(?::-([^}]*))?\}")
|
|
12
|
+
KNOWN_SERVER_KEYS = frozenset({"command", "args", "env", "url"})
|
|
13
|
+
HTTP_ERROR = "unsupported transport (v0.2)"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ConfigError(Exception):
|
|
17
|
+
"""A configuration problem tied to a file and optionally a server key."""
|
|
18
|
+
|
|
19
|
+
def __init__(self, path: Path | None, key: str | None, message: str) -> None:
|
|
20
|
+
self.path = path
|
|
21
|
+
self.key = key
|
|
22
|
+
self.message = message
|
|
23
|
+
where = f"{path}: " if path is not None else ""
|
|
24
|
+
named = f"[{key}] " if key is not None else ""
|
|
25
|
+
super().__init__(f"{where}{named}{message}")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def expand_env(value: str) -> str:
|
|
29
|
+
def repl(m: re.Match[str]) -> str:
|
|
30
|
+
name = m.group(1)
|
|
31
|
+
default = m.group(2)
|
|
32
|
+
found = os.environ.get(name)
|
|
33
|
+
if found is not None:
|
|
34
|
+
return found
|
|
35
|
+
if default is not None:
|
|
36
|
+
return default
|
|
37
|
+
raise ConfigError(None, name, f"unset variable: {name}")
|
|
38
|
+
|
|
39
|
+
return ENV_PATTERN.sub(repl, value)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _discovery_paths(home: Path, platform: str) -> list[Path]:
|
|
43
|
+
if platform == "darwin":
|
|
44
|
+
claude = home / "Library/Application Support/Claude/claude_desktop_config.json"
|
|
45
|
+
vscode = home / "Library/Application Support/Code/User/mcp.json"
|
|
46
|
+
else:
|
|
47
|
+
claude = home / ".config/Claude/claude_desktop_config.json"
|
|
48
|
+
vscode = home / ".config/Code/User/mcp.json"
|
|
49
|
+
return [
|
|
50
|
+
claude,
|
|
51
|
+
home / ".cursor" / "mcp.json",
|
|
52
|
+
vscode,
|
|
53
|
+
home / ".codeium" / "windsurf" / "mcp_config.json",
|
|
54
|
+
home / ".codex" / "config.toml",
|
|
55
|
+
Path(".mcp.json"),
|
|
56
|
+
Path(".vscode") / "mcp.json",
|
|
57
|
+
]
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def discover_configs(home: Path | None = None, platform: str | None = None) -> list[Path]:
|
|
61
|
+
base = home if home is not None else Path.home()
|
|
62
|
+
system = platform if platform is not None else sys.platform
|
|
63
|
+
found = [path for path in _discovery_paths(base, system) if path.is_file()]
|
|
64
|
+
unique = dict.fromkeys(found)
|
|
65
|
+
return sorted(unique, key=str)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def detect_format(path: Path, data: dict[str, Any]) -> str:
|
|
69
|
+
if path.suffix == ".toml":
|
|
70
|
+
return "codex"
|
|
71
|
+
parts = path.parts
|
|
72
|
+
if any(part in {".cursor", "cursor"} for part in parts):
|
|
73
|
+
return "cursor"
|
|
74
|
+
if any("windsurf" in part for part in parts):
|
|
75
|
+
# Windsurf shares the Claude/Cursor mcpServers shape; no separate enum value.
|
|
76
|
+
return "claude"
|
|
77
|
+
if "Code" in parts and "User" in parts:
|
|
78
|
+
return "vscode"
|
|
79
|
+
if path.name == "claude_desktop_config.json":
|
|
80
|
+
return "claude"
|
|
81
|
+
if "servers" in data or isinstance(data.get("mcp"), dict):
|
|
82
|
+
return "vscode"
|
|
83
|
+
if "mcpServers" in data:
|
|
84
|
+
return "claude"
|
|
85
|
+
return "unknown"
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _servers_section(data: dict[str, Any], path: Path | None) -> dict[str, Any]:
|
|
89
|
+
if isinstance(data.get("mcp_servers"), dict):
|
|
90
|
+
return data["mcp_servers"]
|
|
91
|
+
for key in ("mcpServers", "servers"):
|
|
92
|
+
section = data.get(key)
|
|
93
|
+
if isinstance(section, dict):
|
|
94
|
+
return section
|
|
95
|
+
mcp = data.get("mcp")
|
|
96
|
+
if isinstance(mcp, dict) and isinstance(mcp.get("servers"), dict):
|
|
97
|
+
return mcp["servers"]
|
|
98
|
+
raise ConfigError(path, None, "unknown config shape")
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def parse_config(path: Path) -> dict[str, Any]:
|
|
102
|
+
try:
|
|
103
|
+
text = path.read_text(encoding="utf-8")
|
|
104
|
+
except OSError as exc:
|
|
105
|
+
raise ConfigError(path, None, "cannot read config") from exc
|
|
106
|
+
try:
|
|
107
|
+
if path.suffix == ".json":
|
|
108
|
+
data = json.loads(text)
|
|
109
|
+
elif path.suffix == ".toml":
|
|
110
|
+
data = tomllib.loads(text)
|
|
111
|
+
else:
|
|
112
|
+
raise ConfigError(path, None, "unknown config shape")
|
|
113
|
+
except json.JSONDecodeError as exc:
|
|
114
|
+
raise ConfigError(path, None, "invalid json") from exc
|
|
115
|
+
except tomllib.TOMLDecodeError as exc:
|
|
116
|
+
raise ConfigError(path, None, "invalid toml") from exc
|
|
117
|
+
if not isinstance(data, dict):
|
|
118
|
+
raise ConfigError(path, None, "unknown config shape")
|
|
119
|
+
return data
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _string_list(value: Any, path: Path | None, name: str) -> list[str]:
|
|
123
|
+
if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
|
|
124
|
+
raise ConfigError(path, name, "args must be a list of strings")
|
|
125
|
+
return [expand_env(item) for item in value]
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _string_env(value: Any, path: Path | None, name: str) -> dict[str, str]:
|
|
129
|
+
if not isinstance(value, dict) or not all(
|
|
130
|
+
isinstance(k, str) and isinstance(v, str) for k, v in value.items()
|
|
131
|
+
):
|
|
132
|
+
raise ConfigError(path, name, "env must be a dict of strings")
|
|
133
|
+
return {key: expand_env(item) for key, item in sorted(value.items())}
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def validate_config(cfg: dict[str, Any], path: Path | None = None) -> list[dict[str, Any]]:
|
|
137
|
+
section = _servers_section(cfg, path)
|
|
138
|
+
servers: list[dict[str, Any]] = []
|
|
139
|
+
for name in sorted(section):
|
|
140
|
+
entry = section[name]
|
|
141
|
+
if not isinstance(entry, dict):
|
|
142
|
+
raise ConfigError(path, name, "server entry is not an object")
|
|
143
|
+
command = entry.get("command")
|
|
144
|
+
url = entry.get("url")
|
|
145
|
+
if command is None and url is None:
|
|
146
|
+
raise ConfigError(path, name, "server has neither command nor url")
|
|
147
|
+
args = _string_list(entry.get("args", []), path, name)
|
|
148
|
+
env = _string_env(entry.get("env", {}), path, name)
|
|
149
|
+
extra = {key: value for key, value in entry.items() if key not in KNOWN_SERVER_KEYS}
|
|
150
|
+
server: dict[str, Any] = {
|
|
151
|
+
"name": name,
|
|
152
|
+
"args": args,
|
|
153
|
+
"env": env,
|
|
154
|
+
"env_keys": sorted(env),
|
|
155
|
+
"error": None,
|
|
156
|
+
}
|
|
157
|
+
if command is not None:
|
|
158
|
+
if not isinstance(command, str) or command == "":
|
|
159
|
+
raise ConfigError(path, name, "command must be a non-empty string")
|
|
160
|
+
server["transport"] = "stdio"
|
|
161
|
+
server["command"] = expand_env(command)
|
|
162
|
+
else:
|
|
163
|
+
server["transport"] = "http"
|
|
164
|
+
server["command"] = None
|
|
165
|
+
server["error"] = HTTP_ERROR
|
|
166
|
+
if extra:
|
|
167
|
+
server["extra"] = extra
|
|
168
|
+
servers.append(server)
|
|
169
|
+
return servers
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def public_server(server: dict[str, Any]) -> dict[str, Any]:
|
|
173
|
+
"""Copy a server entry without the expanded env values (secrets stay out of JSON)."""
|
|
174
|
+
return {key: value for key, value in server.items() if key != "env"}
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def load_config(path: Path) -> dict[str, Any]:
|
|
178
|
+
data = parse_config(path)
|
|
179
|
+
return {
|
|
180
|
+
"path": str(path),
|
|
181
|
+
"format": detect_format(path, data),
|
|
182
|
+
"servers": validate_config(data, path),
|
|
183
|
+
}
|