@eidonze/mcpdoctor 0.1.2 → 0.1.3

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.
Files changed (3) hide show
  1. package/README.md +110 -108
  2. package/bin/mcpdoctor.mjs +155 -155
  3. package/package.json +17 -17
package/README.md CHANGED
@@ -1,108 +1,110 @@
1
- # mcpdoctor
2
-
3
- **mcpdoctor is a read-only CLI for inspecting MCP and x402 endpoints.**
4
-
5
- Point it at a URL, get one `PASS / FAIL / UNKNOWN` report:
6
-
7
- - the **HTTP 402 payment document** — parsed from the known locations
8
- (`Payment-Required` / `X-Payment-Required` / `WWW-Authenticate` headers or
9
- the response body), in both x402 v1 (`accepts[]`) and v2 (`x402.accepts`)
10
- shapes, with every `scheme / network / asset / amount / payTo` field checked;
11
- - the **discovery manifests** — whether `/.well-known/mcp/server.json` and
12
- `/.well-known/x402` are reachable, with a SHA-256 of each;
13
- - a **SHA-256 digest** of the response body, plus latency and size.
14
-
15
- mcpdoctor is **not an MCP server** and does not implement the MCP protocol.
16
- It is the endpoint inspector you run *before* pointing an MCP client or an
17
- x402 buyer at an endpoint — a preflight/debugging tool for AI-agent payment
18
- infrastructure. Zero dependencies. Node ≥ 18. Never touches keys, never pays.
19
-
20
- ## Install
21
-
22
- ```bash
23
- npm install -g @eidonze/mcpdoctor # or run without installing:
24
- npx @eidonze/mcpdoctor inspect <url>
25
- ```
26
-
27
- ## Usage
28
-
29
- ```bash
30
- mcpdoctor inspect <url> [--method=GET|POST] [--format=json|markdown]
31
- ```
32
-
33
- | Option | Default | Description |
34
- |---|---|---|
35
- | `--method` | `GET` | HTTP verb for the probe (`POST` sends `{}`) |
36
- | `--format` | `markdown` | `json` for CI / machine-readable reports |
37
- | `--json` | — | shorthand for `--format=json` |
38
-
39
- Exit codes: `0` PASS · `1` FAIL · `2` UNKNOWN (network/timeout) · `3` usage error.
40
-
41
- ## Real examples (captured 2026-09-29, against live endpoints)
42
-
43
- Inspecting an MCP endpoint that is free (no payment gate) — the tool reports
44
- the 200 instead of a 402, and still verifies the discovery manifests:
45
-
46
- ```json
47
- {
48
- "endpoint": "https://agenttoll-receipts.app.workbuddy.host/mcp",
49
- "method": "POST",
50
- "finalStatus": "FAIL",
51
- "http": { "status": 200, "elapsedMs": 2830, "bodyBytes": 82,
52
- "bodySha256": "598dc097dcca1e573c742100863899c00724a021b421a5bb49952d49fec6b4f4" },
53
- "findings": [
54
- { "status": "FAIL", "code": "NO_402", "message": "Expected HTTP 402, received 200" }
55
- ],
56
- "metadata": [
57
- { "path": "/.well-known/mcp/server.json", "status": 200, "reachable": true }
58
- ]
59
- }
60
- ```
61
-
62
- Inspecting the official x402 demo endpoint — it does return 402, but ships a
63
- payment document mcpdoctor cannot parse, which is exactly the class of silent
64
- breakage this CLI exists to catch:
65
-
66
- ```json
67
- {
68
- "endpoint": "https://x402.org/protected",
69
- "finalStatus": "FAIL",
70
- "http": { "status": 402 },
71
- "headers": { "paymentRequired": true },
72
- "findings": [
73
- { "status": "FAIL", "code": "NO_ACCEPTS",
74
- "message": "No recognizable payment requirement found" }
75
- ]
76
- }
77
- ```
78
-
79
- ## What it does NOT do
80
-
81
- - No MCP protocol session: no `initialize`, no `tools/list` — mcpdoctor
82
- checks what an endpoint *advertises* (402 documents, discovery manifests),
83
- not a full MCP handshake.
84
- - No wallet, signing, settlement, or retries. Read-only preflight only.
85
- - `PASS` means the observed 402 document had recognizable, complete fields —
86
- it is not a security or payment-success certification.
87
-
88
- ## Why
89
-
90
- We ship an x402 service ourselves ([ReceiptRail](https://github.com/xka0085-byte/agenttoll))
91
- and hit every way a paid endpoint can silently break:
92
-
93
- - an endpoint that validates the request body **before** returning the 402
94
- challenge is invisible to every x402 client — they only react to `402`;
95
- - payment documents arrive in **four different places** and **two different
96
- shapes**; parsers that only look at one place report false failures;
97
- - vendor hint headers without `accepts[]` can shadow the real payment document.
98
-
99
- Each check in mcpdoctor maps to a failure mode we actually hit in production.
100
-
101
- ## Part of the Agent / Chain Evidence Tools suite
102
-
103
- Read-only diagnostics for AI agents on Web3 —
104
- [hub & docs](https://xka0085-byte.github.io/evidence-tools/) ·
105
- [ReceiptRail (live MCP service)](https://github.com/xka0085-byte/agenttoll) ·
106
- [npm: @eidonze/mcpdoctor](https://www.npmjs.com/package/@eidonze/mcpdoctor)
107
-
108
- 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
+ ## 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.
package/bin/mcpdoctor.mjs CHANGED
@@ -1,155 +1,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.2';
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.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
+ }
package/package.json CHANGED
@@ -1,17 +1,17 @@
1
- {
2
- "name": "@eidonze/mcpdoctor",
3
- "version": "0.1.2",
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.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
+ }