---
id: SI0005
title: "LLM tool calling"
url: https://carbium.sh/library/si/llm-tool-calling
collection: AI and blockchain
category: Model tool calling
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# LLM tool calling

How a model's Solana tool call works, from the schema you send to the result you return, with three read-only tools run in parallel and every failure reported per call.

## One turn of tool calling

A model cannot call Solana. It writes text, and when you give it tool definitions it can write a structured request for one of them. Your code reads that request, runs it and sends the answer back. Everything that touches the network is your code, so everything that can go wrong is yours to handle.

1. You send the model its tool definitions: a name, a description and a JSON Schema for the arguments.
2. The model answers with one or more `tool_use` blocks, each with an `id`, a tool `name` and an `input` object.
3. You run each block and return one `tool_result` block per `tool_use`, with the same id in `tool_use_id`.
4. The model reads the results and either answers or asks for more calls. You repeat until it answers.

Field names differ between model APIs. Some call the schema field `parameters` and others `input_schema`. The code below uses `input_schema`; rename it where you register the tools and the loop stays the same.

If your model client loads tools over MCP, the handler bodies are the same functions. The protocol changes how the schema reaches the model and how the call reaches your code. The Carbium side stays one HTTPS JSON-RPC call to `https://services.carbium.sh`, whichever way the call arrived.

## Writing the definitions

The model reads the description when it picks a tool, so put in it the facts a model gets wrong. `get_balance` says that 1 SOL is 1,000,000,000 lamports. `get_recent_signatures` says it reaches back 30 days at most. Carbium's `getSignaturesForAddress` pages come from its own address index, which keeps up to 30 days, and an empty page past that is the index's age limit. Without that sentence a model reads the empty page as an address with no history.

Keep the argument schema small. One `address` string is easier for a model to fill correctly than an options object, and `additionalProperties: false` tells it nothing else is accepted. The schema informs the model and enforces nothing. The handler checks again: `address()` from @solana/kit throws on a string that is not a valid base58 address, before any request leaves the process.

