Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.agentscore.sh/llms.txt

Use this file to discover all available pages before exploring further.

@agent-score/commerce is the full merchant-side SDK for agent commerce. One install bundles identity gating, payment-protocol helpers, 402 challenge builders, discovery doc generators, and Stripe multichain support. Subpath imports keep bundle size focused: identity-only consumers pay no cost for payment helpers, and vice versa.

Installation

npm install @agent-score/commerce
Framework + integration packages are optional peer deps — install only what you use:
npm install hono mppx @x402/core @x402/evm stripe   # whatever your stack needs

Subpaths

ImportWhat it gives you
@agent-score/commerce/identity/{hono,express,fastify,nextjs,web}Trust gate middleware: KYC, age, sanctions, jurisdiction. agentscoreGate(...), captureWallet(...), verifyWalletSignerMatch(...), getAgentScoreData(c).
@agent-score/commerce/paymentnetworks, USDC, rails registries; paymentDirective, buildPaymentHeaders (one-call WWW-Authenticate + PAYMENT-REQUIRED bundle), wwwAuthenticateHeader, paymentRequiredHeader, aliasAmountFields (v1↔v2 amount field shim for v1-only x402 parser compat), settlementOverrideHeader, dispatchSettlementByNetwork, extractPaymentSigner, buildIdempotencyKey; createX402Server, buildX402AcceptsFor402 (one-call helper for the 402-emit path; derives extra.name from the registered scheme so EIP-712 domain matches the on-chain USDC contract), createMppxServer; drop-in x402 helpers: validateX402NetworkConfig (boot-time guard), verifyX402Request (parse + validate inbound X-Payment), processX402Settle (verify-then-settle in one call), classifyX402SettleResult (maps the tagged settle result to a recommended HTTP status / code / next_steps so merchants get a controlled envelope without coupling to facilitator-specific error text).
@agent-score/commerce/discoveryisDiscoveryProbeRequest, buildDiscoveryProbeResponse (with optional x402Sample for x402-aware crawlers), sampleX402AcceptForNetwork, buildWellKnownMpp, buildWellKnownX402 (x402scan v1 /.well-known/x402 shape: {version: 1, resources: ["METHOD /path"]}), buildLlmsTxt, buildSkillMd (Claude-Skill-compatible /skill.md agent-discovery manifest — strictly agent-facing data only, no internal posture), agentscoreOpenApiSnippets, siwxSecurityScheme + xPaymentInfoExtension (fixed/dynamic price + multi-protocol) + xGuidanceExtension per the x402scan OpenAPI spec, createBazaarDiscovery; noindexNonDiscoveryPaths (Hono middleware) + noindexNonDiscoveryPathsExpress + noindexNonDiscoveryPathsFastify + wrapNoindexResponse / applyNoindexHeader (Web Fetch + Next.js) — emits X-Robots-Tag: noindex on every path except the agent-discovery surfaces (/openapi.json, /llms.txt, /skill.md, /.well-known/{mpp.json,x402,agent-card.json,ucp}, /favicon.{png,ico}); pure helpers isDiscoveryPath + defaultDiscoveryPaths for any framework not listed.
@agent-score/commerce/challengebuildAcceptedMethods, buildIdentityMetadata, buildHowToPay, buildAgentInstructions, build402Body, buildPricingBlock (cents → dollar-string with shipping support), firstEncounterAgentMemory, OrderReceipt type; respond402 — drop-in 402 emit that preserves mppx’s WWW-Authenticate and layers x402’s PAYMENT-REQUIRED. buildValidationError — structured 4xx body builder ({error: {code, message}, required_fields?, example_body?, next_steps?, ...extra}) so vendors compose body shapes by name instead of inlining at every validation site.
@agent-score/commerce/stripe-multichaincreateMultichainPaymentIntent, getDepositAddress, simulateCryptoDeposit, createMppxStripe; createPiCache (TTL’d PI / deposit-address cache, Redis-backed when redisUrl set), simulateDepositIfTestMode (gates on sk_test_ and looks up the PI for you), STRIPE_TEST_TX_HASH_SUCCESS / STRIPE_TEST_TX_HASH_FAILED constants.
@agent-score/commerce/apiEverything from @agent-score/sdk re-exported in one place: AgentScore + AgentScoreError, AGENTSCORE_TEST_ADDRESSES + isAgentScoreTestAddress. Don’t add @agent-score/sdk as a separate dep — the two can drift versions.
@agent-score/commerce (top-level)Identity-publishing helpers for cross-vendor standards: buildA2AAgentCard (Google A2A v1.0 Signed Agent Card, served at /.well-known/agent-card.json), buildUCPProfile (Google Universal Commerce Protocol, served at /.well-known/ucp). Both return unsigned payloads — vendor signs + publishes.

Identity model

Two identity types: wallet (X-Wallet-Address) and operator-token (X-Operator-Token). Default checks operator-token first, then wallet. Address normalization is network-aware: EVM lowercased, Solana base58 preserved verbatim. DenialReason codes (missing_identity, identity_verification_required, token_expired, invalid_credential, wallet_signer_mismatch, wallet_auth_requires_wallet_signing, wallet_not_trusted, api_error, payment_required) each carry a structured agent_instructions JSON block describing concrete recovery actions. createSessionOnMissing auto-mints a verification session when no identity is present. verifyWalletSignerMatch (per-adapter) recovers the signer from MPP/x402 credentials and routes the verdict through the API’s server-side resolve_signer mode — one /v1/assess round trip carries both the gate verdict and the wallet-signer-match outcome. Repeat lookups for the same (claimed, signer) pair hit a per-entry cache so repeat payments under the same operator cost zero extra API calls. captureWallet is fire-and-forget — POSTs the signer to /v1/credentials/wallets so the operator’s cross-merchant credential↔wallet profile builds up over time.

