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/protocol.py ADDED
@@ -0,0 +1,303 @@
1
+ """Stdio JSON-RPC client for MCP servers (v0.1 transport contract)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import selectors
8
+ import signal
9
+ import time
10
+ from pathlib import Path
11
+ from subprocess import PIPE, Popen, TimeoutExpired
12
+ from typing import Any, NoReturn, Self
13
+
14
+ from mcpcheck import __version__
15
+
16
+ BUFFER_LIMIT = 8 * 1024 * 1024
17
+ STDERR_TAIL = 4 * 1024
18
+ PROTOCOL_VERSION = "2025-06-18"
19
+ READ_CHUNK = 65536
20
+ CLOSE_GRACE = 0.2
21
+
22
+
23
+ class TransportError(Exception):
24
+ """Transport failure with a machine-readable kind."""
25
+
26
+ def __init__(self, kind: str, detail: str) -> None:
27
+ super().__init__(f"{kind}: {detail}")
28
+ self.kind = kind
29
+ self.detail = detail
30
+
31
+
32
+ class Session:
33
+ """One MCP server process speaking line-delimited JSON-RPC over stdio."""
34
+
35
+ def __init__(
36
+ self, command: list[str], env: dict[str, str], cwd: Path | None = None
37
+ ) -> None:
38
+ self.command = list(command)
39
+ self.env = dict(env)
40
+ self.cwd = cwd
41
+ self.server_info: dict[str, Any] = {}
42
+ self.protocol_version: str | None = None
43
+ self.startup_ms: float = 0.0
44
+ self.skipped_lines = 0
45
+ self.stderr_tail = ""
46
+ self._proc: Popen[str] | None = None
47
+ self._selector: selectors.BaseSelector | None = None
48
+ self._buffer = b""
49
+ self._stderr = b""
50
+ self._next_id = 1
51
+
52
+ def __enter__(self) -> Self:
53
+ return self
54
+
55
+ def __exit__(self, *exc_info: object) -> None:
56
+ self.close()
57
+
58
+ def start(self, timeout: float = 5.0) -> dict[str, Any]:
59
+ if self._proc is not None:
60
+ raise TransportError("protocol", "session already started")
61
+ begun = time.monotonic()
62
+ try:
63
+ proc = Popen(
64
+ self.command,
65
+ stdin=PIPE,
66
+ stdout=PIPE,
67
+ stderr=PIPE,
68
+ cwd=self.cwd,
69
+ env={**os.environ, **self.env},
70
+ start_new_session=True,
71
+ text=True,
72
+ bufsize=1,
73
+ )
74
+ except (OSError, ValueError) as exc:
75
+ raise TransportError("spawn", str(exc)) from exc
76
+ self._proc = proc
77
+ assert proc.stdout is not None and proc.stderr is not None
78
+ selector = selectors.DefaultSelector()
79
+ selector.register(proc.stdout, selectors.EVENT_READ)
80
+ selector.register(proc.stderr, selectors.EVENT_READ)
81
+ self._selector = selector
82
+
83
+ request_id = self._take_id()
84
+ self._send(
85
+ {
86
+ "jsonrpc": "2.0",
87
+ "id": request_id,
88
+ "method": "initialize",
89
+ "params": {
90
+ "protocolVersion": PROTOCOL_VERSION,
91
+ "capabilities": {},
92
+ "clientInfo": {"name": "mcpcheck", "version": __version__},
93
+ },
94
+ }
95
+ )
96
+ result = self._read_response(request_id, timeout, "initialize")
97
+ self.startup_ms = (time.monotonic() - begun) * 1000.0
98
+ info = result.get("serverInfo")
99
+ self.server_info = info if isinstance(info, dict) else {}
100
+ version = result.get("protocolVersion")
101
+ self.protocol_version = version if isinstance(version, str) else None
102
+ self._send({"jsonrpc": "2.0", "method": "notifications/initialized"})
103
+ return self.server_info
104
+
105
+ def request(
106
+ self, method: str, params: dict[str, Any] | None = None, timeout: float = 5.0
107
+ ) -> dict[str, Any]:
108
+ if self._proc is None:
109
+ raise TransportError("protocol", "session not started")
110
+ request_id = self._take_id()
111
+ payload: dict[str, Any] = {
112
+ "jsonrpc": "2.0",
113
+ "id": request_id,
114
+ "method": method,
115
+ }
116
+ if params is not None:
117
+ payload["params"] = params
118
+ self._send(payload)
119
+ return self._read_response(request_id, timeout, method)
120
+
121
+ def close(self) -> None:
122
+ self._terminate()
123
+
124
+ def _take_id(self) -> int:
125
+ request_id = self._next_id
126
+ self._next_id += 1
127
+ return request_id
128
+
129
+ def _send(self, payload: dict[str, Any]) -> None:
130
+ proc = self._proc
131
+ if proc is None or proc.stdin is None:
132
+ raise TransportError("protocol", "session not started")
133
+ line = json.dumps(payload, separators=(",", ":"))
134
+ try:
135
+ proc.stdin.write(line + "\n")
136
+ proc.stdin.flush()
137
+ except OSError as exc:
138
+ self._write_failure(exc)
139
+
140
+ def _write_failure(self, exc: OSError) -> NoReturn:
141
+ detail = self._exit_detail()
142
+ if not detail.startswith("server exited with code"):
143
+ detail = f"cannot write to server: {exc}"
144
+ self._fail("exit", detail)
145
+
146
+ def _read_response(
147
+ self, request_id: int, timeout: float, waiting_for: str
148
+ ) -> dict[str, Any]:
149
+ deadline = time.monotonic() + timeout
150
+ while True:
151
+ message = self._read_message(deadline, waiting_for)
152
+ if "id" not in message:
153
+ continue
154
+ if message["id"] != request_id:
155
+ self._fail(
156
+ "protocol",
157
+ f"unexpected id {message['id']!r} while waiting for {waiting_for}",
158
+ )
159
+ if "error" in message:
160
+ error = message["error"]
161
+ text = error.get("message") if isinstance(error, dict) else None
162
+ self._fail("protocol", f"{waiting_for} failed: {text or error}")
163
+ if "result" not in message:
164
+ self._fail("protocol", f"{waiting_for} response has no result")
165
+ result = message["result"]
166
+ if not isinstance(result, dict):
167
+ self._fail("protocol", f"{waiting_for} returned non-object result")
168
+ return result
169
+
170
+ def _read_message(self, deadline: float, waiting_for: str) -> dict[str, Any]:
171
+ while True:
172
+ message = self._take_line()
173
+ if message is not None:
174
+ return message
175
+ if len(self._buffer) > BUFFER_LIMIT:
176
+ self._fail("protocol", "buffer limit")
177
+ remaining = deadline - time.monotonic()
178
+ if remaining <= 0:
179
+ self._fail("timeout", f"timeout waiting for {waiting_for}")
180
+ selector = self._selector
181
+ proc = self._proc
182
+ if selector is None or proc is None or proc.stdout is None:
183
+ raise TransportError("protocol", "session not started")
184
+ stdout_fd = proc.stdout.fileno()
185
+ for key, _ in selector.select(remaining):
186
+ if key.fd == stdout_fd:
187
+ self._read_stdout(stdout_fd)
188
+ else:
189
+ self._read_stderr(key.fd)
190
+
191
+ def _take_line(self) -> dict[str, Any] | None:
192
+ while True:
193
+ newline = self._buffer.find(b"\n")
194
+ if newline < 0:
195
+ return None
196
+ raw = self._buffer[:newline]
197
+ self._buffer = self._buffer[newline + 1 :]
198
+ text = raw.decode("utf-8", errors="replace").strip()
199
+ if not text:
200
+ continue
201
+ try:
202
+ message = json.loads(text)
203
+ except json.JSONDecodeError:
204
+ self.skipped_lines += 1
205
+ continue
206
+ if not isinstance(message, dict):
207
+ self.skipped_lines += 1
208
+ continue
209
+ return message
210
+
211
+ def _read_stdout(self, fd: int) -> None:
212
+ chunk = os.read(fd, READ_CHUNK)
213
+ if not chunk:
214
+ self._fail("exit", self._exit_detail())
215
+ self._buffer += chunk
216
+
217
+ def _read_stderr(self, fd: int) -> None:
218
+ chunk = os.read(fd, READ_CHUNK)
219
+ if not chunk:
220
+ self._unregister_stderr()
221
+ return
222
+ self._stderr = (self._stderr + chunk)[-STDERR_TAIL:]
223
+ self.stderr_tail = self._stderr.decode("utf-8", errors="replace")
224
+
225
+ def _unregister_stderr(self) -> None:
226
+ proc = self._proc
227
+ selector = self._selector
228
+ if proc is None or proc.stderr is None or selector is None:
229
+ return
230
+ try:
231
+ selector.unregister(proc.stderr)
232
+ except (KeyError, ValueError):
233
+ pass
234
+
235
+ def _exit_detail(self) -> str:
236
+ proc = self._proc
237
+ if proc is None:
238
+ return "server closed stdout"
239
+ try:
240
+ code = proc.wait(timeout=2.0)
241
+ except TimeoutExpired:
242
+ return "server closed stdout"
243
+ return f"server exited with code {code}"
244
+
245
+ def _fail(self, kind: str, detail: str) -> NoReturn:
246
+ self._terminate()
247
+ raise self._error(kind, detail)
248
+
249
+ def _error(self, kind: str, detail: str) -> TransportError:
250
+ tail = self.stderr_tail.strip()
251
+ if tail:
252
+ detail = f"{detail} (stderr: {tail})"
253
+ return TransportError(kind, detail)
254
+
255
+ def _terminate(self) -> None:
256
+ proc = self._proc
257
+ if proc is None:
258
+ return
259
+ self._proc = None
260
+ selector, self._selector = self._selector, None
261
+ if proc.stdin is not None:
262
+ try:
263
+ proc.stdin.close()
264
+ except OSError:
265
+ pass
266
+ try:
267
+ proc.wait(timeout=CLOSE_GRACE)
268
+ except TimeoutExpired:
269
+ pass
270
+ try:
271
+ os.killpg(proc.pid, signal.SIGKILL)
272
+ except OSError:
273
+ pass
274
+ proc.wait()
275
+ self._collect_stderr(proc)
276
+ if selector is not None:
277
+ selector.close()
278
+ for stream in (proc.stdout, proc.stderr):
279
+ if stream is not None:
280
+ try:
281
+ stream.close()
282
+ except OSError:
283
+ pass
284
+
285
+ def _collect_stderr(self, proc: Popen[str]) -> None:
286
+ if proc.stderr is None:
287
+ return
288
+ fd = proc.stderr.fileno()
289
+ try:
290
+ os.set_blocking(fd, False)
291
+ except OSError:
292
+ return
293
+ while True:
294
+ try:
295
+ chunk = os.read(fd, READ_CHUNK)
296
+ except BlockingIOError:
297
+ break
298
+ except OSError:
299
+ break
300
+ if not chunk:
301
+ break
302
+ self._stderr = (self._stderr + chunk)[-STDERR_TAIL:]
303
+ self.stderr_tail = self._stderr.decode("utf-8", errors="replace")
@@ -0,0 +1,167 @@
1
+ Metadata-Version: 2.4
2
+ Name: mcpcheck-cli
3
+ Version: 0.1.0
4
+ Summary: MCP server configuration probe
5
+ Requires-Python: >=3.11
6
+ Description-Content-Type: text/markdown
7
+ License-File: LICENSE
8
+ Provides-Extra: dev
9
+ Requires-Dist: pytest; extra == "dev"
10
+ Requires-Dist: pytest-cov; extra == "dev"
11
+ Requires-Dist: ruff; extra == "dev"
12
+ Requires-Dist: pyright; extra == "dev"
13
+ Dynamic: license-file
14
+
15
+ # mcpcheck
16
+
17
+ Diagnose and lock your MCP setup: validate configs, probe servers over stdio, and
18
+ diff tool schemas in CI so your agent does not silently gain or lose abilities.
19
+
20
+ [![CI](https://github.com/Matrinus/mcpcheck/actions/workflows/ci.yml/badge.svg)](https://github.com/Matrinus/mcpcheck/actions/workflows/ci.yml)
21
+ [![GitHub Action](https://img.shields.io/badge/GitHub%20Action-mcpcheck-blue?logo=githubactions&logoColor=white)](action.yml)
22
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
23
+ [![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue.svg)](pyproject.toml)
24
+
25
+ **Status: v0.1.0**
26
+
27
+ ## Demo
28
+
29
+ ```text
30
+ # demo: two fixture servers (ok.py, evil.py) in a temporary directory
31
+
32
+ $ mcpcheck config --config mcp.json
33
+ mcp.json (claude)
34
+ fs: stdio
35
+ risky: stdio
36
+
37
+ $ mcpcheck probe --config mcp.json
38
+ name status startup tools
39
+ fs ok 11ms 2
40
+ risky ok 11ms 1
41
+
42
+ $ mcpcheck lock --config mcp.json -o mcp.lock.json
43
+ wrote mcp.lock.json
44
+
45
+ $ mcpcheck verify --config mcp.json --lock mcp.lock.json
46
+ no changes
47
+
48
+ $ mcpcheck verify --config mcp-v2.json --lock mcp.lock.json
49
+ ~ fs.echo
50
+ 0 added, 0 removed, 1 changed
51
+
52
+ $ mcpcheck doctor --config mcp.json --security
53
+ info DOC006 risky.exec_shell (mcp.json): tool name looks like it executes or writes: exec_shell
54
+ hint: Disable this tool for untrusted models or scope what it can reach. Treat this as a signal, not a verdict: heuristic, review manually.
55
+ info DOC007 risky.exec_shell (mcp.json): description contains "ignore previous": exec_shell
56
+ hint: Inspect the description and consider pinning the server version. Treat this as a signal, not a verdict: heuristic, review manually.
57
+ 0 errors, 0 warnings, 2 info
58
+
59
+ all 6 steps behaved as expected
60
+ ```
61
+
62
+ The transcript above is the output of [`demo.sh`](demo.sh) on the fixture servers:
63
+ config and probe see both servers, the lock matches, a changed schema turns
64
+ `verify` red, and `doctor --security` flags the risky tool as info only.
65
+
66
+ ## Install
67
+
68
+ ```bash
69
+ # from source, works today
70
+ pipx install git+https://github.com/Matrinus/mcpcheck
71
+ pip install git+https://github.com/Matrinus/mcpcheck
72
+
73
+ # from PyPI, once 0.1.0 is published (the distribution is mcpcheck-cli, the command is mcpcheck)
74
+ pipx install mcpcheck-cli
75
+ ```
76
+
77
+ `pipx` keeps the CLI in its own environment (recommended); `pip` installs it into
78
+ the current one. Python 3.11 or newer.
79
+
80
+ ## Quickstart
81
+
82
+ ```bash
83
+ mcpcheck config --config mcp.json # validate the config and resolve ${VAR}
84
+ mcpcheck probe --config mcp.json # start each server and read its tools
85
+ mcpcheck lock --config mcp.json -o mcp.lock.json # record schemas in a lockfile
86
+ mcpcheck verify --config mcp.json --lock mcp.lock.json # compare live tools with the lock
87
+ mcpcheck doctor --config mcp.json --security # aggregate findings and security hints
88
+ ```
89
+
90
+ ## What it does
91
+
92
+ | command | returns | exit code |
93
+ | -------- | ----------------------------------------------------------------------- | --------- |
94
+ | `config` | discovered/validated configs, resolved env, config errors | 0, 1, 2 |
95
+ | `probe` | per-server status, startup ms, tools, schema hashes, resources | 0, 1, 2 |
96
+ | `lock` | writes `mcp.lock.json` for servers that answered | 0, 2, 3 |
97
+ | `verify` | added / removed / changed tools versus the lockfile | 0, 1, 2, 3 |
98
+ | `doctor` | findings `DOC001`–`DOC009` with severity and an actionable hint | 0, 1, 2 |
99
+
100
+ `--json` is available on every command and is byte-stable across runs: no
101
+ timestamps, sorted keys. The only exception is `startup_ms` in `probe`, which
102
+ measures real process startup.
103
+
104
+ ## How it works
105
+
106
+ `mcpcheck` speaks JSON-RPC over stdio itself: one JSON message per line,
107
+ `initialize` + `notifications/initialized`, a deadline on every read, and a
108
+ process-group kill on timeout or close. It then sends `tools/list` (following
109
+ `nextCursor`) and `resources/list`. Each tool is hashed as the SHA-256 of its
110
+ canonical JSON schema with sorted keys, so a new parameter changes the hash while
111
+ reformatting the config does not. Environment values are expanded and handed to
112
+ the child process, but never serialized: `--json` carries only `env_keys`, so
113
+ secrets stay out of logs and CI output.
114
+
115
+ ## What it does not do
116
+
117
+ - HTTP/SSE transports — remote servers are reported as `unsupported` (v0.2).
118
+ - OAuth or any interactive auth; a server that needs a browser cannot be probed.
119
+ - Tools are never called, so it cannot tell you whether a tool *works*.
120
+ - The `--security` checks are heuristics on names and descriptions, not an audit.
121
+ - Linux and macOS only in v0.1.
122
+
123
+ ## Exit codes
124
+
125
+ | code | meaning |
126
+ | ---- | ------------------------------------------------------------------------- |
127
+ | 0 | success; changes outside the `--fail-on` policy are still printed |
128
+ | 1 | config errors, unreachable servers, findings (with `--strict` also warns), or changes inside the policy |
129
+ | 2 | usage error, unreadable or invalid config/lockfile |
130
+ | 3 | a server did not respond during `lock`/`verify`, so nothing was compared |
131
+
132
+ ## Use as a GitHub Action
133
+
134
+ The composite action installs its own Python 3.12 and runs `mcpcheck verify`,
135
+ failing the job on changes inside `fail-on` (`any` by default):
136
+
137
+ ```yaml
138
+ - uses: actions/checkout@v4
139
+ - uses: Matrinus/mcpcheck@v0.1.0
140
+ with:
141
+ config: .mcp.json
142
+ lock: mcp.lock.json
143
+ fail-on: any
144
+ ```
145
+
146
+ Inputs: `config` (default `.mcp.json`), `lock` (default `mcp.lock.json`),
147
+ `fail-on` (`any`, `added`, `removed` or `changed`) and `timeout` in seconds
148
+ (default `5`). Pin the tag to the version of `mcpcheck` that wrote the lockfile;
149
+ see [`action.yml`](action.yml) for the full definition.
150
+
151
+ ## Roadmap
152
+
153
+ - **v0.2** — HTTP/SSE transports, `--watch`, pre-commit hook.
154
+ - **v0.3** — per-project policy (`policy.yaml`), SARIF export for code scanning.
155
+ - **v0.4** — compare two machines: what one has that the other does not.
156
+
157
+ See [`docs/design.md`](docs/design.md) for the decisions behind v0.1.
158
+
159
+ ## Contributing
160
+
161
+ See [CONTRIBUTING.md](CONTRIBUTING.md). New config formats and new doctor rules
162
+ are designed to be small, self-contained contributions; `make check` must pass
163
+ and `bash demo.sh` must stay green.
164
+
165
+ ## License
166
+
167
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,13 @@
1
+ mcpcheck/__init__.py,sha256=C52JK4KMjf9MnPZNJ_yYBD0f49c1qgMV5818fiDNO7Y,58
2
+ mcpcheck/cli.py,sha256=KL2qcTx_XyZ43AJJLP1w-JNuVWl0Pj_C0d4Kc57pgfM,12742
3
+ mcpcheck/config.py,sha256=MBk_HsdL3kYAHhinlIbPt1BklStqns6c_9zIG96X2VE,6613
4
+ mcpcheck/doctor.py,sha256=EUf0WUshH7xmsju9jNNrp_IgK46NrNxmFpLn-XEbOaU,8244
5
+ mcpcheck/lockfile.py,sha256=qVsxb94P3a0j6TjhLB-Bx2TQJje9u1oh6W3ynCYnTSI,4859
6
+ mcpcheck/probe.py,sha256=sg_ajxr54dKgRJEo-aLXNUcf8WdsQZ_cK7vcGvrdPqY,5963
7
+ mcpcheck/protocol.py,sha256=3JCASXDVDi8O-zX-06m6TbvteANP3Q05QQHK9h8Y0O8,10339
8
+ mcpcheck_cli-0.1.0.dist-info/licenses/LICENSE,sha256=rLDUrMKykect_CHiStO3w2lvd6Pe3HLpQQtgn2gvUpg,1065
9
+ mcpcheck_cli-0.1.0.dist-info/METADATA,sha256=XU3zD1BfU6-bipVyFncor1vUtEDbF8AVqpHAmhIpa5Y,6896
10
+ mcpcheck_cli-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
11
+ mcpcheck_cli-0.1.0.dist-info/entry_points.txt,sha256=jyG6b1BtMtHEevQcuaNg4eGani97JdeV5F3Bnd-v28A,47
12
+ mcpcheck_cli-0.1.0.dist-info/top_level.txt,sha256=NpQNQnxv8knCFfkoeTk5EA4tvS8ruVX7_pZqEMU5IHo,9
13
+ mcpcheck_cli-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ mcpcheck = mcpcheck.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Matrinus
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ mcpcheck