Give the model one tool for each question you want it to ask. A generic tool that takes a method name and params hands it every method, including the ones that move funds. Carbium serves `sendTransaction` (20 cells without preflight, 70 with it), so nothing at the door would refuse a model that asked for it. Fixed tools, each bound to one method, keep that decision in your code. [Read-only model tools](https://carbium.sh/library/si/read-only-model-tools) shows the fixed allowlist in full.

## The tool file

The code is one file on @solana/kit 8.6.0 and Node 24, which runs the TypeScript directly. Set `CARBIUM_KEY` before you start; the file exits with a message when it is missing. `CARBIUM_RPC_URL` overrides the endpoint, which defaults to `https://services.carbium.sh`.

`main.ts` (run: `node main.ts`)

```ts
// SI0005 · LLM tool calling
// https://carbium.sh/library/si/llm-tool-calling
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

// One turn of model tool calls against Solana RPC. Run: CARBIUM_KEY=... node main.ts [address]
import { address, createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";

const key = process.env.CARBIUM_KEY;
if (!key) {
  console.error("Set CARBIUM_KEY to your Carbium API key.");
  process.exit(1);
}
const rpc = createSolanaRpcFromTransport(
  createDefaultRpcTransport({
    url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh",
    headers: { "x-api-key": key },
  }),
);

type Input = Record<string, unknown>;
export type ToolUse = { type: "tool_use"; id: string; name: string; input: Input };
export type ToolResult = { type: "tool_result"; tool_use_id: string; content: string; is_error?: true };

const json = (v: unknown) => JSON.stringify(v, (_k, x) => (typeof x === "bigint" ? x.toString() : x));
const addressInput = {
  type: "object",
  properties: { address: { type: "string", description: "Base58 account address" } },
  required: ["address"],
  additionalProperties: false,
};

// Some model APIs call `input_schema` by another name (`parameters`).
export const tools = [
  { name: "get_slot", description: "Current slot at confirmed commitment, true when read. Read only.", input_schema: { type: "object", properties: {}, additionalProperties: false } },
  { name: "get_balance", description: "SOL balance of one address in lamports (1 SOL is 1,000,000,000). Read only.", input_schema: addressInput },
  { name: "get_recent_signatures", description: "Up to 5 newest transaction signatures of one address, last 30 days at most; an empty list can mean older. Read only.", input_schema: addressInput },
];

// Kit fills in `confirmed` when a call leaves commitment out.
const handlers: Record<string, (input: Input) => Promise<unknown>> = {
  get_slot: () => rpc.getSlot().send(),
  get_balance: async (i) => (await rpc.getBalance(address(String(i.address))).send()).value,
  get_recent_signatures: async (i) => {
    const rows = await rpc.getSignaturesForAddress(address(String(i.address)), { limit: 5 }).send();
    return rows.map(({ signature, slot, err }) => ({ signature, slot, failed: err !== null }));
  },
};

// One tool_result per tool_use, in order; a failure becomes an error result, never a throw.
export function runToolCalls(blocks: ToolUse[]): Promise<ToolResult[]> {
  return Promise.all(
    blocks.map(async (b): Promise<ToolResult> => {
      try {
        if (!Object.hasOwn(handlers, b.name)) throw new Error(`unknown tool "${b.name}"`);
        return { type: "tool_result", tool_use_id: b.id, content: json(await handlers[b.name]!(b.input)) };
      } catch (e) {
        const status = (e as { context?: { statusCode?: number } }).context?.statusCode;
        const content = status === 429 ? "rate limited, wait a few seconds before the next call" : (e as Error).message;
        return { type: "tool_result", tool_use_id: b.id, content, is_error: true };
      }
    }),
  );
}

if (import.meta.main) {
  const who = process.argv[2] ?? "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM";
  const turn: ToolUse[] = [
    { type: "tool_use", id: "t1", name: "get_slot", input: {} },
    { type: "tool_use", id: "t2", name: "get_balance", input: { address: who } },
    { type: "tool_use", id: "t3", name: "get_recent_signatures", input: { address: who } },
    { type: "tool_use", id: "t4", name: "send_transaction", input: {} },
    { type: "tool_use", id: "t5", name: "get_balance", input: { address: "not-an-address" } },
  ];
  for (const r of await runToolCalls(turn)) console.log(r.tool_use_id, r.is_error ? "error" : "ok", r.content.slice(0, 200));
}
```

`runToolCalls` is the part you keep. It takes the `tool_use` blocks from one model turn and returns the `tool_result` blocks for the next request. The main block stands in for the model: it writes five `tool_use` blocks by hand, as a model would, and prints one line per result. Three are real reads for the address you pass as the first argument. A fourth names a tool that does not exist, and a fifth passes a string that is not an address. Those two print `error`, produced in your code with no request sent.

Kit returns slots and lamports as `bigint`, which `JSON.stringify` refuses. The `json` helper writes them as strings, which also keeps a model from receiving a large number as a rounded float. Results are cut at 200 characters in the printout only; in a real loop you send the whole string.

## Several calls in one turn

Models often return several `tool_use` blocks in one turn. `runToolCalls` starts them together with `Promise.all`, which returns the results in the order of the blocks. Every block gets exactly one `tool_result` with its own id. Most model APIs reject the next request when a `tool_use` id has no matching result, so a handler that throws must still produce one. The catch turns each failure into a result with `is_error` set, and the model sees the failure next to the successes.

| Tool | JSON-RPC method | Cost at Carbium |
|---|---|---|
| `get_slot` | `getSlot` | 1 cell, a cheap cached read |
| `get_balance` | `getBalance` | billed at its [method's cell price](https://carbium.sh/docs#rpc) |
| `get_recent_signatures` | `getSignaturesForAddress` | 50 cells |

Parallel calls spend in parallel. The signatures read costs 50 cells against 1 for the slot, and its rate is 0.24 requests a second on Free and 1.2 on Dev. Each class absorbs a burst of cells well above that, so three signature calls in one turn get through from a full bucket. A loop that keeps making signature calls drains the burst, and then the calls come back as 429.

Limits are per account, and an account's keys share one budget. A tool loop in one service and a cron job in another can drain the same budget. Put a cap on tool calls per task in your loop, since a model that gets an error often asks again.

## Commitment, staleness and errors

A slot is about 200 ms and a model turn takes seconds, so the chain has moved on several slots by the time the model reads `get_slot`. The description says the value was true when read, and the model should not compare slots across turns as if they were live. It also says confirmed, because kit fills that in when a call leaves commitment out.

- On a 429 the kit transport does not retry. The error reaches the handler with the HTTP status in its context, and the file returns a result that tells the model to wait. Whether to call again is your loop's decision.
- -32601 is method not found: do not retry. Methods such as `getTokenLargestAccounts` are not served and answer it. None of the three tools here can reach it, but a tool you add later on a method Carbium does not serve will, and its result should say not to retry.
- Any other error goes back as the error's own message with `is_error` set, so the model gets the reason and no stack trace.

## Where it ends

- The file makes no model request. It runs one turn with calls written by hand. The loop that sends the tool definitions and feeds the results back belongs to your model client.
- Three fixed tools cannot send a transaction, and that holds only while nobody adds a fourth. There is no signing and no private key here. A tool that spends needs its own process and a human approval step.
- On-chain text, such as token names and memos, is written by strangers and can contain instructions. These tools return numbers, signatures and slots. A tool that returns on-chain text needs that text treated as untrusted input.
- `get_balance` reads SOL only. Token balances need a token account tool; [SPL token balance](https://carbium.sh/library/howsolana/spl-token-balance) reads one.
- `get_recent_signatures` returns up to five rows from the last 30 days. Older transactions are not served, and the tool cannot find an address's first transaction.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| The next request is rejected because a `tool_use` id has no `tool_result`. | Return exactly one result per block, in order, and catch every handler error into a result with `is_error` set. |
| `JSON.stringify` throws on a slot or a lamport count. | Kit returns `bigint`. Serialise with a replacer that writes bigints as strings. |
| The model reads an empty signatures page as an address with no history. | State the 30-day reach in the tool description. Carbium's address index keeps up to 30 days, and an empty page past that is its age limit. |
| A turn of parallel calls hits 429 and the model asks again at once. | Return a result that says to wait, and cap tool calls per task in your loop. Limits are per account, so other keys may be spending the same budget. |
| The model passes a name or a sentence as `address`. | Let `address()` throw before any request, and return its message as an error result. The model usually corrects itself on the next call. |
| The model reports a lamport count as SOL. | Put the conversion in the description: 1 SOL is 1,000,000,000 lamports. |

## Questions

### Do I need MCP to give a model Solana tools?

No, tool calling works with plain definitions and a loop in your code. MCP is one way to carry the same definitions and calls between a model client and your handlers, and the handlers and the Carbium calls stay as they are.

### Where does the Carbium key go?

In the `x-api-key` header, set once on the transport from `CARBIUM_KEY`. It stays out of tool arguments, tool results, error text and logs, so the model never sees it.

### How do I add a token balance tool?

Add a definition, a handler and a result trim for `getTokenAccountBalance`. Account reads cost 10 cells each, and [SPL token balance](https://carbium.sh/library/howsolana/spl-token-balance) shows the call.

### How many tool calls can one task make?

Cached reads such as `getSlot` cost 1 cell and run at 5, 30, 100 and 500 requests a second on Free, Dev, Business and Pro. The signatures read costs 50 cells. The cap itself belongs in your loop, and the [limits](https://carbium.sh/docs#limits) set the rates it works within.

## Related

- [Read-only model tools](https://carbium.sh/library/si/read-only-model-tools) (AI and blockchain, SI0001)
- [SPL token balance](https://carbium.sh/library/howsolana/spl-token-balance) (How to use Solana, HS0001)
- [carbium.sh/docs#rpc](https://carbium.sh/docs#rpc)
- [carbium.sh/docs#auth](https://carbium.sh/docs#auth)
- [carbium.sh/docs#limits](https://carbium.sh/docs#limits)
- [carbium.sh/docs#errors](https://carbium.sh/docs#errors)
- [carbium.sh/docs#endpoints](https://carbium.sh/docs#endpoints)
