Skip to main content
Glama
x207 barter protocol

x207 barter protocol

Official

x207 SDK

TypeScript packages of x207, the barter protocol for AI agents on NEAR. They let an x402 agent pay and sell on credit inside a barter circle: the x402 batch-settlement binding on the network x207:<circleId>, plus a reference facilitator, an MCP server and test vectors.

At a glance

x207 SDK

What

The x402 batch-settlement binding on the network x207:<circleId>, a reference facilitator, an MCP server and test vectors

Role

How agents meet the contract without knowing NEAR

Run

npx -y @x207/mcp (the live testnet circle, no key; environment in Try it)

Proof

packages/scheme/test/readme-register.test.ts (TC-UM-185-01)

Packages

Package

What it is

Install

@x207/core 0.0.3

Voucher types and signing, client for the x207-circle contract, NEP-297 event parser, onboardMember

npm install @x207/core

@x207/scheme 0.0.3

x402 binding per role: client/, server/, facilitator/

npm install @x207/scheme

@x207/mcp 0.0.7

MCP server: read tools by default, signs nothing (bin x207-mcp)

npx -y @x207/mcp

flowchart LR
  subgraph Agent["Buyer agent"]
    X[x402 fetch wrapper] --> PC[X207PaymentClient]
  end
  subgraph Seller["Seller"]
    MW[x207Middleware]
  end
  PC -- "voucher" --> MW
  MW -- "/verify, /settle" --> FA[Facilitator]
  FA -- "register_cumulative" --> CT[(x207-circle)]
  CO["@x207/core"] -.-> PC
  CO -.-> FA
  MCP["@x207/mcp: read tools"] --> CT

Related MCP server: obolpay-x402-mcp

Try it

Ask an AI client about the live testnet circle through the MCP server, with no key (needs Node 22.22.2 or newer):

X207_CIRCLE_CONTRACT=x207-v013.testnet X207_CIRCLE_ID=agents-main \
X207_BACKEND_URL=https://x207.boxd.sh npx -y @x207/mcp

This starts a stdio server for an MCP client, so it waits for input. Configuration for Claude Desktop and Cursor: docs in the umbrella. To pay as a buyer:

npm install @x207/core @x207/scheme @x402/fetch

The snippet is ESM (top-level await): put "type": "module" in your package.json, or save it as a .mts file.

import { wrapFetchWithPayment } from "@x402/fetch";
import { X207PaymentClient, headroomFromRpc } from "@x207/scheme";

const secretKey = process.env.X207_VOUCHER_KEY as `ed25519:${string}`; // the voucher key, see below
const client = new X207PaymentClient({ payer: "agent.near", secretKey, headroom: headroomFromRpc({}) });
const paidFetch = wrapFetchWithPayment(fetch, client);
const response = await paidFetch("https://seller.example/api/summarize");
  • secretKey is the voucher key: one ed25519 key used only for vouchers, never a NEAR access key (Voucher key security).

  • X207PaymentClient registers x207:* and falls back to the other entry of the 402 answer (normally exact) when headroom runs out.

  • A 200 response carries the header PAYMENT-RESPONSE; extensions.x207.registration is pending, retrying or registered.

TIP

Joining a circle (onboardMember: voucher key, join, stake, wait for active) is in the quickstart. Selling: docs/seller-quickstart.md. Full tested examples: examples/buyer, examples/seller.

IMPORTANT

Honest limits.

  • The live circle is on NEAR testnet (x207-v013.testnet). The USDC entry is on Base Sepolia (eip155:84532), a testnet token with no real funds.

  • In the default verify-first mode the seller serves before the chain is asked, so when a buyer signs vouchers to many sellers the seller whose voucher is late has served and cannot be paid. settleMode: "register-first" mitigates it: one on-chain call (about 2 seconds) runs before every response, and there is no refund path if the handler fails after the voucher is registered. Full list: Overspend across sellers.

  • The MCP server reads by default and signs nothing. The proposal to the x402 Foundation is open upstream as x402-foundation/x402#4131, not accepted yet (Documents).

Add x207 with one register call (the real API of @x402/core 2.29, same in 2.30: register(network, schemeClient); the network is x207:<circleId>, or x207:* for every circle). It does not fall back to exact and does not check headroom, which X207PaymentClient above does:

import { x402Client } from "@x402/core/client";
import { X207SchemeClient } from "@x207/scheme";

