import { X402 } from '@x402/core';
import { createEvmClient } from '@x402/evm';
// Initialize x402 client
const x402 = createEvmClient({
privateKey: process.env.EVM_PRIVATE_KEY,
chainId: 8453 // Base mainnet
});
// Make MCP call
async function callMcpTool(toolName: string, args: any) {
// First attempt - will require payment
const response = await fetch(`${API_URL}/mcp`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
method: 'tools/call',
params: {
name: toolName,
arguments: args
},
id: 1
})
});
const result = await response.json();
// Check if payment required
if (result.error?.code === -32402) {
const { taskId, paymentRequired } = result.error.data;
// Sign payment
const signedPayment = await x402.createPaymentPayload(
paymentRequired
);
// Retry with payment
const paidResponse = await fetch(`${API_URL}/mcp`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
method: 'tools/call',
params: {
name: toolName,
arguments: args,
_meta: {
taskId,
x402Payment: signedPayment
}
},
id: 2
})
});
return paidResponse.json();
}
return result;
}
// Use the function
const result = await callMcpTool('pay_twitter', {
receiver: 'alice',
amount: 0.01,
description: 'Thanks for the help!'
});
console.log('Payment sent:', result.result);