Integrate

TypeScript SDK

@cortexpay/sdk is a typed client for the CortexPay API: agents, policies, discovery, payments, approvals, network activity, analytics, credits and webhook verification. It has no runtime dependencies, adds an Idempotency-Key to every payment call and turns API errors into typed exceptions.

Preview status#

Preview: implemented and tested against this deployment

Version 0.1.0-preview.0 is not published to npm; build it from the sdk folder of this repository. Every method on this page was run against this deployment's API in a sandbox workspace on 2 December 2026 (see what was tested). The SDK has not been run against a live workspace.

Install#

Build and install from this repository
# in a checkout of this repository
cd sdk
npx tsc -p tsconfig.json        # builds sdk/dist

# in your project
npm install /path/to/cortexpay/sdk
  • Requires fetch, AbortController and Web Crypto. It was tested on Node 24; the package declares Node 20 or later. Other runtimes with those globals were not run.
  • Use it on servers. An API key in a browser bundle can be read by anyone who opens the page.

Create a client#

client.ts
import { CortexPay } from "@cortexpay/sdk";

const cortex = new CortexPay({
  apiKey: process.env.CORTEXPAY_API_KEY!, // cpk_test_… for a sandbox workspace
  baseUrl: "https://cortexpay.vercel.app",
});

const credits = await cortex.credits.balance();
console.log(credits.mode, credits.balance);
OptionDefaultWhat it does
apiKeyrequiredA key from Developer Console → API keys: cpk_test_… for a sandbox workspace, cpk_live_… for a live one.
baseUrlrequiredThe deployment to call, http or https.
timeoutMs60000Timeout for each attempt. A timeout raises ConnectionError with code timeout.
maxRetries2Retries after a network failure, 429 or 5xx. See Idempotency and retries.
maxRetryDelayMs10000Longest wait between retries. A longer Retry-After raises RateLimitError instead of waiting.
fetchglobal fetchYour own fetch, for tests or a proxy.

Every method also takes a last argument { idempotencyKey?, signal?, timeoutMs? } for that call alone.

Methods#

approvals.approve and approvals.reject exist so your code can handle the refusal: approvals are decided by an owner or admin in a signed-in session, and the API answers 403 to every API key. Resume, fund, withdraw and the sandbox credit top-up are session-only too, so an agent holding a key can never un-pause itself, move funds or approve its own payment. They are not in the SDK.

Pay for a service#

services.request runs the whole flow in one call. A refused payment is a result, not an exception: read status. A request that waits for approval comes back with HTTP 202 and status: "awaiting_approval"; the SDK returns it like any other result.

services.request
// One call: x402 challenge, quote, the ten policy checks, payment and delivery.
const result = await cortex.services.request(
  { agentId: "AGENT_ID", serviceId: "SERVICE_ID", input: { query: "Summarise stablecoin flows for today" } },
  { idempotencyKey: "TASK_ID:market-summary" }, // optional: generated when omitted
);

switch (result.status) {
  case "delivered":
    console.log(result.delivery?.data, result.settlement?.reference);
    break;
  case "awaiting_approval":
    console.log("Waiting for an owner:", result.approvalId);
    break;
  default:
    console.log(result.status, result.evaluation?.reasonCode, result.evaluation?.reason ?? result.error?.message);
}

Quote first, then authorize

payments.quote reads the service's x402 challenge, stores a quote valid for five minutes and previews the decision without charging anything. payments.authorize runs the ten checks again and pays. Authorizing the same quote twice returns the same payment.

payments.quote → payments.authorize
const quoted = await cortex.payments.quote({ agentId: "AGENT_ID", serviceId: "SERVICE_ID", input: { query: "..." } });
console.log(quoted.quote?.amountBase, quoted.quote?.expiresAt, quoted.evaluation?.decision);

if (quoted.quote && quoted.evaluation?.decision !== "rejected") {
  const paid = await cortex.payments.authorize({ quoteId: quoted.quote.id });
  console.log(paid.status, paid.paymentId);
}

Let the agent send the payment

With execute: false, a sandbox workspace gets the signed PAYMENT-SIGNATURE header back instead of CortexPay calling the service. The agent sends it to the resource before payment.validBefore. See x402 payment flow.

authorize({ execute: false })
const input = { query: "ETH funding rates" };
const quoted = await cortex.payments.quote({ agentId: "AGENT_ID", serviceId: "SERVICE_ID", input });
const signed = await cortex.payments.authorize({ quoteId: quoted.quote!.id, execute: false });

if (signed.status === "authorized" && signed.payment?.resource) {
  const res = await fetch(signed.payment.resource, {
    method: "POST",
    headers: { "Content-Type": "application/json", [signed.payment.header.name]: signed.payment.header.value },
    body: JSON.stringify(input),
  });
  console.log(res.status, res.headers.get("PAYMENT-RESPONSE"));
}

Idempotency and retries#

  • agents.register, policies.create, services.request, payments.quote and payments.authorize always send an Idempotency-Key: a new UUID, or the one you pass. A key must be 8 to 128 characters of A-Z a-z 0-9 . _ : -; anything else throws before a request is sent.
  • Store the key with your task and pass it again after a crash: CortexPay replays the first result instead of paying twice.
  • Network failures, 429 and 5xx are retried up to maxRetries times with a growing delay, only for GET requests and calls that carry an Idempotency-Key, and always with the same key. Other POSTs, such as agents.pause, are never retried.
  • On 429 the SDK waits for Retry-After when it is within maxRetryDelayMs; otherwise it raises RateLimitError at once.

The server side of this is described in Idempotency.

Errors#

Every error response { "error": { "code", "message", "details" } } becomes an exception with status, code, message and details. An error page that is not JSON gets the code http_<status>.