const client = new x402Client().register("x207:agents-main", new X207SchemeClient({ payer: "agent.near", secretKey }));

Tested in packages/scheme/test/readme-register.test.ts (TC-UM-185-01): a fake seller answers 402 with the x207 entry, and wrapFetchWithPayment(fetch, client) retries with a signed voucher.

One 402, two kinds of buyer (SD-093)

A seller can offer the voucher to circle members and exact USDC on Base Sepolia (eip155:84532, testnet token, no real funds) to EVM buyers outside the circle, in the same 402. The 402 then lists batch-settlement@x207:<circleId>, exact@near:mainnet and exact@eip155:84532.

Seller (examples/seller):

const app = createSeller({
  facilitatorUrl: "https://facilitator.example", // x207 facilitator: vouchers
  circleId: "agents-main",
  payTo: "seller.near",
  baseSepolia: { payTo: "0xYourSellerAddress" }, // exact on Base Sepolia, settled by the public x402 testnet facilitator (https://x402.org/facilitator)
});

Under the hood this is x207Middleware({ …, alsoAccept: [{ network: "eip155:84532", asset, payTo, facilitatorUrl, extra }] }): a payment that picks the extra entry is verified and settled at that facilitator, never at the x207 one. Buyer outside the circle (needs @x402/evm, a test key from your own wallet, kept out of the repo):

import { x402Client, wrapFetchWithPayment } from "@x402/fetch";
import { ExactEvmScheme } from "@x402/evm/exact/client";
import { privateKeyToAccount } from "viem/accounts";

const client = new x402Client().register("eip155:*", new ExactEvmScheme(privateKeyToAccount(process.env.EVM_TEST_KEY as `0x${string}`)));
const response = await wrapFetchWithPayment(fetch, client)("https://seller.example/api/summarize");

A circle member registers the voucher scheme next to it. X207PaymentClient is an x402Client that already registers x207:*; other schemes are added with register, and it prefers the voucher while headroom lasts:

const client = new X207PaymentClient({ payer: "agent.near", secretKey, headroom: headroomFromRpc({}) });
client.register("eip155:*", new ExactEvmScheme(account)); // optional fallback in USDC
// the same as x402Client.register(`x207:${circleId}`, …) for a client built by hand

Run the seller with BASE_SEPOLIA_PAY_TO=0x… npm run start -w @x207/example-seller. The test examples/seller/test/seller.base-sepolia.test.ts runs both buyers locally with a mock facilitator and no keys. seller.x402-evm.test.ts (SD-096) does the same with the real ExactEvmScheme of @x402/evm 2.29.0 as buyer and the real ExactEvmScheme facilitator as verifier (a fresh key per run, chain reads stubbed): the payload passes structure, EIP-712 signature and time checks, and a payload changed after signing is refused with invalid_exact_evm_signature. The same check passes with @x402/evm 2.30.0.

Overspend across sellers: settleMode: "register-first" (SD-121)

The gap. A buyer can sign vouchers to many sellers up to its limit. The headroom check of a facilitator only sees the vouchers that facilitator holds, so with two sellers behind two facilitators the buyer can sign vouchers that are each valid but above the limit together. The contract is first come, first served: it registers the first voucher and refuses the late one with ERR_INSUFFICIENT_CREDIT. In the default mode (verify-first: /verify, handler, /settle) the seller has served on the word of its facilitator before the chain is asked, so the seller whose voucher is late has served and cannot be paid.

The mitigation. Pass settleMode: "register-first" and a registerVoucher function. The seller then registers the voucher on-chain first and runs the handler only if the contract accepts it; a refusal answers 402 (errorReason: "insufficient_credit", the contract code in extensions.x207.contractCode) and the handler does not run. registerVoucher is permissionless, so the seller sends it from its own account:

import { buildRegisterVoucherCall, registerRefusal } from "@x207/core";

const registerVoucher: RegisterVoucherFn = async ({ voucher, signature }) => {
  try {
    await sellerAccount.call(buildRegisterVoucherCall({ circleContract: "x207-circle.near", voucher, signature }));
    return { ok: true };
  } catch (error) {
    const refusal = registerRefusal(error); // { ok: false, reason: "ERR_…" } for a contract refusal
    if (refusal) return refusal;
    throw error; // RPC or key problem: the middleware answers 503 with Retry-After
  }
};
app.use(x207Middleware({ …, settleMode: "register-first", registerVoucher }));

