mcp-cli icon indicating copy to clipboard operation
mcp-cli copied to clipboard

x402 HTTP receipt can attach to a different overlapping call to the same tool

Open epistemedeus opened this issue 3 weeks ago • 0 comments

In @apify/[email protected], two overlapping tools-call commands on the same named session can attach A’s PAYMENT-RESPONSE to B’s tool result. This is stronger than the documented drop-only limitation after #399: B can look reconciled against the wrong transaction even when the server gave B no receipt.

Repro: Use the same tool name with arguments A and B. Flush A’s HTTP 200 headers with receipt A, but hold A’s JSON-RPC body. Finish B without a receipt. Then finish A. Three Linux runs of the published CLI produced A = no receipt, B = receipt A. When B sent its own receipt, B was correct and A’s receipt disappeared. A serial positive control and a serial missing-header control both passed.

The capture/attach path uses a bridge-wide lastSettlement keyed only by tool name. I tested a small prototype that scopes the slot to the existing local tool-call operation with AsyncLocalStorage, leaving the signing/cache behavior and wire request unchanged. The same replay passed all three cases in three runs, including server-native _meta taking precedence over its header. This is not an upstream patch or a change to what the receipt proves on-chain. For the current release, serial calls or separate sessions avoid this overlap.

Credential-free CLI replay and prototype

In a fresh temporary directory with Node 22.23.2, run npm install --ignore-scripts --no-audit --no-fund @apify/[email protected]. Save the script as replay.mjs, then run node replay.mjs (red) and node replay.mjs --candidate (green). The signer returns an inert marker and the only server is loopback.

// Run in an isolated Linux directory with @apify/[email protected] installed.
// No credential store, wallet key, signature, facilitator, or public endpoint.
import assert from 'node:assert/strict';
import { execFile } from 'node:child_process';
import { createServer } from 'node:http';
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { setTimeout as delay } from 'node:timers/promises';
import { promisify } from 'node:util';

const exec = promisify(execFile);
const cli = join(process.cwd(), 'node_modules/@apify/mcpc/dist/cli/index.js');
const home = await mkdtemp(join(tmpdir(), 'mcpc-race-'));
const mock = join(home, 'mock.mjs');
const candidate = process.argv.includes('--candidate');
await writeFile(mock, `
  import { registerHooks } from 'node:module';
  registerHooks({
    load(url, context, next) {
      if (url.endsWith('/mcpc/dist/lib/wallets.js')) {
        return { format: 'module', shortCircuit: true, source: \`
          export const getWallet = async () => ({
            address: '0x0000000000000000000000000000000000000001',
            privateKey: 'not-a-key'
          });
          export const saveWallet = () => { throw Error('disabled'); };
          export const removeWallet = saveWallet;
        \` };
      }
      if (process.env.MCPC_RECEIPT_CANDIDATE === '1' &&
          url.endsWith('/mcpc/dist/lib/x402/fetch-middleware.js')) {
        const loaded = next(url, context);
        const source = Buffer.from(loaded.source).toString();
        const capture = 'function captureSettlementReceipt(cache, init, response) {';
        if (!source.includes(capture)) throw Error('capture seam changed');
        return { ...loaded, source: \`
          import { AsyncLocalStorage } from 'node:async_hooks';
          const settlementScope = new AsyncLocalStorage();
          export const runWithSettlementReceipt = (operation) => {
            const scope = {};
            return settlementScope.run(scope, operation, scope);
          };
        \` + source.replace(capture, capture + \`
          cache = settlementScope.getStore();
          if (!cache) return;
        \`) };
      }
      if (process.env.MCPC_RECEIPT_CANDIDATE === '1' && url.endsWith('/mcpc/dist/bridge/index.js')) {
        const loaded = next(url, context);
        const source = Buffer.from(loaded.source).toString();
        const start = '                    try {\\n                        result = await executeToolCall();';
        const end = '\\n                    break;';
        const begin = source.indexOf(start);
        const finish = source.indexOf(end, begin);
        if (begin < 0 || finish < 0) throw Error('bridge seam changed');
        const block = source.slice(begin, finish);
        if (block.split('this.x402PaymentCache').length !== 4) throw Error('receipt uses changed');
        const operation = block.replaceAll('this.x402PaymentCache', 'scope');
        return { ...loaded, source: source.slice(0, begin) + \`
          const receive = async (scope) => {
            \${operation}
          };
          if (this.x402Wallet) {
            const { runWithSettlementReceipt } = await import('../lib/x402/fetch-middleware.js');
            await runWithSettlementReceipt((scope) => receive(scope));
          } else {
            await receive({});
          }
        \` + source.slice(finish) };
      }
      if (url.endsWith('/mcpc/dist/lib/x402/signer.js')) {
        const loaded = next(url, context);
        const source = Buffer.from(loaded.source).toString();
        const target = 'export async function signPayment(';
        if (!source.includes(target)) throw Error('signer seam changed');
        return { ...loaded, source: source.replace(target, 'async function disabledRealSigner(') + \`
          export async function signPayment() {
            return {
              paymentSignatureBase64: Buffer.from(JSON.stringify({synthetic:true})).toString('base64'),
              amountUsd: 0.01,
              to: 'loopback-only',
              networkLabel: 'synthetic'
            };
          }
        \` };
      }
      return next(url, context);
    }
  });
`);

