Agents and integrations

SDKs, MCP and frameworks.

Every model on one key, or paid per request from a wallet, with a receipt for every request. Call it from TypeScript, Python, the AI SDK, any OpenAI-compatible client, MCP or the command line.

npm i @usdf/sdkv0.1.6
20,000+Tools
650+Models
6Clients
On this page

The USDF SDK pays per request from a wallet, with no account, or charges a key. It also reads receipts, quotes and the account. Any OpenAI chat completions client works with a key.

ClientInstallPays withFits
@usdf/sdknpm install @usdf/sdk, and viem to pay from a walletA key, or a wallet per requestApps and agents in TypeScript
@usdf/sdk/ainpm install @usdf/sdk aiA wallet or a keyThe AI SDK
openai, TypeScript and Pythonnpm install openai, pip install openaiA keyExisting OpenAI code
LangChainpip install langchain-openai, npm install @langchain/openaiA keyLangChain apps
MCPNothing: a URLA key, or a payment per callMCP clients and agents
Command linenpx @usdf/sdkA keyThe terminal

Samples use deepseek-v4.1-flash and read the key from USDF_API_KEY.

With an API key, run charges your account, paid from its Foundry wallet or its Foundry balance: new USDF({ apiKey }), or USDF_API_KEY in the environment. With a wallet instead, it pays each request on its own, with no account.

With an API key

TypeScript
Install
npm install @usdf/sdk
Code
import { USDF } from "@usdf/sdk";

const usdf = new USDF({ apiKey: process.env.USDF_API_KEY });
const result = await usdf.run("deepseek-v4.1-flash", "Hello");
console.log(result.text, result.id);

Pay per request (wallet)

TypeScript
Install
npm install @usdf/sdk viem
Code
import { USDF } from "@usdf/sdk";
import { privateKeyToAccount } from "viem/accounts";
const wallet = privateKeyToAccount(process.env.PAYER_KEY as `0x${string}`);
const usdf = new USDF({ wallet }); // or new USDF({ apiKey: process.env.USDF_API_KEY })
const result = await usdf.run("deepseek-v4.1-flash", "Hello");
console.log(result.text);

The client's methods:

MethodWhat it does
run(model, prompt)One prompt, returning { text, receipt }. Streams with onText.
chat.completions.createA chat completion, plain or streamed, with its receipt.
embeddings.createEmbeddings.
batches.createA batch job; get, result and wait follow it.
quote, balanceThe worst case of a request before it runs, and what is left.
models.list, pricingThe models serving now, and the full price sheet.
tools.list, tools.callTools on the same balance.
receipts.get, receipts.list, receipts.attestationReceipts, and the provider's signed receipt for a private request.
keys.limits, update, pause, resumeA key's caps, allowlist, pause and flags.
account.*The overview, activity, settings and analytics.
links.*USDF links: create, list, get, claim, cancel.
agents.*Create, fund, limit and pay agents.
zap.quote, pool.readPay with any token, and the USDF/USDG pool.

It reads these environment variables:

VariableMeaning
USDF_API_KEYThe API key, when no wallet is given.
USDF_BASE_URLThe gateway. Default https://api.usdf.fi.
USDF_SESSION_TOKENA session, for account calls.
USDF_RPC_URLThe chain RPC the SDK reads the wallet's USDF payment allowance from.
USDF_MAX_AMOUNTThe most it signs for one request, in units. Default 1000000, 1 USDF. A larger quote is refused before signing, with amount_over_limit: raise it, or lower max_tokens.
USDF_PAY_TOThe payee it pays, when not the gateway's own wallet.

The SDK signs only on the gateway's chain, in USDF or USDG, to the gateway's wallet, up to its maximum amount. Anything else in a 402 is refused before signing.

npm: @usdf/sdk@0.1.6

From Python, use the official openai package with a key: point it at https://api.usdf.fi/v1. LangChain's ChatOpenAI works the same way (LangChain).

One request

Python
Install
pip install openai
Code
import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.usdf.fi/v1",
    api_key=os.environ["USDF_API_KEY"],
)

completion = client.chat.completions.create(
    model="deepseek-v4.1-flash",
    messages=[{"role": "user", "content": "Hello"}],
    max_tokens=256,
)
print(completion.choices[0].message.content)

# Fields the SDK does not model stay on the response object.
receipt = completion.model_extra["receipt"]
print(receipt["request_id"], receipt["cost"]["usdf"], "USDF")

@usdf/sdk/ai is a provider for the AI SDK. usdf(model) charges USDF_API_KEY.

