@eidonze/mcpdoctor 0.1.3 → 0.1.5

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,100 @@
1
1
  # mcpdoctor
2
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`.
3
+ Read-only checks for MCP tool schemas and x402 payment endpoints. Use it before an agent client or buyer depends on an endpoint.
4
4
 
5
- **mcpdoctor is a read-only CLI for inspecting MCP and x402 endpoints.**
5
+ [![npm](https://img.shields.io/npm/v/@eidonze/mcpdoctor?logo=npm)](https://www.npmjs.com/package/@eidonze/mcpdoctor)
6
+ [![CI](https://github.com/xka0085-byte/mcp-doctor/actions/workflows/ci.yml/badge.svg)](https://github.com/xka0085-byte/mcp-doctor/actions/workflows/ci.yml)
7
+ [![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
6
8
 
7
- Point it at a URL, get one `PASS / FAIL / UNKNOWN` report:
9
+ ## Find the right guide
8
10
 
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.
11
+ - [Public documentation site](https://xka0085-byte.github.io/mcp-doctor/)
12
+ - [MCP schema checker](docs/mcp-schema-checker.md)
13
+ - [x402 endpoint inspector](docs/x402-endpoint-inspector.md)
14
+ - [MCP security CI](docs/mcp-security-ci.md)
15
+ - [Troubleshooting](docs/troubleshooting.md)
16
+ - [OAuth scope and current limits](docs/mcp-oauth-diagnostics.md)
16
17
 
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.
18
+ ## Run it now
21
19
 
22
- ## Install
20
+ Check an MCP server without calling any tools:
23
21
 
24
22
  ```bash
25
- npm install -g @eidonze/mcpdoctor # or run without installing:
26
- npx @eidonze/mcpdoctor inspect <url>
23
+ npx @eidonze/mcpdoctor@0.1.5 schema https://your-mcp-server.example/mcp --json
27
24
  ```
28
25
 
29
- ## Usage
26
+ Check an x402 endpoint without paying:
30
27
 
31
28
  ```bash
32
- mcpdoctor inspect <url> [--method=GET|POST] [--format=json|markdown]
29
+ npx @eidonze/mcpdoctor@0.1.5 inspect https://your-api.example/paid --method=POST --json
33
30
  ```
34
31
 
35
- | Option | Default | Description |
32
+ Requires Node.js 18+. No API key or wallet is needed.
33
+
34
+ ## Which command?
35
+
36
+ | Command | Checks | Does not do |
36
37
  |---|---|---|
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
- }
38
+ | `schema` | MCP `initialize`, `tools/list`, tool names, descriptions, and JSON schemas | Does not call tools or prove runtime behavior |
39
+ | `inspect` | HTTP 402, x402 v1/v2 payment document, `accepts[]`, discovery manifests, latency and response digest | Does not sign, pay, settle, retry, or verify delivery |
40
+
41
+ Exit codes are stable for automation: `0` PASS, `1` FAIL, `2` UNKNOWN/network error, `3` usage error.
42
+
43
+ ## GitHub Actions
44
+
45
+ Add a read-only check to pull requests:
46
+
47
+ ```yaml
48
+ name: MCP Trust Check
49
+ on: [pull_request]
50
+
51
+ jobs:
52
+ mcp-trust:
53
+ runs-on: ubuntu-latest
54
+ steps:
55
+ - uses: xka0085-byte/mcp-doctor@v1
56
+ with:
57
+ endpoint: https://your-mcp-server.example/mcp
58
+ mode: schema
59
+ format: markdown
62
60
  ```
63
61
 
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
- }
62
+ Use `mode: inspect` for an x402 preflight. The action fails on `FAIL` or `UNKNOWN` by default; set `fail-on: false` for an informational check.
63
+
64
+ ## Starter template
65
+
66
+ Start a new MCP project with this check already wired in:
67
+
68
+ - [Secure MCP Server Starter](examples/secure-mcp-server-starter/)
69
+
70
+ The check is read-only and should target a public test endpoint. Do not place private keys or credentials in workflow inputs.
71
+
72
+ ## What the report means
73
+
74
+ `PASS` means the observed response matched the checks in this version. It is not a security audit, protocol certification, payment-success guarantee, or proof that an endpoint is safe. `UNKNOWN` means the endpoint could not be observed within the timeout or response-size limits.
75
+
76
+ Example schema failure:
77
+
78
+ ```text
79
+ FAIL REQUIRED_PROPERTY_UNDEFINED tools[0] requires undeclared property query
79
80
  ```
80
81
 
81
- ## What it does NOT do
82
+ Example x402 failure:
82
83
 
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.
84
+ ```text
85
+ FAIL NO_402 Expected HTTP 402, received 400
86
+ ```
89
87
 
90
- ## Why
88
+ ## Why it exists
91
89
 
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:
90
+ The checks come from failure modes observed while building ReceiptRail: body validation that prevents an x402 challenge, payment documents in multiple headers/body shapes, and vendor hint headers that can hide the real `accepts[]` document.
94
91
 
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.
92
+ mcpdoctor is not an MCP server. It is an independent, read-only endpoint inspector. It is not affiliated with mcpdoctor.dev; verify the npm scope is `@eidonze/mcpdoctor`.
100
93
 
101
- Each check in mcpdoctor maps to a failure mode we actually hit in production.
94
+ ## Feedback
102
95
 
103
- ## Part of the Agent / Chain Evidence Tools suite
96
+ Found a false positive or a protocol shape we should support? [Open an issue](https://github.com/xka0085-byte/mcp-doctor/issues). Include the command, redacted output, Node version, and whether the endpoint is MCP or x402. Never include tokens, payment signatures, or private URLs.
104
97
 
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)
98
+ ## License
109
99
 
110
- MIT licensed. Known limitations are documented, not hidden.
100
+ MIT
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.5",
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-security", "mcp-scanner", "mcp-schema", "mcp-oauth", "agent-security", "tool-schema", "x402-inspector", "http-402", "mcp-cli", "mcp-debugging", "developer-tools", "diagnostics", "x402", "cli"],
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 }));