TypeScript SDK
Reference for @ndstill/sdk: the client, pay(), approvals, simulate, x402 hook, AI proxy helpers and Verify middleware.
@ndstill/sdk is the designed TypeScript client for the v2 API: typed requests and responses generated from the same registry as the API reference, plus hand-written helpers for the parts agents use most (paying, waiting for approval, x402, the AI proxy, webhooks and Verify). It runs on Node 20+, Deno, Bun, Cloudflare Workers and modern browsers (browsers only with test keys or short-lived tokens).
Install#
npm install @ndstill/sdkCreate a client#
import { NdStill } from "@ndstill/sdk";
const ndstill = new NdStill({ apiKey: process.env.NDSTILL_API_KEY });| Option | Type | Default | Notes |
|---|---|---|---|
apiKey | string | NDSTILL_API_KEY | An org key, an agent-scoped key (nds_live_…) or a test key (nds_test_…). |
accessToken | string | none | An OAuth 2.1 access token instead of a key (MCP clients, platforms). |
baseUrl | string | https://api.ndstill.com/v2 | Point at a regional cell or a local mock. |
version | string | 2026-11-01 | Sent as Ndstill-Version. Pin it; upgrade deliberately. |
timeoutMs | number | 30000 | Per request. |
maxRetries | number | 2 | Retries on network errors, 429, 502 and 504, with backoff and the same idempotency key. |
fetch | typeof fetch | global fetch | Bring your own (undici, a proxy, a test double). |
agent | string | none | Default agent ID for calls that take one. |
Pay#
pay() is payments.create(): one call, any rail. It runs the full decision pipeline and returns the payment.
const payment = await ndstill.pay({
agent: "agt_01JD8Q3W6Z",
amount: { amount: 4200, asset: "USD" }, // $42.00 in cents
counterparty: "Delta Air Lines",
purpose: "Flight SFO to JFK for the offsite",
});
if (payment.status === "held") {
// A person approves first. Wait here, or listen for approval.decided.
await ndstill.approvals.wait(payment.approval_id, { timeoutMs: 10 * 60_000 });
} else if (payment.status === "declined") {
// Plain reasons, e.g. "Over Travel desk's weekly budget by $112.00"
console.log(payment.reasons.map((r) => r.message));
}| Parameter | Type | Notes |
|---|---|---|
agent | string | Required with an org key; implied by an agent-scoped key. |
amount | Money | Integer minor units plus asset. |
counterparty | string | Name, domain, API host or payTo address. |
purpose | string | Shown to approvers and kept in evidence. |
railPreference | Rail[] | Rails to try in order. |
mandateId | string | The signed instruction this fulfils. |
dims | object | Attribution: { customer, task, project }. |
Every POST gets an Idempotency-Key automatically, and retries reuse it. Pass your own when the payment has a natural key (an invoice number), so a retry from a different process is still the same payment:
await ndstill.pay({ … }, { idempotencyKey: "invoice-1042" });Resources#
| Method | Endpoint |
|---|---|
payments.create(params) / pay(params) | POST /payment-intents |
payments.get(id) | GET /payment-intents/{id} |
payments.list(params) | GET /payment-intents |
payments.timeline(id) | GET /payment-intents/{id}/timeline |
payments.requestRefund(id, { reason, amount? }) | POST /payment-intents/{id}/refund |
simulate(params) | POST /decisions/simulate |
decisions.get(id) | GET /decisions/{id} |
approvals.get(id), approvals.wait(id, opts) | GET /approvals/{id} (polls, or listens on the event stream) |
budgets.check({ agent, amount? }) | GET /budgets for the agent's scopes |
mandates.create(params), mandates.parse(params) | POST /mandates, POST /mandates/parse |
agents.create, agents.get, agents.list, agents.freeze, agents.unfreeze | /agents… |
freezes.create(params), freezes.preview(params) | POST /freezes, POST /freezes/preview |
policies.validate, policies.simulate, policies.replay, policies.activate | /policies/{id}/… |
webhooks.verify(rawBody, headers, secret) | Local: verifies a Standard Webhooks signature and parses the event |
Every endpoint in the API reference has a typed method; the names follow the registry (ndstill.connections.test(id), ndstill.evidence.packs.create(…)).
Simulate before you ship#
// In CI, with a test key: fail the build if the policy would block a normal purchase.
const sim = await ndstill.simulate({
agent: "agt_01JD8Q3W6Z",
amount: { amount: 4200, asset: "USD" },
counterparty: "Delta Air Lines",
});
expect(sim.would_outcome).toBe("approve");
console.log(sim.trace.map((s) => `${s.stage}: ${s.result}`));Lists and pagination#
List methods return a page and an async iterator over every page:
const page = await ndstill.payments.list({ status: "held", limit: 50 });
page.data; page.has_more; page.next_cursor;
for await (const p of ndstill.payments.list({ agent_id: "agt_01JD8Q3W6Z" })) {
// fetches the next page with next_cursor as needed
}Errors#
Every non-2xx response throws an NdStillError subclass carrying the error body:
| Class | When |
|---|---|
DeclinedError | 402: declineReasons holds the structured reasons. |
InvalidRequestError | 400: fields maps each bad field to a message. |
StepUpRequiredError | A person must confirm with a passkey first. |
AuthenticationError, PermissionError | 401, 403. |
NotFoundError, ConflictError | 404, 409 (including a reused idempotency key). |
RateLimitError | 429: retryAfterMs. |
UpstreamError, TimeoutError, InternalError | 502, 504, 500. Safe to retry with the same key. |
import { DeclinedError } from "@ndstill/sdk";
try {
await ndstill.pay({ … });
} catch (e) {
if (e instanceof DeclinedError) console.log(e.declineReasons[0].message, e.requestId);
else throw e;
}Note that a held payment isn't an error: pay() resolves with status: "held".
x402 hook#
ndstill.x402.fetch is a drop-in fetch that handles 402 Payment Required. When a seller answers 402, it sends the challenge to ndStill, waits for the decision, and only with an approved payment approval token lets your wallet sign and retry the request.
const paidFetch = ndstill.x402.fetch({
agent: "agt_01JD8Q3W6Z",
wallet, // a viem account, a Coinbase CDP wallet, or any signer with signTypedData
maxAmount: { amount: 100000, asset: "USDC" }, // never sign more than $0.10 per call
});
const res = await paidFetch("https://api.northwind.example/v1/search?q=agents");A held or declined decision makes paidFetch reject with the payment attached, without signing anything. See x402 and USDC.
AI proxy helpers#
const openai = ndstill.ai.openai({ agent: "agt_01JD8Q3W6Z", task: "weekly-report" }); // an OpenAI client pointed at the proxy
const anthropic = ndstill.ai.anthropic({ agent: "agt_01JD8Q3W6Z" });Each returns the provider's own client configured with the proxy base URL and the agent's key, so every call is checked against the agent's budget. See AI provider spend.
Verify middleware#
For sellers, @ndstill/verify verifies agent passport signatures (RFC 9421) in Express, Hono, Cloudflare Workers and MCP servers:
import { verify } from "@ndstill/verify/express";
app.post("/v1/search", verify({ require: "passport" }), handler);See Verify for sellers.
Framework plugins#
Plugins wrap the SDK as tools for agent frameworks: the OpenAI Agents SDK (held payments as interruptions), the Claude Agent SDK (an in-process MCP server), LangChain and LangGraph (a toolkit plus an approval interrupt node), CrewAI, the Vercel AI SDK, and browser-agent stacks. Each exposes pay, simulate_payment and check_budget, mirroring the MCP tools.
Test mode#
Use a test key (nds_test_…) in development and CI. Calls run the full pipeline and return real decisions and traces, but simulate only: no money moves, nothing is reserved, and nothing is written to evidence. Every example in these docs runs against an in-browser mock in the same way.