const env = {
  PATH: process.env.PATH,
  TMPDIR: home,
  HOME: home,
  MCPC_HOME_DIR: join(home, 'config'),
  NODE_OPTIONS: `--import=${mock}`,
  MCPC_RECEIPT_CANDIDATE: candidate ? '1' : '0',
};
const command = async (...args) => {
  try {
    const { stdout } = await exec(process.execPath, [cli, ...args], { env, timeout: 7000 });
    return JSON.parse(stdout);
  } catch (error) {
    throw new Error(`mcpc ${args.join(' ')}: ${error.stderr || error.message}`);
  }
};
const acceptance = {
  scheme: 'exact',
  network: 'eip155:8453',
  amount: '10000',
  asset: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
  payTo: '0x0000000000000000000000000000000000000002',
  maxTimeoutSeconds: 60,
};
const receipt = (label) => ({ success: true, network: 'eip155:8453', transaction: label });
const b64 = (value) => Buffer.from(JSON.stringify(value)).toString('base64');
const fakeHeader = b64({ synthetic: true });
const receiptKey = 'x402/payment-response';
const seen = [];
const failures = [];
let pending;
let resultA;
const server = createServer(async (req, res) => {
  if (req.method !== 'POST') {
    res.writeHead(405).end();
    return;
  }
  try {
    const chunks = [];
    for await (const chunk of req) chunks.push(chunk);
    const { method, params, id } = JSON.parse(Buffer.concat(chunks));
    if (id === undefined) {
      res.writeHead(202).end();
      return;
    }
    const body = (result) => JSON.stringify({ jsonrpc: '2.0', id, result });
    const send = (result, extra = {}) =>
      res.writeHead(200, { 'content-type': 'application/json', ...extra }).end(body(result));
    if (method === 'initialize') {
      send({ protocolVersion: '2025-11-25', serverInfo: { name: 'loopback', version: '1' },
        capabilities: { tools: {} } });
      return;
    }
    if (method === 'server/discover') {
      res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify({
        jsonrpc: '2.0', id, error: { code: -32601, message: 'Method not found' },
      }));
      return;
    }
    if (method === 'tools/list') {
      send({ tools: [{ name: 'probe', description: 'Receipt identity control',
        inputSchema: { type: 'object', properties: { run: { type: 'string' } } },
        _meta: { x402: { paymentRequired: true, accepts: [acceptance] } } }] });
      return;
    }
    assert.equal(method, 'tools/call', `unexpected method: ${method}`);
    const label = params.arguments.run;
    if (req.headers['payment-signature'] !== fakeHeader) {
      assert.equal(req.headers['payment-signature'], undefined);
      res.writeHead(402, { 'payment-required': b64({ x402Version: 2, accepts: [acceptance] }) }).end();
      return;
    }
    seen.push(label);
    const output = { content: [{ type: 'text', text: label }] };
    if (label.startsWith('A-')) {
      res.writeHead(200, { 'content-type': 'application/json',
        'payment-response': b64(receipt(`synthetic-${label}`)) });
      res.flushHeaders();
      pending = () => res.end(body(output));
      return;
    }
    if (label === 'B-absent') send(output);
    else if (label === 'B-native') send({
      ...output, _meta: { [receiptKey]: receipt('synthetic-B-native'), trace: 'retained' },
    }, { 'payment-response': b64(receipt('synthetic-B-header-shadowed')) });
    else send(output, { 'payment-response': b64(receipt(`synthetic-${label}`)) });
  } catch (error) {
    failures.push(error.message);
    res.writeHead(500).end();
  }
});

try {
  await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
  const url = `http://127.0.0.1:${server.address().port}/mcp`;
  await command('--json', 'connect', url, '@receipt', '--x402', 'exact');
  const run = (label) => command('--json', '@receipt', 'tools-call', 'probe', `run:=${label}`);
  const control = await run('C');
  assert.deepEqual(control._meta?.[receiptKey], receipt('synthetic-C'), 'ordinary receiving');
  const noReceipt = await run('B-absent');
  assert.equal(noReceipt._meta?.[receiptKey], undefined, 'sequential omission stays unknown');
  const cases = [];
  for (const kind of ['absent', 'header', 'native']) {
    const labelA = `A-${kind}`;
    const labelB = `B-${kind}`;
    pending = undefined;
    resultA = run(labelA);
    resultA.catch(() => {});
    for (let i = 0; !pending && i < 250; i++) await delay(10);
    assert.ok(pending, 'A entered the loopback endpoint with an inert signature');
    // A headers are visible while its tool body is not. B finishes first.
    const b = await run(labelB);
    pending();
    const a = await resultA;
    assert.deepEqual(a.content, [{ type: 'text', text: labelA }]);
    assert.deepEqual(b.content, [{ type: 'text', text: labelB }]);
    if (kind === 'native') assert.equal(b._meta?.trace, 'retained');
    cases.push({
      kind,
      a: a._meta?.[receiptKey]?.transaction ?? null,
      b: b._meta?.[receiptKey]?.transaction ?? null,
    });
  }
  assert.deepEqual(seen, [
    'C', 'B-absent', 'A-absent', 'B-absent', 'A-header', 'B-header', 'A-native', 'B-native',
  ]);
  assert.deepEqual(failures, []);
  console.log(JSON.stringify({
    candidate,
    control: control._meta?.[receiptKey]?.transaction ?? null,
    cases,
    syntheticRequests: seen.length,
  }));
  assert.deepEqual(cases, [
    { kind: 'absent', a: 'synthetic-A-absent', b: null },
    { kind: 'header', a: 'synthetic-A-header', b: 'synthetic-B-header' },
    { kind: 'native', a: 'synthetic-A-native', b: 'synthetic-B-native' },
  ], 'receipt references stay with their own results');
} catch (error) {
  if (failures.length) console.error('Loopback failures:', failures);
  throw error;
} finally {
  pending?.();
  await resultA?.catch(() => {});
  await command('--json', '@receipt', 'close').catch(() => {});
  server.closeAllConnections();
  await new Promise((resolve) => server.close(resolve));
  await rm(home, { recursive: true, force: true });
}

epistemedeus avatar Nov 09 '26 11:11 epistemedeus