Identity publishing (cross-vendor standards)

Two helpers compose AgentScore identity into the payload formats published to other agent-commerce ecosystems. Each returns an unsigned object — your service signs + serves it however its key infrastructure works.
import { buildA2AAgentCard, buildUCPProfile } from '@agent-score/commerce';

// 1. Google A2A v1.0 Signed Agent Card — published at /.well-known/agent-card.json
const card = buildA2AAgentCard({
  name: 'My Agent Service',
  url: 'https://agents.example.com',
  capabilities: { endpoints: [{ name: 'purchase', method: 'POST' }] },
  data,
});

// 2. Google Universal Commerce Protocol profile — published at /.well-known/ucp
const profile = buildUCPProfile({
  name: 'My Agent Service',
  services: [{ type: 'rest', url: 'https://agents.example.com' }],
  payment_handlers: [{ name: 'tempo', config: { recipient: TEMPO_ADDR } }],
  signing_keys: yourJWKS,
  data,
});
Note: ACP (Stripe + OpenAI Agentic Commerce Protocol) is a transactional checkout protocol — not an identity-publishing surface. ACP merchants integrate through the existing build402Body + buildPaymentHeaders + Stripe SPT rail.

Quick start: full merchant in 30 lines

import { Hono } from 'hono';
import { agentscoreGate, getAgentScoreData } from '@agent-score/commerce/identity/hono';
import {
  createX402Server,
  createMppxServer,
  paymentDirective,
  wwwAuthenticateHeader,
} from '@agent-score/commerce/payment';
import { build402Body, buildAcceptedMethods, buildAgentInstructions, buildHowToPay } from '@agent-score/commerce/challenge';

const x402 = await createX402Server({
  facilitator: 'coinbase',
  rails: ['x402-base-mainnet'],
});
const mppx = await createMppxServer({
  rails: {
    tempo: { recipient: process.env.TEMPO_RECIPIENT! },
    solana: { recipient: process.env.SOLANA_RECIPIENT!, network: 'mainnet-beta' },
  },
  secretKey: process.env.MPP_SECRET_KEY!,
});

const app = new Hono();
const _gate = agentscoreGate({ apiKey: process.env.AGENTSCORE_API_KEY!, requireKyc: true, minAge: 21 });

// Gate runs CONDITIONALLY — fires only when a payment credential is attached so
// anonymous discovery returns a 402 challenge with rails + pricing. Identity is
// verified at settle time on the retry leg.
app.use('/purchase', async (c, next) => {
  const hasPaymentHeader = Boolean(
    c.req.header('payment-signature') ||
    c.req.header('x-payment') ||
    c.req.header('authorization')?.startsWith('Payment '),
  );
  if (!hasPaymentHeader) { await next(); return; }
  return _gate(c, next);
});

app.post('/purchase', async (c) => {
  // ... identity + payment processing ...
});
See the variable-cost merchant example for x402 upto + tempo session in one file.

Fail-open (opt-in)

By default AgentScore Gate fails closed on AgentScore-side infra failure (429 / 5xx / network timeout) — buyer gets 503. Pass failOpen: true to opt in to graceful degradation, then read the per-request degraded state via getGateDegradedState(c):
import { agentscoreGate, getGateDegradedState } from '@agent-score/commerce/identity/hono';

const gate = agentscoreGate({ apiKey: process.env.AGENTSCORE_API_KEY!, failOpen: true });
app.use('/purchase', gate);

app.post('/purchase', async (c) => {
  const { degraded, infraReason } = getGateDegradedState(c);
  if (degraded) console.warn(`[gate] degraded: ${infraReason}`);
  // ...
});
getGateDegradedState is exported by every Node adapter (Hono, Express, Fastify). For withAgentScoreGate (Next.js / Web Fetch), the degraded + infraReason fields land on the gate object passed to your handler. Compliance denials (sanctions, age, jurisdiction, signer-mismatch) still deny regardless of failOpen — see compliance-gating › Fail-open behavior.

Examples

The examples/ directory has runnable single-file Hono apps for each common merchant scenario:
ExampleScenario
api-provider.tsPer-call API billing on multiple rails: Tempo MPP + x402 (Base + Solana); no compliance gate
identity-only.tsCompliance gate without payment (vendor handles their own)
multi-rail-merchant.tsFull agent-commerce: identity + Tempo MPP + x402 + Stripe SPT
stripe-multichain-merchant.tsStripe-anchored multichain (PaymentIntent → tempo/base/solana deposit addresses)
variable-cost-merchant.tsPay-per-actual-usage on two protocols: x402 upto + MPP tempo session
compliance-merchant.tsRegulated-goods merchant — full compliance gate + custom onDenied composing the denial helpers (verificationAgentInstructions, isFixableDenial, buildSignerMismatchBody, buildContactSupportNextSteps)
per-product-policy-merchant.tsMulti-product merchant where each row carries its own compliance policy (hard gate, soft, or none). Uses PolicyBlock, policyToGateOptions, runGateWithEnforcement, shippingCountryAllowed, shippingStateAllowed.