Generate text

TypeScript
Install
npm install @usdf/sdk ai
Code
import { generateText } from "ai";
import { usdf } from "@usdf/sdk/ai"; // charges USDF_API_KEY; createUSDF({ wallet }) from "@usdf/sdk/ai" pays per request from a wallet
const model = usdf("deepseek-v4.1-flash");
const result = await generateText({ model, prompt: "Hello" });
console.log(result.text);

createUSDF({ wallet }) pays per request from a wallet instead. The receipt is at providerMetadata.usdf.receipt.

Point any OpenAI client at https://api.usdf.fi/v1 with a key.

The openai package

Install
npm install openai
Code
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.usdf.fi/v1",
  apiKey: process.env.USDF_API_KEY,
});

const completion = await client.chat.completions.create({
  model: "deepseek-v4.1-flash",
  messages: [{ role: "user", content: "Hello" }],
  max_tokens: 256,
});
console.log(completion.choices[0].message.content);

// The receipt is an extra field the SDK's types do not declare.
const { receipt } = completion as unknown as {
  receipt: { request_id: string; cost: { usdf: string } };
};
console.log(receipt.request_id, receipt.cost.usdf, "USDF");

The TypeScript sample uses top-level await, so Node runs it only as a module: save it as a .mts file, or set "type": "module" in package.json.

The AI SDK's OpenAI-compatible provider

Works with a key. Chat completions and stateless Responses are served. With Responses, send the conversation in the input.

createOpenAICompatible

TypeScript
Install
npm install @ai-sdk/openai-compatible@3.0.54 ai@7.0.112
Code
import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
import { generateText } from "ai";

const usdf = createOpenAICompatible({
  name: "usdf",
  baseURL: "https://api.usdf.fi/v1",
  apiKey: process.env.USDF_API_KEY,
});

const { text, response } = await generateText({
  model: usdf("deepseek-v4.1-flash"),
  prompt: "Hello",
  maxOutputTokens: 256,
});
console.log(text, response.id);

Messages API clients

Clients built on the Messages API (POST /v1/messages) take the same key: set their base URL to the gateway's address without /v1, since they add /v1/messages themselves. Anthropic's SDKs read ANTHROPIC_API_KEY and send it as x-api-key; the gateway takes the key there or as a Bearer token.

Environment

export ANTHROPIC_BASE_URL=https://api.usdf.fi
export ANTHROPIC_API_KEY="$USDF_API_KEY"

Anthropic's own SDKs work the same way: the base URL without /v1, and your key.

The Anthropic SDK

Install
npm install @anthropic-ai/sdk
Code
import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic({
  baseURL: "https://api.usdf.fi",
  apiKey: process.env.USDF_API_KEY,
});

const message = await client.messages.create({
  model: "deepseek-v4.1-flash",
  max_tokens: 256,
  messages: [{ role: "user", content: "Hello" }],
});
console.log(message.content);

Moving from another router? Switch in two lines: what changes and what stays.

The whole setup, the Claude desktop app's included, with what works and what to do about each error: Claude Code and the Claude app.

Claude Code speaks the Anthropic API. Give it the gateway's address without /v1 (it adds /v1/messages itself) and your key as its auth token. Its default model and its opus, sonnet and haiku choices work with no model setting. To pin them, the newest Claude models the gateway lists now are claude-opus-5-5, claude-sonnet-5-5 and claude-haiku-5-5: see Models. Replace sk_YOUR_KEY with your key.

~/.claude/settings.json

{
  "env": {
    "ANTHROPIC_BASE_URL": "https://api.usdf.fi",
    "ANTHROPIC_AUTH_TOKEN": "sk_YOUR_KEY"
  }
}

Or set the same in the shell, then start claude from it. ANTHROPIC_API_KEY works in place of the token, sent as x-api-key: set one of the two.

Shell

export ANTHROPIC_BASE_URL=https://api.usdf.fi
export ANTHROPIC_AUTH_TOKEN=sk_YOUR_KEY
claude

The MCP server's tools inside Claude Code. Run it in a shell where USDF_API_KEY is set: the key comes from the environment, not typed into the command or your shell history.

MCP in Claude Code

claude mcp add --transport http usdf https://api.usdf.fi/mcp --header "Authorization: Bearer $USDF_API_KEY"

Cursor

Cursor connects to the MCP server with its URL and reads your key from USDF_API_KEY (${env:USDF_API_KEY}), so the file holds no key. Start Cursor where the variable is set (cursor . from that shell). Its agent then reaches every model here through the server's chat tool, paid from your key. Cursor's own model picker stays on your Cursor account: its settings take a key for the providers Cursor lists, never another address.

