JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 2861
  • Score
    100M100P100Q120443F
  • License MIT

TypeScript SDK for Zero — search, fetch, and pay for AI capabilities (x402 + MPP).

Package Exports

  • @zeroxyz/sdk
  • @zeroxyz/sdk/testing

Readme

@zeroxyz/sdk

TypeScript SDK for Zero — the search and payment layer for AI agents.

Zero indexes the API capabilities published across the web and gives an agent one interface to find them, call them, and pay for them. You search for a capability, call its URL with client.fetch(), and the SDK settles payment automatically — over x402 or MPP, in USDC — handing you back the response and the payment receipt together. The wallet is the agent's identity, so there are no per-service API keys to provision.

Install

pnpm add @zeroxyz/sdk
# npm install @zeroxyz/sdk
# yarn add @zeroxyz/sdk

Requires Node 20.3+.

Quickstart

Search needs no credentials. This is the smallest thing that runs:

import { ZeroClient } from "@zeroxyz/sdk";

const client = new ZeroClient();

const { capabilities } = await client.search("current weather in tokyo");
for (const cap of capabilities) {
  console.log(cap.id, cap.name, cap.url, cap.availabilityStatus);
}

Calling and paying for a capability needs a wallet. That's the next section.

Authentication

A client runs in one of three modes. Pick one at construction:

Mode You provide Use it when
Account A viem LocalAccount (your wallet key) You hold the wallet and sign locally. The default for partners and backends.
Session A Zero-issued access + refresh token You act on behalf of a Zero user — e.g. forwarding a session your server holds.
None Public routes only (search, capabilities.get).

Passing both account and session is a configuration error — the two modes don't compose.

Account mode (bring your own key)

The common case: you have a private key and sign requests locally.

import { ZeroClient } from "@zeroxyz/sdk";

const client = ZeroClient.fromPrivateKey(
  process.env.ZERO_PRIVATE_KEY as `0x${string}`,
);

const result = await client.fetch("https://example.com/weather?city=tokyo", {
  maxPay: "0.01", // refuse to pay more than $0.01 USDC for this call
});

console.log(result.outcome); // "success" | "payment_failed" | ...
console.log(result.body);    // parsed JSON when the response is JSON
console.log(result.payment); // { protocol, txHash, ... }, or null on a free call

fromPrivateKey and fromMnemonic are convenience constructors. For any other signer — a KMS-backed account, a hardware wallet, a custom viem account — build the account yourself and pass it in:

import { privateKeyToAccount } from "viem/accounts";

const account = privateKeyToAccount(process.env.ZERO_PRIVATE_KEY as `0x${string}`);
const client = new ZeroClient({ account });

Session mode (acting for a Zero user)

Use this when your server holds a Zero-issued token pair for a user and wants the SDK to sign with that user's Zero-managed wallet, resolved on the first paid call:

const client = new ZeroClient({
  session: {
    accessToken: userSession.access,
    refreshToken: userSession.refresh,
    onRefreshed: async ({ accessToken, refreshToken }) => {
      await db.updateUserSession(userId, { accessToken, refreshToken });
    },
  },
});

The SDK refreshes the access token automatically after a 401, and every refresh rotates the refresh token. onRefreshed is your one hook to persist the new pair — skip it and the next process restart will present a token the server has already revoked.

client.fetch()

client.fetch() is the call you'll reach for most. Given a URL, it:

  1. Sends the request.
  2. If the server answers 402 Payment Required (x402 or MPP), reads the payment challenge and pays it.
  3. Replays the request with proof of payment.
  4. Returns the body, status, and payment metadata together.
  5. Records a run on Zero when you pass a capabilityId, so the capability's reliability signal stays current and the call stays reviewable.

Endpoints that don't charge pass straight through: a 200 on the first request returns with payment: null and outcome: "success". No payment is attempted.

const result = await client.fetch(url, {
  method: "POST",
  headers: { "content-type": "application/json" },
  body: JSON.stringify({ city: "tokyo" }),
  maxPay: "0.01",          // USDC ceiling; an over-cap challenge aborts before signing
  capabilityId: "cap_abc", // attribute the run to a known capability
  signal: controller.signal,
});

switch (result.outcome) {
  case "success":
    // 2xx/3xx — result.body / result.bodyRaw are populated.
    break;
  case "payment_failed":
    // Couldn't pay: over your maxPay, insufficient balance, or an
    // unrecognized 402 protocol. Nothing settled — generally safe to retry.
    break;
  case "payment_rejected":
    // Paid, but the capability still returned 402 (a settlement/facilitator
    // race). Reconcile via result.warnings and result.payment.
    break;
  case "payment_close_failed":
    // MPP — charged, but the session-close voucher was rejected. The channel
    // is orphaned; reconcile out-of-band via result.payment.session.
    break;
  case "server_error":
    // The capability returned 4xx/5xx (after payment, if any). See
    // result.upstreamError.
    break;
  case "network_error":
    // The request never reached the server.
    break;
}

