-
-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathmcp.test.js
More file actions
701 lines (607 loc) · 24.4 KB
/
Copy pathmcp.test.js
File metadata and controls
701 lines (607 loc) · 24.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { Readable } from 'node:stream';
// ── Env vars (must be set before any lazy env.* access) ──────────────────
process.env.PUBLIC_APP_ORIGIN ||= 'https://app.test';
process.env.JWT_SECRET ||= 'test-secret-mcp';
process.env.UPSTASH_REDIS_REST_URL ||= 'https://redis.test';
process.env.UPSTASH_REDIS_REST_TOKEN ||= 'redis-token';
// ── Auth ──────────────────────────────────────────────────────────────────
const authState = { extracted: null, bearer: null };
vi.mock('../../api/_lib/auth.js', () => ({
extractBearer: vi.fn(() => authState.extracted),
authenticateBearer: vi.fn(async () => authState.bearer),
hasScope: vi.fn((granted, required) => {
const g = new Set((granted || '').split(/\s+/).filter(Boolean));
return required.split(/\s+/).every((s) => g.has(s));
}),
}));
// ── DB ────────────────────────────────────────────────────────────────────
const sqlState = { queue: [], calls: [] };
vi.mock('../../api/_lib/db.js', () => ({
sql: vi.fn(async (strings, ...values) => {
sqlState.calls.push({ query: strings.join('?'), values });
return sqlState.queue.length ? sqlState.queue.shift() : [];
}),
}));
// ── Rate limits ───────────────────────────────────────────────────────────
const rlState = {
mcpIp: { success: true, reset: Date.now() + 60000 },
mcpUser: { success: true, reset: Date.now() + 60000 },
mcpValidate: { success: true, reset: Date.now() + 60000 },
};
vi.mock('../../api/_lib/rate-limit.js', () => ({
limits: {
mcpIp: vi.fn(async () => rlState.mcpIp),
mcpUser: vi.fn(async () => rlState.mcpUser),
mcpValidate: vi.fn(async () => rlState.mcpValidate),
mcpInspect: vi.fn(async () => ({ success: true })),
mcpOptimize: vi.fn(async () => ({ success: true })),
},
clientIp: vi.fn(() => '203.0.113.1'),
}));
// ── Usage ─────────────────────────────────────────────────────────────────
vi.mock('../../api/_lib/usage.js', () => ({
recordEvent: vi.fn(),
logger: () => ({ info: () => {}, warn: () => {}, error: () => {} }),
}));
// ── x402 ─────────────────────────────────────────────────────────────────
class MockX402Error extends Error {
constructor(code, message, status = 402) {
super(message);
this.code = code;
this.status = status;
}
}
const x402State = { verifyOk: false, verifyResult: null };
vi.mock('../../api/_lib/x402-spec.js', () => ({
X402Error: MockX402Error,
X402_VERSION: 2,
paymentRequirements: vi.fn(() => [
{
scheme: 'exact',
network: 'eip155:8453',
payTo: '0xrecipient',
amount: '1000',
asset: '0xusdc',
maxTimeoutSeconds: 60,
},
]),
bazaarExtension: vi.fn(() => ({
method: 'POST',
bodyType: 'json',
input: {},
inputSchema: {},
output: { example: {} },
})),
verifyPayment: vi.fn(async () => {
if (!x402State.verifyOk)
throw new MockX402Error('invalid_payment', 'payment rejected', 402);
return x402State.verifyResult;
}),
settlePayment: vi.fn(async () => ({
success: true,
transaction: 'tx123',
network: 'eip155:8453',
payer: '0xpayer',
})),
encodePaymentResponseHeader: vi.fn(() => 'settlement-b64'),
send402: vi.fn((res, { resourceUrl, accepts, error } = {}) => {
res.statusCode = 402;
res.setHeader('content-type', 'application/json; charset=utf-8');
const list = Array.isArray(accepts) ? accepts : [accepts];
res.end(
JSON.stringify({
x402Version: 2,
error: error || 'X-PAYMENT header is required',
resource: { url: resourceUrl, description: 'MCP', mimeType: 'application/json' },
accepts: list,
extensions: { bazaar: { method: 'POST', bodyType: 'json' } },
}),
);
}),
build402Body: vi.fn(({ resourceUrl, accepts, error } = {}) => {
const list = Array.isArray(accepts) ? accepts : [accepts];
return {
x402Version: 2,
error: error || 'X-PAYMENT header is required',
resource: { url: resourceUrl, description: 'MCP', mimeType: 'application/json' },
accepts: list,
extensions: { bazaar: { method: 'POST', bodyType: 'json' } },
};
}),
resolveResourceUrl: vi.fn((req, path) => `https://app.test${path}`),
}));
// ── Pump pricing ──────────────────────────────────────────────────────────
const pricingState = { price: null };
vi.mock('../../api/_lib/pump-pricing.js', () => ({
priceFor: vi.fn(() => pricingState.price),
findActiveSubscription: vi.fn(async () => null),
resolveBillingMint: vi.fn(() => null),
// Per-tool x402 amount (atomic-unit string) derived from the advertised
// price. mcp.js peeks the called tool and passes this into the 402 challenge
// so advertised price == charged price. null = free tool (flat default).
x402AmountForTool: vi.fn(() =>
pricingState.price ? String(Math.round(pricingState.price.amount_usdc * 1e6)) : null,
),
}));
// ── Avatars ────────────────────────────────────────────────────────────────
const avatarState = {
avatar: null,
avatarUrl: { url: 'https://cdn.test/model.glb' },
searchResult: { avatars: [] },
};
vi.mock('../../api/_lib/avatars.js', () => ({
listAvatars: vi.fn(async () => ({ avatars: [] })),
getAvatar: vi.fn(async () => avatarState.avatar),
getAvatarBySlug: vi.fn(async () => avatarState.avatar),
searchPublicAvatars: vi.fn(async () => avatarState.searchResult),
resolveAvatarUrl: vi.fn(async () => avatarState.avatarUrl),
deleteAvatar: vi.fn(async () => true),
}));
// ── Model fetch ────────────────────────────────────────────────────────────
class MockFetchModelError extends Error {
constructor(message, code) {
super(message);
this.code = code;
}
}
const fetchModelState = { result: null, error: null };
vi.mock('../../api/_lib/fetch-model.js', () => ({
FetchModelError: MockFetchModelError,
fetchModel: vi.fn(async (url) => {
if (fetchModelState.error) throw fetchModelState.error;
return fetchModelState.result || { bytes: new Uint8Array(4), url, filename: 'model.glb' };
}),
}));
// ── gltf-validator ─────────────────────────────────────────────────────────
vi.mock('gltf-validator', () => ({
validateBytes: vi.fn(async () => ({
validatorVersion: '2.0.0',
mimeType: 'model/gltf-binary',
issues: {
numErrors: 0,
numWarnings: 0,
numInfos: 0,
numHints: 0,
truncated: false,
messages: [],
},
info: {},
})),
}));
// ── Solana attestations ────────────────────────────────────────────────────
vi.mock('../../api/_lib/solana-attestations.js', () => ({
crawlAgentAttestations: vi.fn(async () => {}),
KIND_MAP: {},
}));
// ── Pumpfun ────────────────────────────────────────────────────────────────
vi.mock('../../api/_lib/pumpfun-mcp.js', () => ({
pumpfunMcp: {
recentClaims: vi.fn(async () => ({ ok: true, data: [] })),
tokenIntel: vi.fn(async () => ({ ok: true, data: {} })),
creatorIntel: vi.fn(async () => ({ ok: true, data: {} })),
graduations: vi.fn(async () => ({ ok: true, data: [] })),
},
pumpfunBotEnabled: vi.fn(() => false),
}));
// ── Model inspection ────────────────────────────────────────────────────────
vi.mock('../../api/_lib/model-inspect.js', () => ({
inspectModel: vi.fn(async () => ({
counts: {
scenes: 1,
nodes: 5,
meshes: 2,
materials: 1,
textures: 0,
animations: 0,
skins: 0,
totalVertices: 100,
totalTriangles: 50,
indexedPrimitives: 2,
nonIndexedPrimitives: 0,
},
textures: [],
extensionsUsed: [],
container: 'glb',
generator: 'test',
version: '2.0',
fileSize: 1024,
})),
suggestOptimizations: vi.fn(() => []),
}));
// ── Infrastructure ──────────────────────────────────────────────────────────
vi.mock('../../api/_lib/zauth.js', () => ({ instrument: () => {} }));
vi.mock('../../api/_lib/sentry.js', () => ({ captureException: () => {} }));
// ── Import handler AFTER mocks ─────────────────────────────────────────────
const { default: handler } = await import('../../api/mcp.js');
// ── Test helpers ───────────────────────────────────────────────────────────
function makeReq({
method = 'POST',
url = '/api/mcp',
headers = {},
body = null,
rawBody = null,
} = {}) {
let base;
if (rawBody !== null) {
base = Readable.from([rawBody]);
} else if (body !== null) {
base = Readable.from([Buffer.from(JSON.stringify(body))]);
} else {
base = Readable.from([]);
}
base.method = method;
base.url = url;
base.headers = {
host: 'app.test',
...(body !== null || rawBody !== null ? { 'content-type': 'application/json' } : {}),
...headers,
};
return base;
}
function makeRes() {
return {
statusCode: 200,
headers: {},
body: '',
writableEnded: false,
setHeader(k, v) {
this.headers[k.toLowerCase()] = v;
},
getHeader(k) {
return this.headers[k.toLowerCase()];
},
end(chunk) {
if (chunk !== undefined) this.body += String(chunk);
this.writableEnded = true;
},
};
}
async function invoke(reqOpts = {}) {
const req = makeReq(reqOpts);
const res = makeRes();
await handler(req, res);
const parsed = res.body ? safeJson(res.body) : null;
return { res, status: res.statusCode, body: parsed };
}
function safeJson(s) {
try {
return JSON.parse(s);
} catch {
return s;
}
}
// Shorthand for a JSON-RPC POST body with valid auth headers.
function rpc(method, params, extraHeaders = {}) {
return {
body: { jsonrpc: '2.0', id: 1, method, params },
headers: { authorization: 'Bearer valid-token', ...extraHeaders },
};
}
const FULL_AUTH = {
userId: 'user-1',
scope: 'avatars:read avatars:write avatars:delete',
source: 'oauth',
};
// ── Reset between tests ───────────────────────────────────────────────────
beforeEach(() => {
authState.extracted = null;
authState.bearer = null;
sqlState.queue = [];
sqlState.calls = [];
rlState.mcpIp = { success: true, reset: Date.now() + 60000 };
rlState.mcpUser = { success: true, reset: Date.now() + 60000 };
rlState.mcpValidate = { success: true, reset: Date.now() + 60000 };
avatarState.avatar = null;
avatarState.searchResult = { avatars: [] };
fetchModelState.result = null;
fetchModelState.error = null;
pricingState.price = null;
x402State.verifyOk = false;
x402State.verifyResult = null;
});
// ── Protocol layer ────────────────────────────────────────────────────────
describe('Protocol layer', () => {
it('initialize returns protocol version, server info, and capabilities', async () => {
authState.extracted = 'valid-token';
authState.bearer = FULL_AUTH;
const { status, body } = await invoke(rpc('initialize', { protocolVersion: '2025-06-18' }));
expect(status).toBe(200);
expect(body.jsonrpc).toBe('2.0');
expect(body.result.protocolVersion).toBe('2025-06-18');
expect(body.result.serverInfo.name).toBe('3d-agent-mcp');
expect(body.result.capabilities.tools).toBeDefined();
});
it('tools/list returns the full tool catalog', async () => {
authState.extracted = 'valid-token';
authState.bearer = FULL_AUTH;
const { status, body } = await invoke(rpc('tools/list', {}));
expect(status).toBe(200);
const names = body.result.tools.map((t) => t.name);
expect(names).toContain('getting_started');
expect(names).toContain('search_public_avatars');
expect(names).toContain('validate_model');
expect(names).toContain('render_avatar');
expect(names).toContain('list_my_avatars');
});
it('tools/list with no jsonrpc field still succeeds (minimal-client tolerance)', async () => {
authState.extracted = 'valid-token';
authState.bearer = FULL_AUTH;
// Minimal/legacy MCP clients omit the `jsonrpc: "2.0"` envelope on
// discovery calls. Rejecting those with -32600 broke interop; an absent
// version must be tolerated (auth/pricing still gate the call).
const { status, body } = await invoke({
body: { id: 1, method: 'tools/list', params: {} },
headers: { authorization: 'Bearer valid-token' },
});
expect(status).toBe(200);
expect(body.result.tools.length).toBeGreaterThan(0);
});
it('a present-but-wrong jsonrpc version is still rejected with -32600', async () => {
authState.extracted = 'valid-token';
authState.bearer = FULL_AUTH;
const { status, body } = await invoke({
body: { jsonrpc: '1.0', id: 1, method: 'tools/list', params: {} },
headers: { authorization: 'Bearer valid-token' },
});
expect(status).toBe(200);
expect(body.error.code).toBe(-32600);
});
it('unknown method returns JSON-RPC -32601 error', async () => {
authState.extracted = 'valid-token';
authState.bearer = FULL_AUTH;
const { status, body } = await invoke(rpc('totally/unknown', {}));
expect(status).toBe(200);
expect(body.error.code).toBe(-32601);
});
it('malformed JSON body returns HTTP 400', async () => {
authState.extracted = 'valid-token';
authState.bearer = FULL_AUTH;
const { status } = await invoke({
rawBody: Buffer.from('{ not valid json !!'),
headers: { authorization: 'Bearer valid-token' },
});
expect(status).toBe(400);
});
it('DELETE returns 204 (stateless session termination)', async () => {
const { status } = await invoke({ method: 'DELETE' });
expect(status).toBe(204);
});
it('GET without bearer returns 401 + WWW-Authenticate (OAuth discovery) with x402 envelope attached', async () => {
// MCP protocol clients (mcp-protocol-version header) get 401 per the MCP
// authorization spec; bare x402 agents get 402 (covered in Authentication).
const { status, body, res } = await invoke({
method: 'GET',
headers: { 'mcp-protocol-version': '2025-03-26' },
});
expect(status).toBe(401);
expect(res.headers['www-authenticate']).toMatch(/resource_metadata=/);
// x402 price discovery still rides along in the body + PAYMENT-REQUIRED header.
expect(body.x402Version).toBe(2);
expect(Array.isArray(body.accepts)).toBe(true);
expect(res.headers['payment-required']).toBeTruthy();
});
it('GET with valid bearer returns 405 (SSE not yet implemented)', async () => {
authState.extracted = 'valid-token';
authState.bearer = FULL_AUTH;
const { status, res } = await invoke({
method: 'GET',
headers: { authorization: 'Bearer valid-token' },
});
expect(status).toBe(405);
expect(res.headers['allow']).toMatch(/POST/);
});
});
// ── Authentication ────────────────────────────────────────────────────────
describe('Authentication', () => {
it('POST with no bearer and no X-PAYMENT returns 401 (OAuth challenge) for MCP protocol clients', async () => {
// no bearer, no payment, MCP protocol header → sendAuthChallenge → 401 + WWW-Authenticate
const { status, body, res } = await invoke({
headers: { 'mcp-protocol-version': '2025-03-26' },
body: {
jsonrpc: '2.0',
id: 1,
method: 'tools/call',
params: { name: 'search_public_avatars' },
},
});
expect(status).toBe(401);
expect(res.headers['www-authenticate']).toMatch(/resource_metadata=/);
expect(body.x402Version).toBe(2);
});
it('POST with no bearer, no X-PAYMENT, and no MCP headers returns 402 (x402 agent challenge)', async () => {
// Bare x402 agents/crawlers (no MCP protocol headers) key on a proper
// 402 Payment Required carrying the same envelope.
const { status, body, res } = await invoke({
body: {
jsonrpc: '2.0',
id: 1,
method: 'tools/call',
params: { name: 'search_public_avatars' },
},
});
expect(status).toBe(402);
expect(body.x402Version).toBe(2);
expect(res.headers['payment-required']).toBeTruthy();
});
it('POST getting_started with no bearer and no X-PAYMENT succeeds (free public tool)', async () => {
// no bearer, no payment → allowFree bypass → 200 with the server overview,
// while a scoped tool on the same path still 401s (test above).
const { status, body } = await invoke({
body: {
jsonrpc: '2.0',
id: 1,
method: 'tools/call',
params: { name: 'getting_started', arguments: {} },
},
});
expect(status).toBe(200);
expect(body.result.structuredContent.server).toBe('three.ws');
expect(body.result.structuredContent.tools.length).toBeGreaterThan(0);
expect(body.result.content[0].text).toContain('Getting Started');
});
it('POST with a bearer that fails authentication returns 401', async () => {
authState.extracted = 'bad-token';
authState.bearer = null; // authenticateBearer returns null → invalid token
const { status, body } = await invoke({
body: {
jsonrpc: '2.0',
id: 1,
method: 'tools/call',
params: { name: 'search_public_avatars' },
},
headers: { authorization: 'Bearer bad-token' },
});
expect(status).toBe(401);
expect(body.error).toBe('unauthorized');
expect((res) => res).toBeDefined(); // www-authenticate header is set
});
it('POST with valid bearer succeeds for a scope-free tool', async () => {
authState.extracted = 'valid-token';
authState.bearer = { userId: 'user-1', scope: '', source: 'oauth' };
avatarState.searchResult = { avatars: [] };
const { status, body } = await invoke(rpc('tools/call', { name: 'search_public_avatars' }));
expect(status).toBe(200);
expect(body.result.content[0].type).toBe('text');
});
it('list_my_avatars without avatars:read scope returns -32002', async () => {
authState.extracted = 'valid-token';
authState.bearer = { userId: 'user-1', scope: '', source: 'oauth' }; // no scope
const { status, body } = await invoke(rpc('tools/call', { name: 'list_my_avatars' }));
expect(status).toBe(200);
expect(body.error.code).toBe(-32002);
expect(body.error.message).toMatch(/avatars:read/);
});
});
// ── Tool: search_public_avatars ───────────────────────────────────────────
describe('Tool: search_public_avatars', () => {
beforeEach(() => {
authState.extracted = 'valid-token';
authState.bearer = FULL_AUTH;
});
it('returns a list of avatars when the DB has results', async () => {
avatarState.searchResult = {
avatars: [
{ id: 'a1', name: 'Warrior', slug: 'warrior', model_url: 'https://cdn.test/w.glb' },
{ id: 'a2', name: 'Mage', slug: 'mage', model_url: 'https://cdn.test/m.glb' },
],
};
const { body } = await invoke(
rpc('tools/call', { name: 'search_public_avatars', arguments: { q: 'warrior' } }),
);
expect(body.result.content[0].text).toContain('Warrior');
expect(body.result.structuredContent.avatars).toHaveLength(2);
});
it('returns "No avatars found." text when results are empty', async () => {
avatarState.searchResult = { avatars: [] };
const { body } = await invoke(
rpc('tools/call', { name: 'search_public_avatars', arguments: {} }),
);
expect(body.result.content[0].text).toBe('No avatars found.');
});
});
// ── Tool: validate_model ──────────────────────────────────────────────────
describe('Tool: validate_model', () => {
beforeEach(() => {
authState.extracted = 'valid-token';
authState.bearer = FULL_AUTH;
});
it('returns structured validation report for a valid model URL', async () => {
const { body } = await invoke(
rpc('tools/call', {
name: 'validate_model',
arguments: { url: 'https://cdn.test/model.glb' },
}),
);
expect(body.result).toBeDefined();
expect(body.error).toBeUndefined();
expect(body.result.content[0].text).toContain('Errors: 0');
expect(body.result.structuredContent.numErrors).toBe(0);
});
it('returns isError result when the model fetch fails (e.g. SSRF / blocked URL)', async () => {
fetchModelState.error = new MockFetchModelError('private IP blocked', 'SSRF');
const { body } = await invoke(
rpc('tools/call', {
name: 'validate_model',
arguments: { url: 'https://cdn.test/blocked.glb' },
}),
);
expect(body.result.isError).toBe(true);
expect(body.result.content[0].text).toContain('fetch failed');
expect(body.result.content[0].text).toContain('SSRF');
});
});
// ── Tool: render_avatar ───────────────────────────────────────────────────
describe('Tool: render_avatar', () => {
it('returns an HTML snippet containing <model-viewer>', async () => {
authState.extracted = 'valid-token';
authState.bearer = FULL_AUTH;
// render_avatar's inputSchema requires id to match uuid format — real
// avatar ids are uuids, so the fixture must be one too.
const avatarId = '11111111-1111-4111-8111-111111111111';
avatarState.avatar = {
id: avatarId,
name: 'Test Avatar',
slug: 'test',
visibility: 'public',
owner_id: 'user-1',
};
// sql returns [] by default → _readMcpPolicyByAvatar returns null (no restriction)
const { body } = await invoke(
rpc('tools/call', { name: 'render_avatar', arguments: { id: avatarId } }),
);
expect(body.result).toBeDefined();
expect(body.error).toBeUndefined();
const resource = body.result.content.find((c) => c.type === 'resource');
expect(resource).toBeDefined();
expect(resource.resource.mimeType).toBe('text/html');
expect(resource.resource.text).toContain('<model-viewer');
expect(resource.resource.text).toContain('https://cdn.test/model.glb');
});
});
// ── x402 payment flow ─────────────────────────────────────────────────────
describe('x402 payment flow', () => {
it('request with no auth and no X-PAYMENT returns 401 carrying the x402 payment body', async () => {
const { status, body } = await invoke({
headers: { 'mcp-protocol-version': '2025-03-26' },
body: {
jsonrpc: '2.0',
id: 1,
method: 'tools/call',
params: { name: 'search_public_avatars' },
},
});
expect(status).toBe(401);
expect(body.x402Version).toBe(2);
expect(body.resource.url).toMatch(/\/api\/mcp$/);
expect(body.resource.mimeType).toBe('application/json');
expect(body.accepts[0].network).toBe('eip155:8453');
expect(body.accepts[0].amount).toBe('1000');
expect(body.extensions.bazaar).toBeDefined();
});
it('valid X-PAYMENT header passes payment verification and executes the tool', async () => {
// No bearer — will enter x402 path
authState.extracted = null;
x402State.verifyOk = true;
x402State.verifyResult = {
paymentPayload: { network: 'base' },
requirement: { network: 'base' },
payer: '0xpayer',
};
avatarState.searchResult = { avatars: [] };
const { status, body, res } = await invoke({
body: {
jsonrpc: '2.0',
id: 1,
method: 'tools/call',
params: { name: 'search_public_avatars', arguments: {} },
},
headers: {
'x-payment': Buffer.from(JSON.stringify({ network: 'base' })).toString('base64'),
},
});
expect(status).toBe(200);
expect(body.result.content[0].type).toBe('text');
expect(res.headers['x-payment-response']).toBe('settlement-b64');
});
});