---
id: SI0128
title: "Chain tools for local models"
url: https://carbium.sh/library/si/chain-tools-for-local-models
collection: AI and blockchain
category: Model tool calling
revision: 1
updated: 2026-11-23
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Chain tools for local models

A local model gets three read-only Solana tools: balance, token supply and recent signatures. The file tolerates the sloppy tool-call JSON small models write, refuses anything off its list and returns short results that fit a small context window.

## What a local model needs from a tool

A model running on your own machine reaches the chain the way a hosted one does: it writes a tool call, your code runs it, and the result goes back as text. The difference is in what comes out of the model. Small local models put the argument under the wrong key, wrap the JSON in a code fence or a sentence, send the arguments as a string that holds more JSON, and call tools that were never offered. A tool layer written for a large hosted model throws on the first of these.

So the layer here does three jobs. It keeps the catalog small, three tools with one string argument each, because a short flat schema is what a small model fills in correctly. It reads the model's raw text forgivingly and then checks every value strictly. It answers with a few short fields, because a small context window fills quickly and a long result pushes the question out of it.

All three tools are reads. The file holds no key pair and builds no transaction. Carbium serves `sendTransaction` (20 cells without preflight, 70 with it), so the endpoint would not stop a model that asked for it. The list in your own code does, the same way as in [read-only model tools](https://carbium.sh/library/si/read-only-model-tools), which goes deeper into the allowlist.

## The tool file

One file on Node 24 and `@solana/kit` 8.6.0. Set `CARBIUM_KEY` first; the file exits with a message when it is missing. The key goes in the `x-api-key` header of the transport, and `CARBIUM_RPC_URL` overrides the default endpoint, `https://services.carbium.sh`. Kit fills in confirmed commitment when a call leaves it out, so every read here runs at confirmed.

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

````ts
// SI0128 · Chain tools for local models
// https://carbium.sh/library/si/chain-tools-for-local-models
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

// Read-only chain tools for a local model. 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 } }),
);
const BASE58 = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;

type Tool = { description: string; key: string; run: (addr: string, limit: number) => Promise<unknown> };
const tools: Record<string, Tool> = {
  get_balance: {
    description: "SOL balance of one address. lamports is exact (1 SOL is 1,000,000,000 lamports); sol is approximate.",
    key: "address",
    run: async (a) => {
      const { value } = await rpc.getBalance(address(a)).send();
      return { lamports: String(value), sol: Number(value) / 1e9 };
    },
  },
  get_token_supply: {
    description: "Total supply of one SPL token mint. Wallet addresses fail.",
    key: "address",
    run: async (a) => {
      const { value } = await rpc.getTokenSupply(address(a)).send();
      return { uiAmountString: value.uiAmountString, decimals: value.decimals, amount: value.amount };
    },
  },
  get_recent_signatures: {
    description: "Newest transactions of one address, 30 days at most. Optional limit, 1 to 10, default 3.",
    key: "address",
    run: async (a, n) => {
      const rows = await rpc.getSignaturesForAddress(address(a), { limit: n }).send();
      return rows.map((r) => ({ signature: r.signature, slot: String(r.slot), failed: r.err !== null, blockTime: r.blockTime === null ? null : Number(r.blockTime) }));
    },
  },
};
Object.freeze(tools);

// Register these with your model server; some call `parameters` by another name.
export const schemas = Object.entries(tools).map(([name, t]) => ({
  name,
  description: t.description,
  parameters: { type: "object", properties: { [t.key]: { type: "string", description: "Base58 address" } }, required: [t.key] },
}));

function parseCall(raw: string): { name: string; args: Record<string, unknown> } {
  const start = raw.indexOf("{");
  const end = raw.lastIndexOf("}");
  if (start < 0 || end < start) throw new Error("no JSON object in the reply");
  const call = JSON.parse(raw.slice(start, end + 1));
  let args = call.arguments ?? call.parameters ?? {};
  if (typeof args === "string") args = JSON.parse(args);
  return { name: String(call.name), args };
}

export async function runCall(raw: string): Promise<string> {
  const fail = (error: string) => JSON.stringify({ error, retry: false });
  try {
    const { name, args } = parseCall(raw);
    if (!Object.hasOwn(tools, name)) return fail(`unknown tool "${name.slice(0, 40)}"`);
    const tool = tools[name] as Tool;
    const value = args[tool.key] ?? Object.values(args).find((v) => typeof v === "string");
    if (typeof value !== "string" || !BASE58.test(value)) return fail("argument is not a base58 address");
    const limit = Math.min(Math.max(Math.trunc(Number(args.limit)) || 3, 1), 10);
    return JSON.stringify(await tool.run(value, limit));
  } catch (e) {
    return fail(String((e as Error).message).slice(0, 200));
  }
}

if (import.meta.main) {
  const target = process.argv[2] ?? "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
  const replies = [
    "Sure! ```json\n" + JSON.stringify({ name: "get_balance", arguments: JSON.stringify({ address: target }) }) + "\n```",
    JSON.stringify({ name: "get_token_supply", parameters: { mint: target } }),
    JSON.stringify({ name: "get_recent_signatures", arguments: { address: target, limit: "3" } }),
    JSON.stringify({ name: "send_transaction", arguments: { transaction: "AQAB" } }),
    "I would check the balance first.",
  ];
  for (const raw of replies) console.log(await runCall(raw));
}
````

The main block feeds five raw strings through `runCall`, the way your loop would feed it the text a model produced. Each is a shape small models really send: a fenced block with double-encoded arguments, `parameters` in place of `arguments` with a wrong key name, a number written as a string, a tool that does not exist, and a reply with no JSON at all. Pass an address as the first argument, or none to use the USDC mint. It prints one line per call.

