Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 13 additions & 7 deletions src/lib/x402/fetch-middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ async function getOrSignPayment(
paymentCache: X402PaymentCache,
schemePreference?: SchemePreference
): Promise<string | undefined> {
if (!getToolByName || !init?.body) {
if (!init?.body) {
return undefined;
}

Expand All @@ -189,6 +189,18 @@ async function getOrSignPayment(
return undefined;
}

// The bridge can populate this cache after receiving a payment-required
// CallToolResult. That retry must not depend on proactive tools/list metadata:
// challenge-first servers may omit _meta.x402 entirely.
if (paymentCache.signature) {
logger.debug(`Using cached payment signature for tool "${toolName}"`);
return paymentCache.signature;
}

if (!getToolByName) {
return undefined;
}

// Look up tool metadata
const tool = getToolByName(toolName);
if (!tool) {
Expand All @@ -203,12 +215,6 @@ async function getOrSignPayment(
return undefined;
}

// Return cached signature if available
if (paymentCache.signature) {
logger.debug(`Using cached payment signature for tool "${toolName}"`);
return paymentCache.signature;
}

const accept = selectAcceptFromToolMeta(x402, schemePreference);
if (!accept) {
logger.debug(
Expand Down
25 changes: 25 additions & 0 deletions test/unit/lib/x402/fetch-middleware.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,31 @@ beforeEach(() => {
// ---------------------------------------------------------------------------

describe('createX402FetchMiddleware proactive sign', () => {
it('reuses a challenge-signed cache entry when the tool has no proactive x402 metadata', async () => {
const cachedPayload = {
x402Version: 2,
payload: { signature: '0xsig', authorization: { from: WALLET.address } },
};
const cachedSignature = Buffer.from(JSON.stringify(cachedPayload)).toString('base64');
const cache: X402PaymentCache = { signature: cachedSignature };
const baseFetch = vi.fn().mockResolvedValue(new Response('', { status: 200 }));
const fetchFn = createX402FetchMiddleware(baseFetch as never, {
wallet: WALLET,
getToolByName: () => undefined,
paymentCache: cache,
schemePreference: 'exact',
});

await fetchFn('https://example.test/mcp', { method: 'POST', body: toolsCallBody('paid-tool') });

expect(mockSignPayment).not.toHaveBeenCalled();
expect(baseFetch).toHaveBeenCalledTimes(1);
const init = baseFetch.mock.calls[0]?.[1] as RequestInit;
expect(new Headers(init.headers).get('PAYMENT-SIGNATURE')).toBe(cachedSignature);
const body = JSON.parse(String(init.body));
expect(body.params._meta['x402/payment']).toEqual(cachedPayload);
});

it('with schemePreference=exact and accepts=[exact, upto], signs exact', async () => {
const tool = makePaidTool({ accepts: [EXACT_ACCEPT, UPTO_ACCEPT], ...UPTO_ACCEPT });
const cache: X402PaymentCache = { signature: null };
Expand Down
Loading