The trade-off. One on-chain call (about 2 seconds) runs before every response, and the facilitator /settle is skipped for that request because the voucher is already registered. The default stays verify-first and is unchanged.

What stays open.

  • If the handler fails after the voucher is registered, the buyer is still charged (the response is passed through, there is no refund path).

  • It covers the x207 entry only: exact and other alsoAccept entries, and vouchers with a bundleId, are not registered by the middleware.

  • The voucher seq must be the last registered seq + 1 (register_voucher demo mode); a seller that serves many requests in parallel for one buyer needs to order them.

  • A seller with its own guard in front of the middleware is not helped by the option; the check is the on-chain call itself.

  • The facilitator is not asked about headroom across sellers; only the chain decides.

Evidence: 9 unit tests (packages/scheme/test/register-first.test.ts), one near-sandbox test with the real contract (register-first.sandbox.test.ts, two sellers, three facilitators, mock facilitators), and the testnet run contracts/scripts/ct132-overspend-demo.mjs (CT-132) on circle 0.0.18, which records the accepted and the refused register_voucher transaction hashes in contracts/docs/testnet-epochs/ct132-overspend-run.json.

Its role in x207

The SDK is how agents meet the contract without knowing NEAR. A buyer wraps fetch once and pays with signed vouchers; a seller adds one middleware and its 402 answer offers the voucher entry next to exact; the facilitator verifies vouchers and registers them on chain. spec/ holds the voucher format and test vectors that the TypeScript and Rust CI share.

Folder

Package

Contents

packages/core/

@x207/core (0.0.3 on npm)

Voucher types and signing, client for the x207-circle contract, NEP-297 event parser, onboardMember

packages/scheme/

@x207/scheme (0.0.3 on npm)

x402 binding per role: client/, server/, facilitator/

packages/mcp/

@x207/mcp (0.0.7 on npm, bin x207-mcp)

MCP server: read tools by default, signs nothing

apps/facilitator/

@x207/facilitator

Reference facilitator: /verify, /settle, /supported

spec/

scheme_batch_settlement_x207.md and test-vectors/

examples/

buyer, seller, mcp-paid-tool, python-buyer

Develop and test

Needs Node ≥ 22.22.2 and npm 11 (the lockfiles are made with it; package.json enforces only the Node version). All dependencies are pinned exactly.

npm install
npm run build
npm test                # unit tests
npm run test:sandbox    # needs a near-sandbox binary and the contract wasm (../contracts/target/near/*.wasm)
npm run conformance     # suite for other implementations of the binding

The sandbox binary is looked up in X207_SANDBOX_BIN, or in the build output of the contracts repository after cargo test has run once. Copy .env.example to .env for the facilitator; secrets live only in .env, which is not committed.

Documents

Back to x207

Overview, live demo links and the claims map: x207-labs/x207.

Part of x207

Repository

What it holds

x207

Umbrella: overview, live demo links and the claims map

contracts

The x207-circle smart contract (Rust, NEAR), the x207-locker account locker and the Sputnik DAO scripts

sdk

TypeScript packages: @x207/core, @x207/scheme, @x207/mcp, reference facilitator, test vectors

backend

The indexer, read API, HTTP 207 report and settlement worker

frontend

The dashboard

solver

The open clearing solver and its barter matching (x207-barter)

agents

Six demo agents that trade services over x402

License

Apache-2.0

Available Tools

6 tools
x207_circle_overviewx207 circle overviewA
Read-onlyIdempotent
Inspect

Start here: the circle itself, i.e. its record and rules (get_circle, get_params) plus a page of its members (read API GET /members, or the contract view list_members when no read API is set). Use x207_member_inspect for one member in detail and x207_epoch_report for one epoch. Returns {contract, circleId, circle, params, members, membersSource, warnings}; amounts are strings in the smallest unit (6 decimals). If the members part fails it shows up in warnings and the rest is still returned; an unreachable contract RPC is an error.

Inputs: members_limit, members_status.

x207_epoch_reportEpoch report (report 207)A
Read-onlyIdempotent
Inspect