`schemas` is what you register with your model server. Servers that take a tool list want a name, a description and a JSON Schema, and the field holding the schema is called `parameters` in some and `input_schema` in others, so rename it where you register. Nothing in the schema is enforced, which is why `runCall` checks again.

## Reading sloppy tool calls

`parseCall` cuts the text from the first `{` to the last `}`, which drops code fences and the sentence a model puts around its JSON. It reads the arguments from `arguments` or `parameters`, and when they arrive as a string it parses that string a second time. Small models double-encode often enough that this one line decides whether a call works.

`runCall` then validates. The tool name must be an own property of a frozen object, so `constructor` fails like any other unknown name. The address is the argument named in the tool's definition; when the model used another key, the first string value in the arguments is taken instead, so `mint` where `address` was expected still works. The value must look like a base58 address of 32 to 44 characters, and `address()` from kit rejects one that decodes to the wrong length. `limit` is coerced from a string or a float and clamped to 1 to 10.

The forgiving part covers only the shape of the call. The tool name and the address are never guessed: an unknown name or a bad address returns an error the model can read and correct.

> Hand the string `runCall` returns to the model as the tool result in every case, errors included. A thrown exception ends your loop; a `{error, retry}` line lets the model fix its next call.

## Results that fit a small context

| Tool | Carbium method | Fields returned |
|---|---|---|
| `get_balance` | `getBalance` | `lamports` as a string, `sol` as an approximate number for display |
| `get_token_supply` | `getTokenSupply` | `uiAmountString`, `decimals`, `amount` |
| `get_recent_signatures` | `getSignaturesForAddress` | `signature`, `slot`, `failed`, `blockTime` |

Kit returns lamports and slots as `bigint`, which `JSON.stringify` refuses, so the file turns them into strings. A string keeps every digit, and a model asked to compare two balances reads the digits as given. The `sol` field exists for display; the tool description states that 1 SOL is 1,000,000,000 lamports so the model can check one against the other.

A signature is up to 88 characters long, so ten rows run to well over a thousand characters of context. That is why `limit` stops at 10 and each row carries four fields. A model with a small window can hold ten rows next to its question. A hundred rows leave no room for it.

## What each call costs

`getSignaturesForAddress` costs 50 cells a call, with rates of 0.24 req/s on Free, 1.2 on Dev, 100 on Business and 500 on Pro. A local model in a loop can ask for a history on every turn, and on a Free key 0.24 req/s is about one call every four seconds. Limits are per account, so every key on the account draws on one budget.

When a call is turned away with 429, the helper returns the node's message with `retry` false, and your loop decides when to ask again. Put a cap on tool calls per question there too. A small model that gets an error will often send the same call again with the same arguments.

## Where it ends

- History stops at the address index. `getSignaturesForAddress` pages come from an index that keeps up to 30 days, and an empty page past that point marks its age limit while the address may have older transactions. Say so in the tool description, or the model will report an empty list as an unused address.
- The file reads signatures and never calls `getTransaction`. It tells the model whether a transaction failed and when, and nothing about what it did.
- A method that is not served, such as `getTokenLargestAccounts`, answers -32601 and should not be retried. Adding it to the tool list gives the model a tool that always fails.
- `parseCall` takes the span from the first brace to the last. A reply with a second JSON object, or prose that contains braces before the call, breaks that and comes back as an error. A server that returns tool calls in a structured field avoids the case.
- Text strangers wrote on chain, such as token names and memos, can carry instructions. These three tools return only numbers and signatures. A tool that returns on-chain text needs that text treated as untrusted.
- How well a model picks between tools depends on the model. Run your own set of questions against it before you rely on it.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| The call arrives with `arguments` as a string holding JSON, so the address reads as undefined. | Parse a string argument a second time before reading keys from it. |
| The model writes the address under another key such as `mint` or `wallet`. | Fall back to the first string value in the arguments, keep the key name in the tool description, and keep tool arguments to one. |
| `JSON.stringify` throws on a lamport count or a slot. | Kit returns these as `bigint`. Convert them to strings before serializing the result. |
| The model repeats the same failing call every turn. | Return `{error, retry: false}` as the tool result and cap tool calls per question in your loop. |
| A signature list fills the model's context and the question falls out of it. | Clamp `limit` to 10 and return four fields per row. |
| An empty signature list is read as an address with no history. | State the 30-day reach in the tool description so the model reports it as the end of the index. |

## Questions

### Which local model do I need?

Any model your server can run with tool calling. The file takes the model's text and returns text, so it does not depend on one. Test your model on a fixed set of questions first.

### Does the model see the Carbium key?

No. The key sits in the transport headers inside the file. The model sees tool names, arguments and results only.

### Why not give the model one generic JSON-RPC tool?

A generic tool lets the model choose any method, `sendTransaction` included, and small models fill method names and params unreliably. Fixed tools with one argument each leave nothing for it to guess.

### How do I add a fourth tool?

Add an entry to `tools` with a short description, the argument key and a function that returns a few plain values. Keep the schema flat and the result small.

## Related

- [Read-only model tools](https://carbium.sh/library/si/read-only-model-tools) (AI and blockchain, SI0001)
- [Signature history pagination](https://carbium.sh/library/howsolana/signature-history-pagination) (How to use Solana, HS0034)
- [carbium.sh/docs/rpc](https://carbium.sh/docs/rpc)
- [carbium.sh/docs/errors](https://carbium.sh/docs/errors)
- [carbium.sh/docs/limits](https://carbium.sh/docs/limits)
- [carbium.sh/docs/auth](https://carbium.sh/docs/auth)