Add to Cursor

~/.cursor/mcp.json

{
  "mcpServers": {
    "usdf": {
      "url": "https://api.usdf.fi/mcp",
      "headers": {
        "Authorization": "Bearer ${env:USDF_API_KEY}"
      }
    }
  }
}

The same through the mcp-remote bridge, for a client that runs local servers only:

~/.cursor/mcp.json, local bridge

{
  "mcpServers": {
    "usdf": {
      "command": "npx",
      "args": [
        "-y",
        "mcp-remote@0.14.3",
        "https://api.usdf.fi/mcp",
        "--header",
        "Authorization:${USDF_AUTH}"
      ],
      "env": {
        "USDF_AUTH": "Bearer ${env:USDF_API_KEY}"
      }
    }
  }
}

Codex

Codex runs on the gateway's models as its model provider. Add this block to ~/.codex/config.toml and start Codex where USDF_API_KEY is set. Codex speaks the Responses API, which the gateway serves at https://api.usdf.fi/v1/responses.

~/.codex/config.toml

# ~/.codex/config.toml
model = "claude-sonnet-5-5"
model_provider = "usdf"

[model_providers.usdf]
name = "USDF"
base_url = "https://api.usdf.fi/v1"
env_key = "USDF_API_KEY"
wire_api = "responses"

Codex adds the MCP server with one command. It reads the key from USDF_API_KEY each time it starts the server, so the key is never written into its config; codex mcp list then shows usdf enabled.

Codex

codex mcp add usdf --url https://api.usdf.fi/mcp --bearer-token-env-var USDF_API_KEY

Cline

In Cline's settings, pick OpenAI Compatible as the API provider. Set Base URL to https://api.usdf.fi/v1, API Key to your key and Model ID to claude-sonnet-5-5, or any id from GET /v1/models.

Other tools

Any tool that takes a custom OpenAI-compatible provider works with these three values. Agents that read documentation can start at /llms.txt.

OpenAI-compatible provider

Base URL   https://api.usdf.fi/v1
API key    sk_YOUR_KEY
Model      claude-sonnet-5-5
Docs       https://api.usdf.fi/llms.txt

Step by step: Kilo Code, LibreChat, Open WebUI, n8n and LiteLLM. Prompt caching works with every client: Prompt caching.

ChatOpenAI reaches the gateway with a key and the base URL.

ChatOpenAI

Install
npm install @langchain/openai
Code
import { ChatOpenAI } from "@langchain/openai";

const llm = new ChatOpenAI({
  model: "deepseek-v4.1-flash",
  apiKey: process.env.USDF_API_KEY,
  maxTokens: 256,
  configuration: { baseURL: "https://api.usdf.fi/v1" },
});
const reply = await llm.invoke("Hello");
console.log(reply.content);

The MCP server is at POST https://api.usdf.fi/mcp. It speaks stateless streamable HTTP: one JSON-RPC message per POST, and no session.

Its tools, as tools/list gives them. The browser reads the list live once the page loads:

ToolWhat it doesAccess
list_modelsList models

Models the gateway serves with their context window, output limits and whether a route is available right now; with an API key, their prices too (USD per 1M tokens, the same figure in USDF).

Read-only
quoteQuote a request
The hold the chat tool places before running a request, in USDF and USD (output capped at 4096 tokens). More

It is an estimate, not a ceiling: a completed request is billed the provider's reported usage, normally less. Pass prompt or messages. No key needed; a request for attested hardware (a :private model id or provider.private), and any request from a Private-tier key, is quoted on its attested routes, at the model's price.

Read-only
list_toolsList tools
Tools you can call through POST /v1/tools/{id}, paid from the same balance and key as chat, each with the input it takes (with an API key, its price in USDF too), ordered by title. More

Every tool listed can be called now. q keeps the tools whose id, title or description has those words; a page holds up to 200, and page.next names the next one. No key needed.

Read-only
quote_toolQuote a tool call

What a call to a tool would hold for this input before it runs (its most it can cost), in USDF and USD, with the tool's price. It checks the input as the call would, and runs and holds nothing. No key needed.

Read-only
x402_payPay an x402 URL
Calls a URL that asks for an x402 payment and pays it for you: the gateway pays the seller in USDC from its own float and charges this key in USDF the seller's amount and the payer's fee (never free credit), within the key's and its agent's limits. More

