@eidonze/mcpdoctor 0.1.1

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/README.md ADDED
@@ -0,0 +1,81 @@
1
+ # mcpdoctor
2
+
3
+ Read-only preflight checks for **x402 payment endpoints** and **MCP servers**.
4
+ One command tells you whether your paid endpoint answers the way agent clients
5
+ actually expect — before a real buyer (human or AI) hits it.
6
+
7
+ Zero dependencies. Runs anywhere Node ≥ 18 runs. Never touches your keys.
8
+
9
+ ```bash
10
+ npx @eidonze/mcpdoctor inspect https://your-endpoint/v1/paid --method=POST
11
+ ```
12
+
13
+ ## Why
14
+
15
+ Shipping an x402 service ourselves ([ReceiptRail](https://github.com/xka0085-byte/agenttoll)),
16
+ we hit every way a paid endpoint can silently break:
17
+
18
+ - an endpoint that validates the request body **before** returning the 402
19
+ challenge is invisible to every x402 client — they only react to `402`;
20
+ - payment documents arrive in **four different places** (`Payment-Required` /
21
+ `X-Payment-Required` / `WWW-Authenticate` headers, or the response body) and
22
+ in **two different shapes** (v1 top-level `accepts[]`, v2 nested `x402.accepts`);
23
+ parsers that only look at one place report false failures;
24
+ - vendor hint headers without `accepts[]` can shadow the real payment document.
25
+
26
+ Each check in mcpdoctor maps to a failure mode we actually hit in production.
27
+
28
+ ## Usage
29
+
30
+ ```bash
31
+ mcpdoctor inspect <url> [--method=GET|POST] [--format=json|markdown]
32
+ ```
33
+
34
+ | Option | Default | Description |
35
+ |---|---|---|
36
+ | `--method` | `GET` | HTTP verb for the probe (`POST` sends `{}`) |
37
+ | `--format` | `markdown` | `json` for CI / machine-readable reports |
38
+
39
+ The report includes the observed HTTP status, the parsed payment requirements
40
+ (`accepts[]` with scheme / network / asset / amount / payTo / timeout), response
41
+ latency, size, a SHA-256 digest of the response bytes (tamper-evident record),
42
+ and reachability of `/.well-known/mcp/server.json` and `/.well-known/x402`.
43
+
44
+ ## Exit codes
45
+
46
+ | Code | Meaning |
47
+ |---|---|
48
+ | `0` | PASS — parseable 402 payment document with required fields |
49
+ | `1` | FAIL — endpoint responded but is not 402 / document incomplete |
50
+ | `2` | UNKNOWN — endpoint could not be observed within limits |
51
+ | `3` | invalid command |
52
+
53
+ ## Verified, not vibes
54
+
55
+ - **Positive control**: passes against a production x402 service that itself
56
+ survived x402scan's auditor (ReceiptRail, dual-network settlement).
57
+ - **Negative control**: the test suite spins up a server that returns `400`
58
+ instead of `402` — the exact production bug that inspired this tool — and
59
+ asserts mcpdoctor flags it (`NO_402`), plus a header-hint-shadowing case.
60
+
61
+ ```bash
62
+ npm test
63
+ ```
64
+
65
+ ## Safety boundary
66
+
67
+ Read-only. mcpdoctor never signs, pays, retries payment, calls a facilitator,
68
+ or accepts a private key. A `PASS` is not a security audit, payment-success
69
+ certificate, or compliance decision — it means the observed 402 document had
70
+ recognizable, well-formed fields.
71
+
72
+ ## Roadmap
73
+
74
+ - `extensions.bazaar` schema conformance (x402 Bazaar discovery listings)
75
+ - `x-payment-info.protocols` object-array check
76
+ - MCP streamable-HTTP `initialize` handshake check
77
+ - `/.well-known/mcp/server-card.json` (Smithery SEP-1649) validation
78
+
79
+ ## License
80
+
81
+ MIT
@@ -0,0 +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.0';
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 ADDED
@@ -0,0 +1,15 @@
1
+ {
2
+ "name": "@eidonze/mcpdoctor",
3
+ "version": "0.1.1",
4
+ "description": "Read-only MCP and x402 endpoint preflight checks: 402 challenge shape, payment document parsing, accepts[] conformance, discovery manifests, response digest. Zero dependencies.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "bin": { "mcpdoctor": "bin/mcpdoctor.mjs" },
8
+ "main": "bin/mcpdoctor.mjs",
9
+ "engines": { "node": ">=18" },
10
+ "scripts": { "test": "node test/smoke.mjs" },
11
+ "keywords": ["mcp", "x402", "model-context-protocol", "developer-tools", "diagnostics", "web3", "solana", "usdc", "agent-payments", "linter"],
12
+ "repository": { "type": "git", "url": "git+https://github.com/xka0085-byte/mcp-doctor.git" },
13
+ "bugs": { "url": "https://github.com/xka0085-byte/mcp-doctor/issues" },
14
+ "homepage": "https://github.com/xka0085-byte/mcp-doctor#readme"
15
+ }
package/test/smoke.mjs ADDED
@@ -0,0 +1,73 @@
1
+ #!/usr/bin/env node
2
+ import assert from 'node:assert/strict';
3
+ import { createServer } from 'node:http';
4
+ import { spawn } from 'node:child_process';
5
+ import { once } from 'node:events';
6
+ import { fileURLToPath } from 'node:url';
7
+ import path from 'node:path';
8
+
9
+ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
10
+ const cli = path.join(root, 'bin', 'mcpdoctor.mjs');
11
+ const server = createServer((request, response) => {
12
+ if (request.url === '/good') {
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
+ response.end(JSON.stringify({ x402Version: 2, accepts: [{ scheme: 'exact', network: 'eip155:8453', asset: 'USDC', amount: '10000', payTo: '0x1234567890123456789012345678901234567890' }] }));
15
+ return;
16
+ }
17
+ // regression (found against production ReceiptRail): a hint header WITHOUT accepts[]
18
+ // must not shadow the real payment document in the body
19
+ if (request.url === '/header-hint') {
20
+ response.writeHead(402, { 'content-type': 'application/json', 'x-payment-required': JSON.stringify({ vendor: 'VendorHintNoAccepts', amount: '1000', decimals: 6 }) });
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
+ return;
23
+ }
24
+ // regression (our original production bug): body validation must not shadow the 402
25
+ if (request.url === '/bad-400') {
26
+ response.writeHead(400, { 'content-type': 'application/json' });
27
+ response.end(JSON.stringify({ error: 'missing body param' }));
28
+ return;
29
+ }
30
+ response.writeHead(404, { 'content-type': 'application/json' });
31
+ response.end(JSON.stringify({ error: 'not found' }));
32
+ });
33
+ server.listen(0, '127.0.0.1');
34
+ await once(server, 'listening');
35
+ const port = server.address().port;
36
+
37
+ function run(url, ...args) {
38
+ return new Promise((resolve) => {
39
+ const child = spawn(process.execPath, [cli, 'inspect', url, '--format=json', ...args], { stdio: ['ignore', 'pipe', 'pipe'] });
40
+ let stdout = ''; let stderr = '';
41
+ child.stdout.on('data', (chunk) => { stdout += chunk; });
42
+ child.stderr.on('data', (chunk) => { stderr += chunk; });
43
+ child.on('close', (code) => resolve({ code, stdout, stderr }));
44
+ });
45
+ }
46
+
47
+ try {
48
+ const good = await run(`http://127.0.0.1:${port}/good`);
49
+ assert.equal(good.code, 0, good.stderr);
50
+ assert.equal(JSON.parse(good.stdout).finalStatus, 'PASS');
51
+ const bad = await run(`http://127.0.0.1:${port}/missing`);
52
+ assert.equal(bad.code, 1, bad.stderr);
53
+ assert.equal(JSON.parse(bad.stdout).finalStatus, 'FAIL');
54
+ const hint = await run(`http://127.0.0.1:${port}/header-hint`, '--method=POST');
55
+ assert.equal(hint.code, 0, hint.stderr);
56
+ const hintReport = JSON.parse(hint.stdout);
57
+ assert.equal(hintReport.finalStatus, 'PASS', JSON.stringify(hintReport.findings));
58
+ assert.equal(hintReport.x402.accepts.length, 1, 'body accepts[] must win over accept-less header hints');
59
+ const bad400 = await run(`http://127.0.0.1:${port}/bad-400`, '--method=POST');
60
+ assert.equal(bad400.code, 1, bad400.stderr);
61
+ const bad400Report = JSON.parse(bad400.stdout);
62
+ assert.equal(bad400Report.finalStatus, 'FAIL');
63
+ assert.ok(bad400Report.findings.some((f) => f.code === 'NO_402'), 'must flag 400-instead-of-402');
64
+ const help = await new Promise((resolve) => {
65
+ const child = spawn(process.execPath, [cli, '--help'], { stdio: ['ignore', 'pipe', 'pipe'] });
66
+ let stdout = ''; child.stdout.on('data', (chunk) => { stdout += chunk; }); child.on('close', (code) => resolve({ code, stdout }));
67
+ });
68
+ assert.equal(help.code, 0);
69
+ assert.match(help.stdout, /mcpdoctor/);
70
+ console.log('mcpdoctor smoke tests passed');
71
+ } finally {
72
+ server.close();
73
+ }