for (const warning of result.warnings ?? []) {
  // e.g. FETCH_WARNINGS.bodyTruncated, FETCH_WARNINGS.mppSessionCloseFailed
}

maxPay

maxPay is your hard per-call ceiling, in USDC. The challenge amount is checked against it before anything is signed; an over-cap challenge aborts with outcome: "payment_failed" and no on-chain spend. Set it on every paid call — it's the guardrail that keeps a mispriced or hostile endpoint from draining the wallet.

To put a human in the loop before any spend, read the price up front (cost.amount is on every search result and on capabilities.get()), show it to your user, and only call fetch() with maxPay once they approve.

Namespaces

Beyond search() and fetch(), the client groups the rest of the API into resource namespaces:

// Search — ranked capabilities for a query (no auth required)
const { capabilities } = await client.search("translate text to french", {
  maxCost: "0.05",  // optional: only results at or under this price
  protocol: "x402", // optional: "x402" | "mpp"
});

// Capabilities — full detail for one capability by id
const cap = await client.capabilities.get("cap_abc");

// Wallet (account or session mode)
const balance = await client.wallet.balance();                 // Base + Tempo
const onBase  = await client.wallet.balance({ chain: "base" }); // a single chain
const fundUrl = await client.wallet.fundingUrl({ amount: "10" }); // onramp link

// Runs — fetch() records these for you on paid calls; reach for them
// directly when you want to log or review a call yourself
const run = await client.runs.create({
  capabilityId: "cap_abc",
  status: 200,
  latencyMs: 1234,
});
await client.runs.review({
  runId: run.runId,
  success: true,
  accuracy: 5,    // 1–5
  value: 4,       // 1–5
  reliability: 5, // 1–5
});

// Bug reports
await client.bugReports.create({
  category: "broken_execution", // see the BugReportCategory union for the full set
  capabilityId: "cap_abc",
  description: "Returns 502 on every call",
});

// Auth (session mode)
await client.auth.refresh();            // force a token refresh
await client.auth.logout(refreshToken); // revoke the session server-side

// Device-code login (RFC 8628 — for CLIs and other browserless flows)
const device = await client.auth.device.start();
console.log(device.verificationUri, device.userCode);
const grant = await client.auth.device.poll(device.deviceCode);

Multi-tenant servers

A server that signs as a different end-user wallet on each request shouldn't build a fresh ZeroClient every call. Pass the wallet per call, or derive a reusable sub-client:

const base = new ZeroClient(); // shared transport config, no auth of its own

// Simplest: sign a single call as a given wallet.
await base.fetch(url, { account: tenantAccount, maxPay: "0.01" });

// Or hold a sub-client bound to that wallet. `withAccount` caches by address,
// so repeat calls for the same tenant reuse one instance.
const tenant = base.withAccount(tenantAccount);
await tenant.fetch(url, { maxPay: "0.01" });

withSession(session) is the session-mode equivalent for per-user token pairs; unlike withAccount it isn't cached, since sessions are typically one per request. On a long-running server, call base.clearAccountCache(account?) when a tenant churns — pass an account to drop one entry, or omit it to clear the cache entirely.

Errors

The SDK throws typed errors instead of strings. Match them with instanceof:

import {
  ZeroApiError,                // a 4xx/5xx from Zero's own API
  ZeroAuthError,               // missing auth, failed refresh, expired session
  ZeroPaymentError,            // payment failed before settlement
  ZeroSessionCloseFailedError, // MPP session-close voucher rejected
  ZeroTimeoutError,            // the configured timeout was exceeded
  ZeroConfigurationError,      // invalid ClientOptions
  ZeroWalletError,             // a wallet read or write failed
  ZeroValidationError,         // a response didn't match its expected schema
  ZeroError,                   // base class for all of the above
} from "@zeroxyz/sdk";

try {
  await client.fetch(url, { maxPay: "0.01" });
} catch (err) {
  if (err instanceof ZeroAuthError) {
    // re-auth and retry
  } else if (err instanceof ZeroError) {
    console.error(err.code, err.message);
  } else {
    throw err;
  }
}

client.fetch() reserves throwing for programmer errors — bad config, missing credentials, and the like. Expected runtime failures (network_error, payment_failed, an upstream 5xx) come back as a FetchResult with the matching outcome, so you handle them by branching on the result rather than by catching.

Logging

Pass a logger to observe SDK-level events — refreshes, recording failures, payment warnings:

new ZeroClient({
  logger: (event) => {
    if (event.level === "error") console.error(event.message, event.meta);
  },
});

Testing

The package ships mock helpers under @zeroxyz/sdk/testing for unit tests against a stubbed Zero API. They carry no runtime peer dependencies:

import { createTestClient, respondJson } from "@zeroxyz/sdk/testing";

const client = createTestClient({
  routes: {
    "GET /v1/capabilities/cap_abc": () =>
      respondJson({ id: "cap_abc", name: "Test capability" }),
  },
});

const cap = await client.capabilities.get("cap_abc");

For end-to-end tests against a real payment flow, mock at the network boundary with MSW or run the call against your own staging facilitator.