Needs an API key. Returns the seller's answer with the payment and its receipt; a payment is charged only once the chain shows it, and one that never settles costs nothing. quote: true answers what it would cost and pays nothing. Third-party tools to call this way are listed under marketplace in list_tools (GET /v1/tools?source=marketplace).

Uses balance
agents_market_searchSearch the agents market
Agents, APIs and tools priced per call, in one market, every listing in the same shape: its id (svc_...), name, description, tags, site and logo, how it is called (GET or POST), what one call costs in USDF from this key's balance, input and output examples, and the data policy. More

Ordered by popularity (default), price or newest. No key needed to search; agents_market_call calls one.

Read-only
agents_market_callCall a listing
Calls a listing of the agents market by its id (svc_..., from agents_market_search), paid from this key's USDF balance (never free credit) within the key's and its agent's limits and at most max_price: what one call costs and nothing on top; a call its seller does not answer 2xx costs nothing, or no more than what its seller kept of it. More

Every listing is called the same way, and answers 503 market_calls_unarmed while calls to the market are not switched on. Needs an API key. Returns the seller's answer and the receipt. The input goes to the seller, whose own policy governs what it keeps.

Uses balance
chatChat completion
Runs a chat completion and returns the text with its receipt (tokens, price, cost, balance, settlement). More

With an API key it spends from that key's balance, holding the most the request can cost first. Not streamed. Output is capped at 4096 tokens. A call without a progress token answers within 55 s of arriving. With a progress token, progress is sent every 15 s and the call may run 10 minutes, so the client must reset its timeout on progress (resetTimeoutOnProgress: true in the TypeScript SDK) or wait that long. At its deadline, or when the client's connection closes, a call is cut: the text produced so far is returned with finish_reason "length" and billed on the provider's usage report where the provider gives one, otherwise on an estimate never above max_tokens; for a model whose reasoning is not streamed, at the held output budget. Cancellation messages are not supported: a call the client stops waiting for without disconnecting runs to completion or its deadline and is billed. With no key, the call is paid with x402 in USDF (signature transfer) or USDG (signed transfer), as POST /x402/v1/chat/completions: without a payment it returns isError with the payment requirements (x402Version, resource, accepts) as structuredContent; sign one accept and call again with the payment in _meta["x402/payment"], the payment argument or the PAYMENT-SIGNATURE header. The quote is the call's maximum cost at the published price (prompt at one token per byte, output at max_tokens, capped as above, no minimum), paid up front; the call is charged what it uses at that price and the rest is refunded in the asset paid, the gateway paying the gas. A paid call runs to its end or its deadline whether or not the client waits and returns the receipt and _meta["x402/payment-response"]; at the deadline the text so far is returned with finish_reason "length" and a note, charged what it used and the rest refunded. A call no provider accepted before its deadline, or whose provider failed or ended with nothing, is refunded in full in the asset paid; so is one cut by the deadline after the provider accepted it, with nothing produced. A call with less than 20 s left before its deadline is refused before the payment is settled (deadline_too_close), nothing charged. MPP clients pay the same quote: the payment-required result also carries _meta["org.paymentauth/payment-required"] with evm charge challenges (USDG by signed transfer authorization, USDF by signature transfer); call again with the credential in _meta["org.paymentauth/credential"], and the paid result carries _meta["org.paymentauth/receipt"].

Uses balance
balanceBalance
With an API key: what the key can spend now, the account's balance and the amount held for requests running, and what is left of the key's budget, in USDF. More

With address instead, and no key: that wallet's USDF and USDG on the chain now, and how much USDF it lets the signature-transfer contract spend, which x402 payments come from.

Read-only
receiptReceipt
With the API key that made the request: its receipt, with the usage, the price sheet version, the cost and, once settled, the settlement, its transaction and the rows behind the onchain digest. More

With no key: the public receipt of any request id, x402 ones included, with its line in the usage log, the payment, the settlement and where its proof is (GET /x402/v1/receipts/{id}).

Read-only

Every tool works with a key. Without one, three behave differently:

ToolWith a keyWith no key
chatCharged to the key's balance.Paid per call. The payment requirements come back as an isError result; pay with _meta["x402/payment"], a payment argument, or the PAYMENT-SIGNATURE header.
receiptThe key's own requests.The public receipt of any request id.
balanceThe key's balance and budget.With { address }: that wallet's USDF, USDG and USDF payment allowance.
list_models, quote, list_tools, quote_toolThe same.The same.

Limits

chat is not streamed to the client, so its limits keep an answer inside a client's wait:

LimitValue
chat max_tokens4096 at most
Deadline55 seconds; 10 minutes with a progress token. In the TypeScript SDK, pass onprogress with resetTimeoutOnProgress: true.
MessagesOne JSON-RPC message per POST. Batches are refused.
Request body256 KiB
Response1 MiB
Rate limitWith a key, the chat, balance and receipt tools count against the key's own limit: No limit (1–5999 req/min, configurable). With no key, the paid chat tool counts against the pay-per-request limit: 30 req/min per caller IP address.

A call cut at its deadline returns the text produced so far, billed for that output. Paid per call, the rest of the payment is refunded.

Client configuration

Name the server usdf. A client that takes a URL and headers reads the key from the environment:

Clients that take a URL and headers

{
  "mcpServers": {
    "usdf": {
      "url": "https://api.usdf.fi/mcp",
      "headers": { "Authorization": "Bearer ${env:USDF_API_KEY}" }
    }
  }
}

In Cursor, the same in one click (it reads the key from USDF_API_KEY): Add to Cursor

A client that runs local servers reaches it through the mcp-remote bridge:

Clients that run local servers

{
  "mcpServers": {
    "usdf": {
      "command": "npx",
      "args": ["-y", "mcp-remote@0.14.3", "https://api.usdf.fi/mcp", "--header", "Authorization:${USDF_AUTH}"],
      "env": { "USDF_AUTH": "Bearer sk_..." }
    }
  }
}

From code

The MCP TypeScript SDK

TypeScript
Install
npm install @modelcontextprotocol/sdk@1.32.0
Code
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";

const transport = new StreamableHTTPClientTransport(new URL("https://api.usdf.fi/mcp"), {
  requestInit: { headers: { Authorization: `Bearer ${process.env.USDF_API_KEY}` } },
});
const client = new Client({ name: "my-agent", version: "1.0.0" });
await client.connect(transport);

const { tools } = await client.listTools();
console.log(tools.map((t) => t.name));

const quote = await client.callTool({
  name: "quote",
  arguments: { model: "deepseek-v4.1-flash", prompt: "Hello", max_tokens: 256 },
});
console.log(JSON.stringify(quote.structuredContent));

// With onprogress the SDK sends a progress token: the gateway reports progress
// as it works and allows the call up to 10 minutes. resetTimeoutOnProgress is
// what makes the client keep waiting.
const chat = await client.callTool(
  { name: "chat", arguments: { model: "deepseek-v4.1-flash", messages: [{ role: "user", content: "Hello" }], max_tokens: 256 } },
  undefined,
  { timeout: 60_000, resetTimeoutOnProgress: true, onprogress: (p) => console.log("still generating", p.progress) },
);
console.log(JSON.stringify(chat.structuredContent));
await client.close();

The SDK ships one command, usdf. Run it with npx @usdf/sdk.

Commands

npx @usdf/sdk balance
npx @usdf/sdk run deepseek-v4.1-flash "Hello" --cost
npx @usdf/sdk receipts
# keys reads the account with a session: npx @usdf/sdk login --token - (the token of a signed-in session), then npx @usdf/sdk keys
# installed with npm install -g @usdf/sdk, the command is usdf: usdf balance

The commands:

CommandWhat it does
loginStores a key (--key sk_…) or a session (--token - reads it from stdin) for the gateway.
logoutForgets the stored session.
balanceWhat is available, held and left on the key.
keys [list|create|revoke|limits|pause|resume]Manages keys.
run <model> "<prompt>" [--cost]Streams an answer. --cost prints the receipt's cost.
receipts, receipt <id>Lists receipts, or shows one.
pricing, models, quote, authReads the sheet, the models, a quote and the sign-in setup.
poolThe USDF/USDG pool: price, tick and reserves. No key.

Every command takes --json. To pay per request from a wallet, use the SDK, which signs each payment.

Files an agent can read to find its way:

FileWhat it is
/skill.mdThe agent skill: buying USDF, a capped key, calling, receipts, paying per request.
/llms.txtWhat USDF is and where every surface lives.
/v1/catalog, /v1/catalog/signatureThe signed model catalog and its signature. Both take an API key or a signed-in session; without one they answer 401 missing_api_key.
/v1/catalog/signerThe address that signs the catalog, to check the signature with. No key needed.
/tokenlist.jsonA token list with USDF.
/usdf.pngThe USDF logo.

See platforms and providers

Foundry documentation

Confirm it's you

Confirm to continue the action you started.

Checking confirmation options…