One epoch of the circle: its phase and deadlines from the contract (get_epoch), and from the read API the summary, the metrics (cleared ratio: the share of debt that netting removed, so only the net cash moves) and the settlements, i.e. who owes whom what in cash. Use it after an epoch closed; use x207_simulate_clearing to test a proposal before it is submitted. Returns {epoch, contract, summary, metrics, settlements, source, warnings}. An epoch that does not exist is an error; if the read API is down the contract record is still returned, with the failures in warnings.

Inputs: epoch, settlements_limit.

x207_member_inspectInspect a circle memberA
Read-onlyIdempotent
Inspect

One member of the circle: status, stake, outstanding debt and credit limit (read API GET /members/{account} and /limits, or the contract views member and limit when no read API is set). Use it after x207_circle_overview has shown the account ids, or before paying a member; for epoch-level amounts use x207_epoch_report. Returns {account, member, limits|limit, source, warnings}. An account that is not a member is an error ("not a member" or a 404 from the read API); a failed limits lookup is only a warning.

Inputs: account (required).

x207_order_statusOrder statusA
Read-onlyIdempotent
Inspect

Orders of the circle's marketplace (read API GET /orders). With a hash: one order with its parties, budget, milestones and status. Without a hash: a page of orders, filtered by party and status. Use x207_search_listings to find offers before an order exists. An unknown hash is an error ("no order ... in circle"); an empty list is a normal result. Needs the read API (X207_BACKEND_URL).

Inputs: hash, limit, party, cursor, +1 more.

x207_search_listingsSearch marketplace listingsA
Read-onlyIdempotent
Inspect

Find offers on the circle's marketplace (read API GET /listings): what an account offers and what it wants. Use it to discover who sells a service; for an order that already exists use x207_order_status. Returns {items, nextCursor}; pass nextCursor as cursor for the next page. No match gives an empty list, not an error. Needs the read API (X207_BACKEND_URL) and fails with a clear message without it.

Inputs: limit, cursor, status, account, +4 more.

x207_simulate_clearingSimulate a clearing proposalA
Read-onlyIdempotent
Inspect

Dry run of a netting proposal: asks the contract (view simulate_clearing) whether the edges would be accepted for an epoch and how much debt they would cancel. Use it to check a proposal before a solver submits it; to see what a finished epoch actually netted use x207_epoch_report. Returns {epoch, edgeCount, result}. An invalid proposal (unknown member, amount above the debt, wrong epoch phase) comes back as an error text from the contract. Read-only, sends nothing.

Inputs: edges (required), epoch (required).

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4.4/5.0

    Scored across 6 tools

    Disambiguation5/5

    Each tool targets a clearly distinct scope: circle overview vs single-member inspection, actual epoch report vs dry-run clearing simulation, and marketplace discovery vs order lookup. The descriptions explicitly cross-reference neighboring tools, so an agent can reliably choose the right one.

    Naming Consistency4/5

    All tools share the x207_ prefix and use snake_case, which makes the set predictable overall. However, the resource/action ordering varies (member_inspect, circle_overview, simulate_clearing, search_listings, order_status), so it is mostly rather than fully consistent.

    Tool Count5/5

    Six tools map cleanly onto the server's apparent subdomains: circle, member, epoch, clearing simulation, listings, and orders. There are no redundant tools, and the count is well scoped for an inspection-oriented MCP.

    Completeness3/5

    The surface covers core read operations and a clearing dry run, but omits lifecycle actions such as submitting a netting proposal, creating orders or listings, paying members, or updating circle state. Agents can inspect the domain thoroughly but will hit dead ends for write workflows.

    Maintenance

    ActivityMaintained
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      C
      maintenance
      MCP server for AgentPay — the payment gateway for autonomous AI agents. Fund a wallet once, give your agent the key, and it discovers, provisions, and pays for tool APIs on its own. One key, every tool.
      112 npm
      1
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      An MCP server for agentic commerce, enabling AI agents to discover services, make x402 payments with USDC across multiple chains, and manage crypto wallets and token swaps.
      598 npm
      1
      MIT
    • A
      license
      A
      quality
      C
      maintenance
      Official reference MCP server for A202, the Verifiable Agreement Protocol for Agent-Led Commerce. Gives an agent the seven capabilities two organisations need to buy and sell directly: issue a mandate, check what an agent may do under it, approve an act needing a person, form an agreement, exchange obligations, verify a record by replay, and read the transaction record back.
      7
      4
      Apache 2.0