ClassWhen
ValidationError400. issues lists up to eight { path, message }.
AuthenticationError401: missing, unknown, expired or revoked key.
PermissionError403: the key lacks the scope, or the action needs a person in a session.
NotFoundError404
ConflictError409, for example already_paused, quote_expired or idempotency_key_reused.
UnprocessableError422
RateLimitError429. retryAfter is in seconds.
ServerError5xx
ConnectionErrorNo response: code is connection_error or timeout, status is 0.
Handling errors
import { CortexPayError, RateLimitError, ValidationError } from "@cortexpay/sdk";

try {
  await cortex.agents.pause("AGENT_ID", { reason: "Budget review" });
} catch (e) {
  if (e instanceof ValidationError) console.log(e.issues); // [{ path, message }]
  else if (e instanceof RateLimitError) console.log("Retry in", e.retryAfter, "s");
  else if (e instanceof CortexPayError) console.log(e.status, e.code, e.message);
  else throw e;
}

All error codes are listed in Errors.

Verify webhooks#

verifyWebhook(rawBody, signatureHeader, secret) resolves to true or false. parseWebhook verifies and returns the typed event, or throws WebhookSignatureError. Both use Web Crypto and a constant-time comparison.

Webhook receiver
// app/api/cortexpay/route.ts (Next.js); any framework that gives you the raw body works the same way
import { parseWebhook, WebhookSignatureError } from "@cortexpay/sdk";

export async function POST(req: Request) {
  const raw = await req.text(); // the raw body: never parse and re-serialise before verifying
  try {
    const event = await parseWebhook(raw, req.headers.get("CortexPay-Signature"), process.env.CORTEXPAY_WEBHOOK_SECRET!);
    // event.id is the same on every retry of this event: skip ids you have already handled.
    if (event.type === "payment.settled") console.log(event.data);
    return new Response(null, { status: 204 });
  } catch (e) {
    if (e instanceof WebhookSignatureError) return new Response("invalid signature", { status: 400 });
    throw e;
  }
}
  • The header is t=<unix>,v1=<hex HMAC-SHA256(secret, "<t>.<raw body>")>. Timestamps more than five minutes from your clock are refused; pass { toleranceSec } to change that.
  • Verify the raw body exactly as received. Parsing and re-serialising the JSON changes the bytes and the check fails.
  • Rotating the secret in the console takes effect at once, so update CORTEXPAY_WEBHOOK_SECRET straight away. Delivery format, retries and event types are in Webhooks.

Other endpoints#

Endpoints the SDK does not wrap yet (webhook endpoints, policy versions, agent updates, transactions, AI reports) can be called with cortex.request. It sends the same headers and raises the same errors; set idempotent: true to send an Idempotency-Key and allow retries.

cortex.request
import type { Page } from "@cortexpay/sdk";

type CreditTx = { id: string; delta: string; balanceAfter: string; reason: string; createdAt: string };

const ledger = await cortex.request<Page<CreditTx>>({
  method: "GET",
  path: "/api/credits/transactions",
  query: { reason: "grant", limit: 5 },
});
console.log(ledger.data, ledger.nextCursor);

Every endpoint, with the scope a key needs, is in the API reference.

What was tested#

The integration suite in sdk/test/integration.test.ts signs in as the owner of a sandbox workspace, creates two API keys through POST /api/keys, runs the steps below against the real API and revokes the keys. It passed in full on 2 December 2026. An endpoint that answers 404 without a JSON error is skipped and logged rather than failed.

  1. credits.balance with an API key, and cortex.request for GET /api/credits/transactions
  2. services.list with q; with a category array, sort price_asc and limit (filter and order checked)
  3. services.get by slug
  4. policies.create; the same Idempotency-Key replays the same policy; the same key with another body raises idempotency_key_reused; policies.get
  5. agents.register on that policy with a sandbox initial budget; agents.get; agents.list with q, status and limit
  6. policies.evaluate: approved at the listed price, rejected with per_transaction_limit above it
  7. services.request: delivered with a simulated sim_ settlement; a retry with the same key returns the same request and payment; services.getRequest
  8. payments.get and payments.verify (verified on the sandbox ledger)
  9. payments.quote then payments.authorize; authorizing the same quote again returns the same payment
  10. payments.authorize with execute: false returns a PAYMENT-SIGNATURE header; sending it to the x402 resource returns 200 with PAYMENT-RESPONSE
  11. an approval-mode agent: services.request resolves awaiting_approval (HTTP 202); approvals.list contains it; approvals.approve and approvals.reject raise PermissionError
  12. agents.pause; pausing again raises ConflictError (already_paused); a request while paused resolves rejected with agent_authorization
  13. agents.revoke cancels the pending approval and freezes the account; revoking again raises ConflictError
  14. network.activity with an agent filter and a kind array; analytics.expenditure with range and agentId
  15. NotFoundError for an unknown service, ValidationError with issues, PermissionError for a key without the scope, AuthenticationError for an unknown key
  16. AuthenticationError for a revoked key

Unit tests with a fake fetch cover headers and query strings, generated and explicit Idempotency-Keys, malformed keys, error classes for each status, validation issues, Retry-After, error pages that are not JSON, retries with the same key, no retries for other POSTs, connection errors and timeouts. The webhook tests check valid signatures, changed or re-serialised bodies, wrong secrets, the five-minute window and malformed headers, and that verifyWebhook accepts what the CortexPay delivery worker signs.

Not tested
Live workspaces (the owner-signed live flow was tested through the API on local forks of both mainnets, not through the SDK), the approve and reject success path (it needs a person in the app), and retries against the real server (covered with the fake fetch only).