@eidonze/mcpdoctor 0.1.3 → 0.1.4

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.
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 xka0085-byte (Eidon)
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.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 xka0085-byte (Eidon)
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.
package/README.md CHANGED
@@ -1,110 +1,161 @@
1
- # mcpdoctor
2
-
3
- > ⚠️ **Official package notice**: this is the official `mcpdoctor`, published by npm user [`eidonze`](https://www.npmjs.com/~eidonze), repo [`xka0085-byte/mcp-doctor`](https://github.com/xka0085-byte/mcp-doctor). We are **NOT affiliated** with **mcpdoctor.dev** — that is a *different* product (an MCP **server-auditing** tool). This `mcpdoctor` is an independent, read-only **402/x402 payment-endpoint inspector CLI**. Same name, different tool. Verify the package by its scope: `@eidonze/mcpdoctor`.
4
-
5
- **mcpdoctor is a read-only CLI for inspecting MCP and x402 endpoints.**
6
-
7
- Point it at a URL, get one `PASS / FAIL / UNKNOWN` report:
8
-
9
- - the **HTTP 402 payment document** — parsed from the known locations
10
- (`Payment-Required` / `X-Payment-Required` / `WWW-Authenticate` headers or
11
- the response body), in both x402 v1 (`accepts[]`) and v2 (`x402.accepts`)
12
- shapes, with every `scheme / network / asset / amount / payTo` field checked;
13
- - the **discovery manifests** — whether `/.well-known/mcp/server.json` and
14
- `/.well-known/x402` are reachable, with a SHA-256 of each;
15
- - a **SHA-256 digest** of the response body, plus latency and size.
16
-
17
- mcpdoctor is **not an MCP server** and does not implement the MCP protocol.
18
- It is the endpoint inspector you run *before* pointing an MCP client or an
19
- x402 buyer at an endpoint — a preflight/debugging tool for AI-agent payment
20
- infrastructure. Zero dependencies. Node ≥ 18. Never touches keys, never pays.
21
-
22
- ## Install
23
-
24
- ```bash
25
- npm install -g @eidonze/mcpdoctor # or run without installing:
26
- npx @eidonze/mcpdoctor inspect <url>
27
- ```
28
-
29
- ## Usage
30
-
31
- ```bash
32
- mcpdoctor inspect <url> [--method=GET|POST] [--format=json|markdown]
33
- ```
34
-
35
- | Option | Default | Description |
36
- |---|---|---|
37
- | `--method` | `GET` | HTTP verb for the probe (`POST` sends `{}`) |
38
- | `--format` | `markdown` | `json` for CI / machine-readable reports |
39
- | `--json` | — | shorthand for `--format=json` |
40
-
41
- Exit codes: `0` PASS · `1` FAIL · `2` UNKNOWN (network/timeout) · `3` usage error.
42
-
43
- ## Real examples (captured 2026-09-29, against live endpoints)
44
-
45
- Inspecting an MCP endpoint that is free (no payment gate) — the tool reports
46
- the 200 instead of a 402, and still verifies the discovery manifests:
47
-
48
- ```json
49
- {
50
- "endpoint": "https://agenttoll-receipts.app.workbuddy.host/mcp",
51
- "method": "POST",
52
- "finalStatus": "FAIL",
53
- "http": { "status": 200, "elapsedMs": 2830, "bodyBytes": 82,
54
- "bodySha256": "598dc097dcca1e573c742100863899c00724a021b421a5bb49952d49fec6b4f4" },
55
- "findings": [
56
- { "status": "FAIL", "code": "NO_402", "message": "Expected HTTP 402, received 200" }
57
- ],
58
- "metadata": [
59
- { "path": "/.well-known/mcp/server.json", "status": 200, "reachable": true }
60
- ]
61
- }
62
- ```
63
-
64
- Inspecting the official x402 demo endpoint — it does return 402, but ships a
65
- payment document mcpdoctor cannot parse, which is exactly the class of silent
66
- breakage this CLI exists to catch:
67
-
68
- ```json
69
- {
70
- "endpoint": "https://x402.org/protected",
71
- "finalStatus": "FAIL",
72
- "http": { "status": 402 },
73
- "headers": { "paymentRequired": true },
74
- "findings": [
75
- { "status": "FAIL", "code": "NO_ACCEPTS",
76
- "message": "No recognizable payment requirement found" }
77
- ]
78
- }
79
- ```
80
-
81
- ## What it does NOT do
82
-
83
- - No MCP protocol session: no `initialize`, no `tools/list` — mcpdoctor
84
- checks what an endpoint *advertises* (402 documents, discovery manifests),
85
- not a full MCP handshake.
86
- - No wallet, signing, settlement, or retries. Read-only preflight only.
87
- - `PASS` means the observed 402 document had recognizable, complete fields —
88
- it is not a security or payment-success certification.
89
-
90
- ## Why
91
-
92
- We ship an x402 service ourselves ([ReceiptRail](https://github.com/xka0085-byte/agenttoll))
93
- and hit every way a paid endpoint can silently break:
94
-
95
- - an endpoint that validates the request body **before** returning the 402
96
- challenge is invisible to every x402 client — they only react to `402`;
97
- - payment documents arrive in **four different places** and **two different
98
- shapes**; parsers that only look at one place report false failures;
99
- - vendor hint headers without `accepts[]` can shadow the real payment document.
100
-
101
- Each check in mcpdoctor maps to a failure mode we actually hit in production.
102
-
103
- ## Part of the Agent / Chain Evidence Tools suite
104
-
105
- Read-only diagnostics for AI agents on Web3 —
106
- [hub & docs](https://xka0085-byte.github.io/evidence-tools/) ·
107
- [ReceiptRail (live MCP service)](https://github.com/xka0085-byte/agenttoll) ·
108
- [npm: @eidonze/mcpdoctor](https://www.npmjs.com/package/@eidonze/mcpdoctor)
109
-
110
- MIT licensed. Known limitations are documented, not hidden.
1
+ # mcpdoctor
2
+
3
+ > ⚠️ **Official package notice**: this is the official `mcpdoctor`, published by npm user [`eidonze`](https://www.npmjs.com/~eidonze), repo [`xka0085-byte/mcp-doctor`](https://github.com/xka0085-byte/mcp-doctor). We are **NOT affiliated** with **mcpdoctor.dev** — that is a *different* product (an MCP **server-auditing** tool). This `mcpdoctor` is an independent, read-only **402/x402 payment-endpoint inspector CLI**. Same name, different tool. Verify the package by its scope: `@eidonze/mcpdoctor`.
4
+
5
+ **mcpdoctor is a read-only CLI for inspecting MCP and x402 endpoints.**
6
+
7
+ Point it at a URL, get one `PASS / FAIL / UNKNOWN` report:
8
+
9
+ - the **HTTP 402 payment document** — parsed from the known locations
10
+ (`Payment-Required` / `X-Payment-Required` / `WWW-Authenticate` headers or
11
+ the response body), in both x402 v1 (`accepts[]`) and v2 (`x402.accepts`)
12
+ shapes, with every `scheme / network / asset / amount / payTo` field checked;
13
+ - the **discovery manifests** — whether `/.well-known/mcp/server.json` and
14
+ `/.well-known/x402` are reachable, with a SHA-256 of each;
15
+ - a **SHA-256 digest** of the response body, plus latency and size.
16
+
17
+ mcpdoctor is **not an MCP server** and does not implement the MCP protocol.
18
+ It is the endpoint inspector you run *before* pointing an MCP client or an
19
+ x402 buyer at an endpoint — a preflight/debugging tool for AI-agent payment
20
+ infrastructure. Zero dependencies. Node ≥ 18. Never touches keys, never pays.
21
+
22
+ ## Install
23
+
24
+ ```bash
25
+ npm install -g @eidonze/mcpdoctor # or run without installing:
26
+ npx @eidonze/mcpdoctor inspect <url>
27
+ ```
28
+
29
+ Current release: `0.1.4`. The CLI is read-only: it does not sign, pay, retry payment, invoke MCP tools, or accept private keys.
30
+
31
+ ## GitHub Actions
32
+
33
+ Run the check in pull requests without installing a package or storing a key:
34
+
35
+ ```yaml
36
+ name: MCP Trust Check
37
+ on: [pull_request]
38
+
39
+ jobs:
40
+ mcp-trust:
41
+ runs-on: ubuntu-latest
42
+ steps:
43
+ - uses: xka0085-byte/mcpdoctor@v1
44
+ with:
45
+ endpoint: https://your-mcp-server.example/mcp
46
+ mode: schema
47
+ format: markdown
48
+ ```
49
+
50
+ `schema` performs read-only `initialize` and `tools/list` checks. Use `mode: inspect`
51
+ for a read-only x402 HTTP 402 preflight. A non-zero exit means the observed result
52
+ was `FAIL` or `UNKNOWN`; this is a CI gate, not a security certification.
53
+
54
+ ## Why
55
+
56
+ Shipping an x402 service ourselves ([ReceiptRail](https://github.com/xka0085-byte/agenttoll)),
57
+ we hit every way a paid endpoint can silently break:
58
+
59
+ - an endpoint that validates the request body **before** returning the 402
60
+ challenge is invisible to every x402 client — they only react to `402`;
61
+ - payment documents arrive in **four different places** (`Payment-Required` /
62
+ `X-Payment-Required` / `WWW-Authenticate` headers, or the response body) and
63
+ in **two different shapes** (v1 top-level `accepts[]`, v2 nested `x402.accepts`);
64
+ parsers that only look at one place report false failures;
65
+ - vendor hint headers without `accepts[]` can shadow the real payment document.
66
+
67
+ Each check in mcpdoctor maps to a failure mode we actually hit in production.
68
+
69
+ ## Usage
70
+
71
+ ```bash
72
+ mcpdoctor inspect <url> [--method=GET|POST] [--format=json|markdown]
73
+ ```
74
+
75
+ | Option | Default | Description |
76
+ |---|---|---|
77
+ | `--method` | `GET` | HTTP verb for the probe (`POST` sends `{}`) |
78
+ | `--format` | `markdown` | `json` for CI / machine-readable reports |
79
+ | `--json` | — | shorthand for `--format=json` |
80
+
81
+ Exit codes: `0` PASS · `1` FAIL · `2` UNKNOWN (network/timeout) · `3` usage error.
82
+
83
+ ## Tool schema checks
84
+
85
+ Inspect MCP initialization and `tools/list` without calling tools:
86
+
87
+ ```bash
88
+ node mcpdoctor/bin/mcpdoctor.mjs schema https://your-mcp-server.example/mcp --json
89
+ ```
90
+
91
+ This is deterministic static lint, not a prediction of model tool selection or a cross-client certification. See [`SCHEMA-MVP.md`](./SCHEMA-MVP.md).
92
+
93
+ ## Real examples (captured 2026-09-29, against live endpoints)
94
+
95
+
96
+ Inspecting an MCP endpoint that is free (no payment gate) — the tool reports
97
+ the 200 instead of a 402, and still verifies the discovery manifests:
98
+
99
+ ```json
100
+ {
101
+ "endpoint": "https://agenttoll-receipts.app.workbuddy.host/mcp",
102
+ "method": "POST",
103
+ "finalStatus": "FAIL",
104
+ "http": { "status": 200, "elapsedMs": 2830, "bodyBytes": 82,
105
+ "bodySha256": "598dc097dcca1e573c742100863899c00724a021b421a5bb49952d49fec6b4f4" },
106
+ "findings": [
107
+ { "status": "FAIL", "code": "NO_402", "message": "Expected HTTP 402, received 200" }
108
+ ],
109
+ "metadata": [
110
+ { "path": "/.well-known/mcp/server.json", "status": 200, "reachable": true }
111
+ ]
112
+ }
113
+ ```
114
+
115
+ Inspecting the official x402 demo endpoint — it does return 402, but ships a
116
+ payment document mcpdoctor cannot parse, which is exactly the class of silent
117
+ breakage this CLI exists to catch:
118
+
119
+ ```json
120
+ {
121
+ "endpoint": "https://x402.org/protected",
122
+ "finalStatus": "FAIL",
123
+ "http": { "status": 402 },
124
+ "headers": { "paymentRequired": true },
125
+ "findings": [
126
+ { "status": "FAIL", "code": "NO_ACCEPTS",
127
+ "message": "No recognizable payment requirement found" }
128
+ ]
129
+ }
130
+ ```
131
+
132
+ ## What it does NOT do
133
+
134
+ - No MCP protocol session: no `initialize`, no `tools/list` — mcpdoctor
135
+ checks what an endpoint *advertises* (402 documents, discovery manifests),
136
+ not a full MCP handshake.
137
+ - No wallet, signing, settlement, or retries. Read-only preflight only.
138
+ - `PASS` means the observed 402 document had recognizable, complete fields —
139
+ it is not a security or payment-success certification.
140
+
141
+ ## Why
142
+
143
+ We ship an x402 service ourselves ([ReceiptRail](https://github.com/xka0085-byte/agenttoll))
144
+ and hit every way a paid endpoint can silently break:
145
+
146
+ - an endpoint that validates the request body **before** returning the 402
147
+ challenge is invisible to every x402 client — they only react to `402`;
148
+ - payment documents arrive in **four different places** and **two different
149
+ shapes**; parsers that only look at one place report false failures;
150
+ - vendor hint headers without `accepts[]` can shadow the real payment document.
151
+
152
+ Each check in mcpdoctor maps to a failure mode we actually hit in production.
153
+
154
+ ## Part of the Agent / Chain Evidence Tools suite
155
+
156
+ Read-only diagnostics for AI agents on Web3 —
157
+ [hub & docs](https://xka0085-byte.github.io/evidence-tools/) ·
158
+ [ReceiptRail (live MCP service)](https://github.com/xka0085-byte/agenttoll) ·
159
+ [npm: @eidonze/mcpdoctor](https://www.npmjs.com/package/@eidonze/mcpdoctor)
160
+
161
+ MIT licensed. Known limitations are documented, not hidden.
package/bin/mcpdoctor.mjs CHANGED
@@ -1,155 +1,194 @@
1
- #!/usr/bin/env node
2
- import { createHash } from 'node:crypto';
3
-
4
- const MAX_BODY = 1024 * 1024;
5
- const TIMEOUT = 10_000;
6
- const VERSION = '0.1.3';
7
-
8
- const help = `mcpdoctor ${VERSION}
9
-
10
- Read-only MCP/x402 endpoint diagnostics.
11
-
12
- Usage:
13
- mcpdoctor inspect <url> [--method=GET|POST] [--format=json|markdown]
14
- mcpdoctor --help
15
-
16
- This MVP never signs, pays, retries payment, or accepts a private key.`;
17
-
18
- function die(message, code = 3) {
19
- console.error(`Error: ${message}\n\n${help}`);
20
- process.exitCode = code;
21
- }
22
-
23
- function redact(value) {
24
- return typeof value === 'string'
25
- ? value.replace(/(authorization|signature|token|api[_-]?key)\s*[:=]\s*[^,\s}]+/gi, '$1: [REDACTED]').replace(/Bearer\s+[^\s]+/gi, 'Bearer [REDACTED]')
26
- : value;
27
- }
28
-
29
- async function readBody(response) {
30
- const reader = response.body?.getReader();
31
- if (!reader) return '';
32
- const chunks = [];
33
- let size = 0;
34
- while (true) {
35
- const { done, value } = await reader.read();
36
- if (done) break;
37
- size += value.byteLength;
38
- if (size > MAX_BODY) { await reader.cancel(); throw new Error(`response body exceeds ${MAX_BODY} bytes`); }
39
- chunks.push(value);
40
- }
41
- return Buffer.concat(chunks).toString('utf8');
42
- }
43
-
44
- function headersOf(headers) {
45
- return Object.fromEntries([...headers].map(([key, value]) => [key.toLowerCase(), redact(value)]));
46
- }
47
-
48
- function json(text) { try { return JSON.parse(text); } catch { return null; } }
49
-
50
- function findPaymentDocument(headers, body) {
51
- const candidates = [headers['payment-required'], headers['x-payment-required'], headers['www-authenticate'], body].filter(Boolean);
52
- const parsed = [];
53
- for (const candidate of candidates) {
54
- const direct = json(candidate);
55
- if (direct && typeof direct === 'object') { parsed.push(direct); continue; }
56
- const start = candidate.indexOf('{');
57
- const end = candidate.lastIndexOf('}');
58
- if (start >= 0 && end > start) {
59
- const nested = json(candidate.slice(start, end + 1));
60
- if (nested) parsed.push(nested);
61
- }
62
- }
63
- if (!parsed.length) return null;
64
- // headers like x-payment-required may carry vendor hints without accepts[] —
65
- // prefer the candidate that actually contains payment requirements
66
- return parsed.find((d) => requirements(d).length > 0) ?? parsed[0];
67
- }
68
-
69
- function requirements(document) {
70
- if (!document || typeof document !== 'object') return [];
71
- // x402 v2 canonical shape: { x402: { version: 2, accepts: [...] } }
72
- if (document.x402 && Array.isArray(document.x402.accepts)) return document.x402.accepts;
73
- if (Array.isArray(document.accepts)) return document.accepts;
74
- if (Array.isArray(document.paymentRequirements?.accepts)) return document.paymentRequirements.accepts;
75
- if (document.paymentRequirements && typeof document.paymentRequirements === 'object') return [document.paymentRequirements];
76
- if (document.challenge && typeof document.challenge === 'object') return [document.challenge];
77
- return [];
78
- }
79
-
80
- function normalize(item) {
81
- return {
82
- scheme: item.scheme ?? null,
83
- network: item.network ?? item.chain ?? null,
84
- asset: item.asset ?? item.mint ?? null,
85
- amount: item.amount ?? item.maxAmountRequired ?? null,
86
- payTo: item.payTo ?? item.vendor ?? item.recipient ?? null,
87
- maxTimeoutSeconds: item.maxTimeoutSeconds ?? null,
88
- };
89
- }
90
-
91
- async function probe(url, method = 'GET') {
92
- const started = Date.now();
93
- const init = { method, redirect: 'manual', signal: AbortSignal.timeout(TIMEOUT), headers: { accept: 'application/json, application/problem+json, text/plain' } };
94
- if (method === 'POST') { init.headers['content-type'] = 'application/json'; init.body = '{}'; }
95
- const response = await fetch(url, init);
96
- const body = await readBody(response);
97
- const headers = headersOf(response.headers);
98
- return { response, body, headers, elapsedMs: Date.now() - started };
99
- }
100
-
101
- async function metadata(base, path) {
102
- try {
103
- const result = await probe(new URL(path, base).toString(), 'GET');
104
- return { path, status: result.response.status, reachable: result.response.ok, bodySha256: createHash('sha256').update(result.body).digest('hex'), bodyBytes: Buffer.byteLength(result.body) };
105
- } catch (error) { return { path, status: null, reachable: false, error: redact(error.message) }; }
106
- }
107
-
108
- function makeReport(url, method, result) {
109
- const { response, body, headers, elapsedMs } = result;
110
- const document = findPaymentDocument(headers, body);
111
- const accepts = requirements(document).map(normalize);
112
- const findings = [];
113
- if (response.status !== 402) findings.push({ status: 'FAIL', code: 'NO_402', message: `Expected HTTP 402, received ${response.status}` });
114
- if (!document) findings.push({ status: 'FAIL', code: 'NO_PAYMENT_DOCUMENT', message: 'No parseable payment document in known headers or body' });
115
- if (document && !accepts.length) findings.push({ status: 'FAIL', code: 'NO_ACCEPTS', message: 'No recognizable payment requirement found' });
116
- for (const [index, item] of accepts.entries()) for (const field of ['scheme', 'network', 'asset', 'amount', 'payTo']) if (!item[field]) findings.push({ status: 'FAIL', code: `MISSING_${field.toUpperCase()}`, message: `accepts[${index}] is missing ${field}` });
117
- const digest = createHash('sha256').update(body).digest('hex');
118
- return { reportVersion: 1, inspectorVersion: VERSION, mode: 'read-only', checkedAt: new Date().toISOString(), endpoint: url, method, finalStatus: response.status === 402 && document && accepts.length && !findings.length ? 'PASS' : 'FAIL', http: { status: response.status, elapsedMs, contentType: headers['content-type'] ?? null, bodyBytes: Buffer.byteLength(body), bodySha256: digest }, headers: { paymentRequired: Boolean(headers['payment-required'] || headers['x-payment-required']), wwwAuthenticate: Boolean(headers['www-authenticate']) }, x402: { version: document?.x402Version ?? null, resource: document?.resource ?? null, accepts }, findings, limitations: ['Read-only preflight only; no wallet, signing, settlement, or post-payment delivery was attempted.', 'PASS means the observed 402 document had recognizable fields; it is not a security, payment-success, or content-quality certification.'] };
119
- }
120
-
121
- function markdown(report) {
122
- const lines = [`# mcpdoctor report`, '', `- Status: **${report.finalStatus}**`, `- Endpoint: ${report.endpoint}`, `- HTTP: ${report.http.status}`, `- Response: ${report.http.elapsedMs} ms / ${report.http.bodyBytes} bytes`, `- Body SHA-256: \`${report.http.bodySha256}\``, '', '## Payment requirements', ''];
123
- if (!report.x402.accepts.length) lines.push('- None parsed', '');
124
- report.x402.accepts.forEach((item, i) => lines.push(`### accepts[${i}]`, '', ...Object.entries(item).map(([key, value]) => `- ${key}: ${value ?? 'missing'}`), ''));
125
- lines.push('## Findings', '', ...(report.findings.length ? report.findings.map((item) => `- **${item.status}** \`${item.code}\`: ${item.message}`) : ['- None']), '', '## Limitations', '', ...report.limitations.map((item) => `- ${item}`), '');
126
- return lines.join('\n');
127
- }
128
-
129
- const args = process.argv.slice(2);
130
- if (args.includes('--help') || args.length === 0) { console.log(help); process.exitCode = args.length ? 0 : 3; }
131
- else if (args[0] !== 'inspect') die('only the inspect command is available in this MVP');
132
- else {
133
- const rawUrl = args[1];
134
- const method = (args.find((arg) => arg.startsWith('--method='))?.split('=')[1] ?? 'GET').toUpperCase();
135
- const format = args.find((arg) => arg.startsWith('--format='))?.split('=')[1] ?? (args.includes('--json') ? 'json' : 'markdown');
136
- if (!rawUrl) die('URL is required');
137
- else if (!['GET', 'POST'].includes(method)) die('--method must be GET or POST');
138
- else if (!['json', 'markdown'].includes(format)) die('--format must be json or markdown');
139
- else {
140
- let url;
141
- try { url = new URL(rawUrl); if (!['http:', 'https:'].includes(url.protocol)) throw new Error('only http(s) URLs are supported'); }
142
- catch (error) { die(error.message); }
143
- if (url) try {
144
- const result = await probe(url, method);
145
- const report = makeReport(url.toString(), method, result);
146
- report.metadata = await Promise.all(['/.well-known/mcp/server.json', '/.well-known/x402'].map((path) => metadata(url, path)));
147
- process.stdout.write(format === 'json' ? `${JSON.stringify(report, null, 2)}\n` : markdown(report));
148
- process.exitCode = report.finalStatus === 'PASS' ? 0 : 1;
149
- } catch (error) {
150
- const report = { reportVersion: 1, inspectorVersion: VERSION, mode: 'read-only', checkedAt: new Date().toISOString(), endpoint: url.toString(), finalStatus: 'UNKNOWN', findings: [{ status: 'UNKNOWN', code: 'REQUEST_FAILED', message: redact(error.message) }], limitations: ['The endpoint could not be observed within the timeout/body limit. No payment was attempted.'] };
151
- process.stdout.write(format === 'json' ? `${JSON.stringify(report, null, 2)}\n` : markdown(report));
152
- process.exitCode = 2;
153
- }
154
- }
155
- }
1
+ #!/usr/bin/env node
2
+ import { createHash } from 'node:crypto';
3
+
4
+ const MAX_BODY = 1024 * 1024;
5
+ const TIMEOUT = 10_000;
6
+ const VERSION = '0.1.4';
7
+
8
+ const help = `mcpdoctor ${VERSION}
9
+
10
+ Read-only MCP/x402 endpoint diagnostics.
11
+
12
+ Usage:
13
+ mcpdoctor inspect <url> [--method=GET|POST] [--format=json|markdown]
14
+ mcpdoctor schema <url> [--format=json|markdown]
15
+ mcpdoctor --help
16
+
17
+ This MVP never signs, pays, retries payment, or accepts a private key.`;
18
+
19
+ function die(message, code = 3) {
20
+ console.error(`Error: ${message}\n\n${help}`);
21
+ process.exitCode = code;
22
+ }
23
+
24
+ function redact(value) {
25
+ return typeof value === 'string'
26
+ ? value.replace(/(authorization|signature|token|api[_-]?key)\s*[:=]\s*[^,\s}]+/gi, '$1: [REDACTED]').replace(/Bearer\s+[^\s]+/gi, 'Bearer [REDACTED]')
27
+ : value;
28
+ }
29
+
30
+ async function readBody(response) {
31
+ const reader = response.body?.getReader();
32
+ if (!reader) return '';
33
+ const chunks = [];
34
+ let size = 0;
35
+ while (true) {
36
+ const { done, value } = await reader.read();
37
+ if (done) break;
38
+ size += value.byteLength;
39
+ if (size > MAX_BODY) { await reader.cancel(); throw new Error(`response body exceeds ${MAX_BODY} bytes`); }
40
+ chunks.push(value);
41
+ }
42
+ return Buffer.concat(chunks).toString('utf8');
43
+ }
44
+
45
+ function headersOf(headers) {
46
+ return Object.fromEntries([...headers].map(([key, value]) => [key.toLowerCase(), redact(value)]));
47
+ }
48
+
49
+ function json(text) { try { return JSON.parse(text); } catch { return null; } }
50
+
51
+ function findPaymentDocument(headers, body) {
52
+ const candidates = [headers['payment-required'], headers['x-payment-required'], headers['www-authenticate'], body].filter(Boolean);
53
+ const parsed = [];
54
+ for (const candidate of candidates) {
55
+ const direct = json(candidate);
56
+ if (direct && typeof direct === 'object') { parsed.push(direct); continue; }
57
+ const start = candidate.indexOf('{');
58
+ const end = candidate.lastIndexOf('}');
59
+ if (start >= 0 && end > start) {
60
+ const nested = json(candidate.slice(start, end + 1));
61
+ if (nested) parsed.push(nested);
62
+ }
63
+ }
64
+ if (!parsed.length) return null;
65
+ // headers like x-payment-required may carry vendor hints without accepts[] —
66
+ // prefer the candidate that actually contains payment requirements
67
+ return parsed.find((d) => requirements(d).length > 0) ?? parsed[0];
68
+ }
69
+
70
+ function requirements(document) {
71
+ if (!document || typeof document !== 'object') return [];
72
+ // x402 v2 canonical shape: { x402: { version: 2, accepts: [...] } }
73
+ if (document.x402 && Array.isArray(document.x402.accepts)) return document.x402.accepts;
74
+ if (Array.isArray(document.accepts)) return document.accepts;
75
+ if (Array.isArray(document.paymentRequirements?.accepts)) return document.paymentRequirements.accepts;
76
+ if (document.paymentRequirements && typeof document.paymentRequirements === 'object') return [document.paymentRequirements];
77
+ if (document.challenge && typeof document.challenge === 'object') return [document.challenge];
78
+ return [];
79
+ }
80
+
81
+ function normalize(item) {
82
+ return {
83
+ scheme: item.scheme ?? null,
84
+ network: item.network ?? item.chain ?? null,
85
+ asset: item.asset ?? item.mint ?? null,
86
+ amount: item.amount ?? item.maxAmountRequired ?? null,
87
+ payTo: item.payTo ?? item.vendor ?? item.recipient ?? null,
88
+ maxTimeoutSeconds: item.maxTimeoutSeconds ?? null,
89
+ };
90
+ }
91
+
92
+ async function probe(url, method = 'GET') {
93
+ const started = Date.now();
94
+ const init = { method, redirect: 'manual', signal: AbortSignal.timeout(TIMEOUT), headers: { accept: 'application/json, application/problem+json, text/plain' } };
95
+ if (method === 'POST') { init.headers['content-type'] = 'application/json'; init.body = '{}'; }
96
+ const response = await fetch(url, init);
97
+ const body = await readBody(response);
98
+ const headers = headersOf(response.headers);
99
+ return { response, body, headers, elapsedMs: Date.now() - started };
100
+ }
101
+
102
+ async function metadata(base, path) {
103
+ try {
104
+ const result = await probe(new URL(path, base).toString(), 'GET');
105
+ return { path, status: result.response.status, reachable: result.response.ok, bodySha256: createHash('sha256').update(result.body).digest('hex'), bodyBytes: Buffer.byteLength(result.body) };
106
+ } catch (error) { return { path, status: null, reachable: false, error: redact(error.message) }; }
107
+ }
108
+
109
+ function makeReport(url, method, result) {
110
+ const { response, body, headers, elapsedMs } = result;
111
+ const document = findPaymentDocument(headers, body);
112
+ const accepts = requirements(document).map(normalize);
113
+ const findings = [];
114
+ if (response.status !== 402) findings.push({ status: 'FAIL', code: 'NO_402', message: `Expected HTTP 402, received ${response.status}` });
115
+ if (!document) findings.push({ status: 'FAIL', code: 'NO_PAYMENT_DOCUMENT', message: 'No parseable payment document in known headers or body' });
116
+ if (document && !accepts.length) findings.push({ status: 'FAIL', code: 'NO_ACCEPTS', message: 'No recognizable payment requirement found' });
117
+ for (const [index, item] of accepts.entries()) for (const field of ['scheme', 'network', 'asset', 'amount', 'payTo']) if (!item[field]) findings.push({ status: 'FAIL', code: `MISSING_${field.toUpperCase()}`, message: `accepts[${index}] is missing ${field}` });
118
+ const digest = createHash('sha256').update(body).digest('hex');
119
+ return { reportVersion: 1, inspectorVersion: VERSION, mode: 'read-only', checkedAt: new Date().toISOString(), endpoint: url, method, finalStatus: response.status === 402 && document && accepts.length && !findings.length ? 'PASS' : 'FAIL', http: { status: response.status, elapsedMs, contentType: headers['content-type'] ?? null, bodyBytes: Buffer.byteLength(body), bodySha256: digest }, headers: { paymentRequired: Boolean(headers['payment-required'] || headers['x-payment-required']), wwwAuthenticate: Boolean(headers['www-authenticate']) }, x402: { version: document?.x402Version ?? null, resource: document?.resource ?? null, accepts }, findings, limitations: ['Read-only preflight only; no wallet, signing, settlement, or post-payment delivery was attempted.', 'PASS means the observed 402 document had recognizable fields; it is not a security, payment-success, or content-quality certification.'] };
120
+ }
121
+
122
+ function markdown(report) {
123
+ const lines = [`# mcpdoctor report`, '', `- Status: **${report.finalStatus}**`, `- Endpoint: ${report.endpoint}`, `- HTTP: ${report.http.status}`, `- Response: ${report.http.elapsedMs} ms / ${report.http.bodyBytes} bytes`, `- Body SHA-256: \`${report.http.bodySha256}\``, '', '## Payment requirements', ''];
124
+ if (!report.x402.accepts.length) lines.push('- None parsed', '');
125
+ report.x402.accepts.forEach((item, i) => lines.push(`### accepts[${i}]`, '', ...Object.entries(item).map(([key, value]) => `- ${key}: ${value ?? 'missing'}`), ''));
126
+ lines.push('## Findings', '', ...(report.findings.length ? report.findings.map((item) => `- **${item.status}** \`${item.code}\`: ${item.message}`) : ['- None']), '', '## Limitations', '', ...report.limitations.map((item) => `- ${item}`), '');
127
+ return lines.join('\n');
128
+ }
129
+
130
+ async function schemaCommand(url, format) {
131
+ const findings = [];
132
+ const add = (code, severity, message) => findings.push({ code, severity, message });
133
+ const response = await fetch(url, { method: 'POST', redirect: 'manual', signal: AbortSignal.timeout(TIMEOUT), headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream', 'MCP-Protocol-Version': '2025-03-26' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-03-26', capabilities: {}, clientInfo: { name: 'mcpdoctor', version: VERSION } } }) });
134
+ const initText = await readBody(response);
135
+ if (!response.ok) throw new Error(`MCP initialize returned HTTP ${response.status}`);
136
+ const init = json(initText);
137
+ if (!init?.result?.protocolVersion) add('INITIALIZE_RESPONSE_INVALID', 'FAIL', 'Initialize response did not include result.protocolVersion');
138
+ const headers = { 'content-type': 'application/json', accept: 'application/json, text/event-stream', 'MCP-Protocol-Version': init?.result?.protocolVersion ?? '2025-03-26' };
139
+ const list = await fetch(url, { method: 'POST', redirect: 'manual', signal: AbortSignal.timeout(TIMEOUT), headers, body: JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'tools/list', params: {} }) });
140
+ const listText = await readBody(list);
141
+ if (!list.ok) throw new Error(`tools/list returned HTTP ${list.status}`);
142
+ const parsed = json(listText);
143
+ const tools = parsed?.result?.tools;
144
+ if (!Array.isArray(tools)) add('TOOLS_LIST_INVALID', 'FAIL', 'tools/list response did not contain result.tools[]');
145
+ else if (!tools.length) add('NO_TOOLS', 'WARN', 'Server exposes an empty tool list');
146
+ else for (const [i, tool] of tools.entries()) {
147
+ const at = `tools[${i}]`;
148
+ if (typeof tool.name !== 'string' || !tool.name.trim()) add('TOOL_NAME_MISSING', 'FAIL', `${at} has no name`);
149
+ if (typeof tool.description !== 'string' || !tool.description.trim()) add('TOOL_DESCRIPTION_MISSING', 'WARN', `${at} has no description`);
150
+ const schema = tool.inputSchema;
151
+ if (!schema || schema.type !== 'object') add('INPUT_SCHEMA_NOT_OBJECT', 'FAIL', `${at}.inputSchema must declare type: object`);
152
+ const props = schema?.properties;
153
+ if (props !== undefined && (!props || typeof props !== 'object' || Array.isArray(props))) add('PROPERTIES_INVALID', 'FAIL', `${at}.inputSchema.properties must be an object`);
154
+ for (const req of schema?.required ?? []) if (!props?.[req]) add('REQUIRED_PROPERTY_UNDEFINED', 'FAIL', `${at} requires undeclared property ${req}`);
155
+ for (const [key, property] of Object.entries(props ?? {})) if (typeof property?.description !== 'string' || !property.description.trim()) add('PROPERTY_DESCRIPTION_MISSING', 'WARN', `${at}.${key} has no description`);
156
+ }
157
+ if (!findings.length) add('STATIC_SCHEMA_CHECKS_PASSED', 'INFO', `${tools.length} tools passed deterministic schema checks`);
158
+ const report = { reportVersion: 1, inspectorVersion: VERSION, mode: 'read-only MCP initialize + tools/list', checkedAt: new Date().toISOString(), endpoint: url.toString(), finalStatus: findings.some(x => x.severity === 'FAIL') ? 'FAIL' : 'PASS', mcp: { protocolVersion: init?.result?.protocolVersion ?? null, serverInfo: init?.result?.serverInfo ?? null, toolCount: Array.isArray(tools) ? tools.length : null }, findings, limitations: ['Static schema checks do not predict model tool selection or prove behavior across all clients.', 'No tool was called; side effects, authorization, data quality and security were not tested.'] };
159
+ console.log(format === 'json' ? JSON.stringify(report, null, 2) : `# MCP Tool Schema Report\n\n- Status: **${report.finalStatus}**\n- Endpoint: ${report.endpoint}\n- Protocol: ${report.mcp.protocolVersion ?? 'unknown'}\n- Tools: ${report.mcp.toolCount ?? 'unknown'}\n\n${findings.map(x => `- **${x.severity}** \`${x.code}\`: ${x.message}`).join('\n')}\n\n${report.limitations.map(x => `- ${x}`).join('\n')}`);
160
+ process.exitCode = report.finalStatus === 'PASS' ? 0 : 1;
161
+ }
162
+
163
+ const args = process.argv.slice(2);
164
+ if (args.includes('--help') || args.length === 0) { console.log(help); process.exitCode = args.length ? 0 : 3; }
165
+ else if (args[0] === 'schema') {
166
+ let url; try { url = new URL(args[1]); if (!['http:', 'https:'].includes(url.protocol)) throw new Error('only http(s) URLs are supported'); } catch (error) { die(error.message); }
167
+ const format = args.includes('--json') || args.includes('--format=json') ? 'json' : 'markdown';
168
+ if (url) schemaCommand(url, format).catch((error) => { console.error(`UNKNOWN: ${redact(error.message)}`); process.exitCode = 2; });
169
+ }
170
+ else if (args[0] !== 'inspect') die('only inspect and schema commands are available in this MVP');
171
+ else {
172
+ const rawUrl = args[1];
173
+ const method = (args.find((arg) => arg.startsWith('--method='))?.split('=')[1] ?? 'GET').toUpperCase();
174
+ const format = args.find((arg) => arg.startsWith('--format='))?.split('=')[1] ?? (args.includes('--json') ? 'json' : 'markdown');
175
+ if (!rawUrl) die('URL is required');
176
+ else if (!['GET', 'POST'].includes(method)) die('--method must be GET or POST');
177
+ else if (!['json', 'markdown'].includes(format)) die('--format must be json or markdown');
178
+ else {
179
+ let url;
180
+ try { url = new URL(rawUrl); if (!['http:', 'https:'].includes(url.protocol)) throw new Error('only http(s) URLs are supported'); }
181
+ catch (error) { die(error.message); }
182
+ if (url) try {
183
+ const result = await probe(url, method);
184
+ const report = makeReport(url.toString(), method, result);
185
+ report.metadata = await Promise.all(['/.well-known/mcp/server.json', '/.well-known/x402'].map((path) => metadata(url, path)));
186
+ process.stdout.write(format === 'json' ? `${JSON.stringify(report, null, 2)}\n` : markdown(report));
187
+ process.exitCode = report.finalStatus === 'PASS' ? 0 : 1;
188
+ } catch (error) {
189
+ const report = { reportVersion: 1, inspectorVersion: VERSION, mode: 'read-only', checkedAt: new Date().toISOString(), endpoint: url.toString(), finalStatus: 'UNKNOWN', findings: [{ status: 'UNKNOWN', code: 'REQUEST_FAILED', message: redact(error.message) }], limitations: ['The endpoint could not be observed within the timeout/body limit. No payment was attempted.'] };
190
+ process.stdout.write(format === 'json' ? `${JSON.stringify(report, null, 2)}\n` : markdown(report));
191
+ process.exitCode = 2;
192
+ }
193
+ }
194
+ }
package/package.json CHANGED
@@ -1,17 +1,17 @@
1
- {
2
- "name": "@eidonze/mcpdoctor",
3
- "version": "0.1.3",
4
- "mcpName": "io.github.xka0085-byte/mcpdoctor",
5
- "description": "CLI for inspecting MCP and x402 endpoints: parses the HTTP 402 payment document (v1/v2 accepts[]), checks /.well-known/mcp and /.well-known/x402 discovery manifests, returns a response SHA-256 digest. Read-only endpoint inspector and preflight debugging tool for AI-agent payment endpoints. Not an MCP server. Zero dependencies.",
6
- "license": "MIT",
7
- "type": "module",
8
- "bin": { "mcpdoctor": "bin/mcpdoctor.mjs" },
9
- "main": "bin/mcpdoctor.mjs",
10
- "files": ["bin", "test", "README.md", "LICENSE"],
11
- "engines": { "node": ">=18" },
12
- "scripts": { "test": "node test/smoke.mjs" },
13
- "keywords": ["mcp", "model-context-protocol", "mcp-cli", "mcp-inspector", "mcp-endpoint-inspector", "mcp-debugging", "x402", "cli", "developer-tools", "diagnostics"],
14
- "repository": { "type": "git", "url": "git+https://github.com/xka0085-byte/mcp-doctor.git" },
15
- "bugs": { "url": "https://github.com/xka0085-byte/mcp-doctor/issues" },
16
- "homepage": "https://xka0085-byte.github.io/evidence-tools/"
17
- }
1
+ {
2
+ "name": "@eidonze/mcpdoctor",
3
+ "version": "0.1.4",
4
+ "mcpName": "io.github.xka0085-byte/mcpdoctor",
5
+ "description": "Read-only MCP and x402 endpoint preflight checks: 402 challenge shape, payment document parsing, accepts[] conformance, discovery manifests, response digest. Zero dependencies.",
6
+ "license": "MIT",
7
+ "type": "module",
8
+ "bin": { "mcpdoctor": "bin/mcpdoctor.mjs" },
9
+ "main": "bin/mcpdoctor.mjs",
10
+ "files": ["bin", "test", "README.md", "LICENSE"],
11
+ "engines": { "node": ">=18" },
12
+ "scripts": { "test": "node test/smoke.mjs" },
13
+ "keywords": ["mcp", "model-context-protocol", "mcp-cli", "mcp-inspector", "mcp-endpoint-inspector", "mcp-debugging", "x402", "cli", "developer-tools", "diagnostics"],
14
+ "repository": { "type": "git", "url": "git+https://github.com/xka0085-byte/mcp-doctor.git" },
15
+ "bugs": { "url": "https://github.com/xka0085-byte/mcp-doctor/issues" },
16
+ "homepage": "https://xka0085-byte.github.io/evidence-tools/"
17
+ }
package/test/smoke.mjs CHANGED
@@ -8,7 +8,7 @@ import path from 'node:path';
8
8
 
9
9
  const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
10
10
  const cli = path.join(root, 'bin', 'mcpdoctor.mjs');
11
- const server = createServer((request, response) => {
11
+ const server = createServer(async (request, response) => {
12
12
  if (request.url === '/good') {
13
13
  response.writeHead(402, { 'content-type': 'application/json', 'payment-required': JSON.stringify({ x402Version: 2, accepts: [{ scheme: 'exact', network: 'eip155:8453', asset: 'USDC', amount: '10000', payTo: '0x1234567890123456789012345678901234567890' }] }) });
14
14
  response.end(JSON.stringify({ x402Version: 2, accepts: [{ scheme: 'exact', network: 'eip155:8453', asset: 'USDC', amount: '10000', payTo: '0x1234567890123456789012345678901234567890' }] }));
@@ -21,6 +21,14 @@ const server = createServer((request, response) => {
21
21
  response.end(JSON.stringify({ x402Version: 2, resource: { url: 'x', description: 'd', mimeType: 'application/json' }, accepts: [{ scheme: 'exact', network: 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1', amount: '1000', asset: 'MINT', payTo: 'PayToAddr' }] }));
22
22
  return;
23
23
  }
24
+ if (request.url === '/mcp') {
25
+ let incoming = ''; for await (const chunk of request) incoming += chunk;
26
+ const rpc = JSON.parse(incoming || '{}');
27
+ if (rpc.method === 'initialize') {
28
+ response.writeHead(200, { 'content-type': 'application/json' }); response.end(JSON.stringify({ jsonrpc: '2.0', id: rpc.id, result: { protocolVersion: '2025-06-18', serverInfo: { name: 'fixture', version: '1' }, capabilities: {} } })); return;
29
+ }
30
+ response.writeHead(200, { 'content-type': 'application/json' }); response.end(JSON.stringify({ jsonrpc: '2.0', id: rpc.id, result: { tools: [{ name: 'hello', description: 'Returns a greeting.', inputSchema: { type: 'object', properties: { name: { type: 'string', description: 'Name.' } }, required: ['name'] } }] } })); return;
31
+ }
24
32
  // regression (our original production bug): body validation must not shadow the 402
25
33
  if (request.url === '/bad-400') {
26
34
  response.writeHead(400, { 'content-type': 'application/json' });
@@ -43,6 +51,15 @@ function run(url, ...args) {
43
51
  child.on('close', (code) => resolve({ code, stdout, stderr }));
44
52
  });
45
53
  }
54
+ function runSchema(url) {
55
+ return new Promise((resolve) => {
56
+ const child = spawn(process.execPath, [cli, 'schema', url, '--format=json'], { stdio: ['ignore', 'pipe', 'pipe'] });
57
+ let stdout = ''; let stderr = '';
58
+ child.stdout.on('data', (chunk) => { stdout += chunk; });
59
+ child.stderr.on('data', (chunk) => { stderr += chunk; });
60
+ child.on('close', (code) => resolve({ code, stdout, stderr }));
61
+ });
62
+ }
46
63
 
47
64
  try {
48
65
  const good = await run(`http://127.0.0.1:${port}/good`);
@@ -61,6 +78,11 @@ try {
61
78
  const bad400Report = JSON.parse(bad400.stdout);
62
79
  assert.equal(bad400Report.finalStatus, 'FAIL');
63
80
  assert.ok(bad400Report.findings.some((f) => f.code === 'NO_402'), 'must flag 400-instead-of-402');
81
+ const schema = await runSchema(`http://127.0.0.1:${port}/mcp`);
82
+ assert.equal(schema.code, 0, schema.stderr);
83
+ const schemaReport = JSON.parse(schema.stdout);
84
+ assert.equal(schemaReport.finalStatus, 'PASS', JSON.stringify(schemaReport.findings));
85
+ assert.equal(schemaReport.mcp.toolCount, 1);
64
86
  const help = await new Promise((resolve) => {
65
87
  const child = spawn(process.execPath, [cli, '--help'], { stdio: ['ignore', 'pipe', 'pipe'] });
66
88
  let stdout = ''; child.stdout.on('data', (chunk) => { stdout += chunk; }); child.on('close', (code) => resolve({ code, stdout }));