Skip to content

LangGraph

A LangGraph agent pays for an API the way it does anything else: through a tool. Make that tool fetch through the spendctl sidecar and the payment rules stop being the graph’s problem. The agent holds no key, and a refusal comes back as text the model can act on.

Run the sidecar and, for a first try, the mock sellers (Quickstart):

Terminal window
npx spendctl init
npx spendctl mock # terminal 1
npx spendctl start # terminal 2
Terminal window
npm install @langchain/langgraph @langchain/core @langchain/anthropic @spendctl/client zod

AgentClient talks to the sidecar at http://127.0.0.1:8402 (or SPENDCTL_URL) as one named agent. readRefusal returns the reason when spendctl did not pay, and undefined when the call was paid or free.

import { ChatAnthropic } from "@langchain/anthropic";
import { tool } from "@langchain/core/tools";
import { createReactAgent } from "@langchain/langgraph/prebuilt";
import { AgentClient, readRefusal } from "@spendctl/client";
import { z } from "zod";
const spendctl = new AgentClient({ agent: "researcher" });
const fetchPaid = tool(
async ({ url }) => {
const response = await spendctl.fetch(url);
const refusal = await readRefusal(response);
return refusal ? `Not paid: ${refusal.message}` : await response.text();
},
{
name: "fetch_paid_url",
description: "GET a URL that may charge per request (HTTP 402). Budget and approvals are enforced by spendctl.",
schema: z.object({ url: z.string().url() }),
},
);
const checkBudget = tool(async () => JSON.stringify(await spendctl.budget()), {
name: "check_budget",
description: "Remaining spend for this agent.",
schema: z.object({}),
});
const agent = createReactAgent({
llm: new ChatAnthropic({ model: "claude-sonnet-5-5" }),
tools: [fetchPaid, checkBudget],
});
const result = await agent.invoke({
messages: [
{
role: "user",
content: "Check my budget, then get the weather in Tokyo from http://localhost:4021/weather?city=Tokyo",
},
],
});
console.log(result.messages.at(-1)?.content);
  • Paid: the seller’s response body. The amount and the ledger id are in the x-spendctl-amount and x-spendctl-attempt response headers if you want to pass them on.
  • Refused: Not paid: followed by spendctl’s sentence, for example that the host is not on the allowlist or that the daily budget is used up. Returning it as the tool result lets the model explain the refusal or change plan.
  • Held for a human: with the default approvals.hold: true the tool call waits until someone runs spendctl approve (up to holdMax, 4 minutes). In a graph with its own timeouts, set approvals.hold: false so the tool returns the approval id at once, and let the agent report it or come back later (Approvals).

Budgets belong to agent names. Give each role in the graph its own AgentClient({ agent: "…" }) and its own entry under agents: in spendctl.yaml, so a researcher and a buyer cannot spend each other’s budget. Free covers two agents (Plans).