---
id: SI0021
title: "Claude Code MCP setup"
url: https://carbium.sh/library/si/claude-code-mcp-setup
collection: AI and blockchain
category: Your own MCP server on Carbium RPC
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Claude Code MCP setup

You get one TypeScript file and the exact Claude Code commands that register it. Claude can then read a balance, list an address's newest transactions and summarize one, with the key in the server's environment and no way to send.

## Registering with Claude Code

Claude Code starts an MCP server as a child process and exchanges one JSON-RPC message per line with it over stdin and stdout. The tools the server lists appear beside the built-in ones. Registration therefore needs a command, its arguments and an environment, and nothing else.

Install the single dependency next to the file with `npm install @solana/kit@8.6.0`. Node 24 runs the TypeScript directly. Then pick the scope that fits how you work:

- `claude mcp add-json carbium "{\"command\":\"node\",\"args\":[\"/absolute/path/main.ts\"],\"env\":{\"CARBIUM_KEY\":\"$CARBIUM_KEY\"}}"` registers it for you in this project only. Your shell expands the variable first, so the value ends up in Claude Code's own config file in your home folder.
- `claude mcp add-json --scope project carbium '{"command":"node","args":["tools/main.ts"],"env":{"CARBIUM_KEY":"${CARBIUM_KEY}"}}'` writes a `.mcp.json` at the repo root that you can commit. The single quotes keep the shell from expanding the text, so the file holds the placeholder `${CARBIUM_KEY}` and Claude Code fills it from its own environment at launch. Start Claude Code from the repo root so the relative path resolves.
- `claude mcp list` prints every server and whether it connected. Inside a session, `/mcp` shows the same and lets you reconnect after an edit.

Claude Code asks you to approve a server it finds in a project's `.mcp.json` before it runs it, so a teammate who clones the repo gets an approval prompt before the server starts.

## The server file

The file speaks the five messages a tools-only server needs: `initialize`, `ping`, `tools/list`, `tools/call` and the `notifications/initialized` notice that gets no reply. It sends every chain call to `https://services.carbium.sh`, the default of `CARBIUM_RPC_URL`, with the key in an `x-api-key` header set once on the transport. It exits with a message when `CARBIUM_KEY` is unset.

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

```ts
// SI0021 · Claude Code MCP setup
// https://carbium.sh/library/si/claude-code-mcp-setup
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

// Read-only Solana tools for Claude Code, as a stdio MCP server.
// Register with claude mcp add-json carbium: command node, args main.ts, env CARBIUM_KEY.
// Check: node main.ts --demo [address]
import { address, signature as sig, createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";
import { createInterface } from "node:readline";

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

type Tool = { description: string; field: string; run: (value: string) => Promise<unknown> };
const text = (v: unknown) => JSON.stringify(v, (_k, x) => (typeof x === "bigint" ? x.toString() : x));

// Claude picks a name from this table and fills one string field. No entry sends or signs.
const TOOLS: Record<string, Tool> = {
  sol_balance: {
    description: "SOL balance of one address in lamports (1 SOL is 1,000,000,000), read at confirmed commitment.",
    field: "address",
    run: async (v) => (await rpc.getBalance(address(v)).send()).value,
  },
  recent_activity: {
    description: "Newest 5 transactions of an address from the last 30 days: signature, slot and err.",
    field: "address",
    run: async (v) => (await rpc.getSignaturesForAddress(address(v), { limit: 5 }).send()).map((s) => ({ signature: s.signature, slot: s.slot, err: s.err })),
  },
  transaction_summary: {
    description: "Slot, block time, fee in lamports and error of one transaction signature. Old signatures may be gone from the ledger.",
    field: "signature",
    run: async (v) => {
      const tx = await rpc.getTransaction(sig(v), { encoding: "json", maxSupportedTransactionVersion: 1 }).send();
      return tx ? { slot: tx.slot, blockTime: tx.blockTime, version: tx.version, fee: tx.meta?.fee, err: tx.meta?.err } : "not found in the ledger";
    },
  },
};

async function handle(msg: any): Promise<object | undefined> {
  if (msg.id === undefined) return undefined; // a notification gets no reply
  const { id, method, params } = msg;
  const ok = (result: object) => ({ jsonrpc: "2.0", id, result });
  const bad = (code: number, message: string) => ({ jsonrpc: "2.0", id, error: { code, message } });
  if (method === "initialize") return ok({ protocolVersion: params?.protocolVersion ?? "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "carbium", version: "1.0.0" } });
  if (method === "ping") return ok({});
  if (method === "tools/list") {
    const tools = Object.entries(TOOLS).map(([name, t]) => ({ name, description: t.description, inputSchema: { type: "object", properties: { [t.field]: { type: "string" } }, required: [t.field] } }));
    return ok({ tools });
  }
  if (method !== "tools/call") return bad(-32601, `method not found: ${method}`);
  const tool = typeof params?.name === "string" && Object.hasOwn(TOOLS, params.name) ? TOOLS[params.name] : undefined;
  if (!tool) return bad(-32602, `unknown tool: ${params?.name}`);
  try {
    return ok({ content: [{ type: "text", text: text(await tool.run(String(params.arguments?.[tool.field]))) }] });
  } catch (e) {
    return ok({ content: [{ type: "text", text: (e as Error).message }], isError: true });
  }
}

if (process.argv[2] === "--demo") {
  const who = process.argv[3] ?? "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
  const call = (id: number, name: string, args: object = {}) => ({ jsonrpc: "2.0", id, method: "tools/call", params: { name, arguments: args } });
  const show = async (req: object) => {
    const out = await handle(req);
    console.log(text(out ?? "no reply").slice(0, 300));
    return out as any;
  };
  await show({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18" } });
  await show({ jsonrpc: "2.0", id: 2, method: "tools/list" });
  await show(call(3, "sol_balance", { address: who }));
  const recent = await show(call(4, "recent_activity", { address: who }));
  const rows = recent?.result?.isError ? [] : JSON.parse(recent?.result?.content?.[0]?.text ?? "[]");
  if (rows[0]) await show(call(5, "transaction_summary", { signature: rows[0].signature }));
  await show(call(6, "send_transaction"));
} else {
  for await (const line of createInterface({ input: process.stdin })) {
    if (!line.trim()) continue;
    try {
      const out = await handle(JSON.parse(line));
      if (out) process.stdout.write(text(out) + "\n");
    } catch {} // a malformed line is skipped
  }
}
```

Each tool is a name, a description and one function that makes one call. The model supplies a single string, the address or the signature. It never supplies a method name, so the set of things Claude can do is the set of entries in `TOOLS`.

`node main.ts --demo` sends the handler the messages a client would: the handshake, the tool list, a balance, the newest signatures of an address, a summary of the newest one and a call to `send_transaction`. That last call gets -32602 from the table and sends no request. Pass your own address as the second argument. The default is the Token program, which has activity every second.

## What Claude does with the tools

Claude Code names each tool after its server, so these three appear as `mcp__carbium__sol_balance`, `mcp__carbium__recent_activity` and `mcp__carbium__transaction_summary`. The first call to each asks for your permission. An allow rule of `mcp__carbium` in your settings approves every tool of that server at once, which is reasonable here because none of them can write.

The description is the only instruction the model gets about a tool, so put the unit in it. The balance description says that 1 SOL is 1,000,000,000 lamports. A model that receives a bare integer sometimes moves the decimal point.

Try it with a question that needs two tools: "What was the fee on the newest transaction touching the Token program?" Claude lists recent activity, takes the first signature and asks for its summary. Each answer comes back as a line of JSON text, with `bigint` values turned into strings by the `text` helper because JSON has no bigint.

A tool that throws returns a normal result with `isError` set and the message as text. Claude reads the message and can retry with a corrected address, and the session keeps running.

## Read-only by construction

Carbium serves `sendTransaction`, at 20 cells without preflight and 70 with it. To the endpoint a send is an ordinary call, so the boundary has to sit in your file. `Object.hasOwn` checks the tool name against the table, which stops `send_transaction` and an inherited name such as `constructor` before a request goes out.

The file holds no keypair and imports nothing that signs. Claude Code's permission prompts are a second layer on top of that table. Treat the table as the control and the prompts as a convenience. The [read-only MCP server entry](https://carbium.sh/library/si/read-only-mcp-server) builds the same idea with different tools and covers the protocol side in more depth.

`address()` and the signature parser from kit reject anything that does not decode, so a pasted sentence or URL fails before it reaches the RPC parameters.

## Cost and limits

| Tool | RPC method | Cells per call |
|---|---|---|
| `recent_activity` | `getSignaturesForAddress` | 50 |
| `transaction_summary` | `getTransaction` | 50 |

The question above costs 100 cells, one of each. `getSignaturesForAddress` runs at 0.24 req/s on Free, which is about one call every four seconds, and 1.2 req/s on Dev. A class absorbs a burst of up to 1,024 cells, about 20 calls at 50 cells each, before that sustained rate applies. A short chain of lookups therefore goes through on Free, and a long task meets 429. A call that stays over its rate gets 429, and the status shows up in the tool's error text.

[Limits are per account](https://carbium.sh/docs#limits), and the account's keys share one budget. Another service on the same account can spend what Claude needs. Cap the lookups per task in your prompt or in a project instruction, because the server does not count calls.

## Where it ends

- Tools only. There are no resources, prompts or notifications, and nothing watches the chain. A live feed would sit on a WebSocket subscription that this file does not open.
- The protocol is a hand-written subset. The server echoes the protocol version the client asks for and validates nothing beyond the address and signature parsers. An MCP SDK adds schema validation, version negotiation and other transports.
- `getSignaturesForAddress` reaches back 30 days at most, from Carbium's own address index. An empty page past that is the index's limit, and the address may hold older transactions. The tool returns one page of five and does not page.
- That index reaches below the validator's ledger floor, so `getTransaction` can answer null for an older signature the list returned. The summary tool says so in plain text. Summaries of the newest signatures work.
- The tools return numbers, addresses and signatures. A tool that returns token names or memos hands text written by strangers to the model, which then needs treating as untrusted input.
- Nothing here signs. A tool that spends needs its own process and a human approval step.

The summary tool reads with `maxSupportedTransactionVersion: 1`. Mainnet carries v1 transactions, and without that value `getTransaction` answers -32015 for one. The [version error entry](https://carbium.sh/library/howsolana/transaction-version-error-32015) walks through that failure.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| `claude mcp list` shows the server as failed to connect. | Run `node /absolute/path/main.ts --demo` by hand with the same environment. The usual causes are a relative path used from another folder, `@solana/kit` not installed beside the file, an empty or unset `CARBIUM_KEY` (the file exits before it lists any tool), and a Node too old to strip types (before 22.18). |
| The tools list, but every call returns an error mentioning 401. | Carbium does not know the key. The `env` value may hold the literal text `$CARBIUM_KEY` because single quotes kept the shell from expanding it when you ran `claude mcp add-json`. Attach the whole key, and check what Claude Code was started with. |
| `transaction_summary` answers that the transaction is not in the ledger for a signature the activity tool just listed. | The address index reaches below the ledger floor, so an old signature can be listed and still be unreadable. Ask for the newest signature first and treat the answer as expected for old ones. |
| A transaction lookup fails with -32015. | The call lost `maxSupportedTransactionVersion`. Keep it at 1 in the config object, since mainnet carries v1 transactions. |
| Claude Code asks for permission before every call. | Add an allow rule for `mcp__carbium` in your settings. That covers all three tools of the server. |
| Calls start returning 429 in the middle of a long task. | The burst of about 20 lookups is spent and the plan's sustained rate applies, or the account's shared budget is used up. Limit the number of lookups per task, and check what else uses the account's keys. |

## Questions

### Can Claude Code send a transaction through this server?

No. The file has no keypair and its table has no send entry. Carbium itself serves `sendTransaction`, so the table in your file is the control.

### Should I commit `.mcp.json`?

Yes, with the placeholder `${CARBIUM_KEY}` and never the value. Each teammate sets the variable in the environment that starts Claude Code, and Claude Code expands it at launch.

### Why a server when Claude Code can run curl?

A server fixes the methods to the table, while a shell command lets the model pick any method, `sendTransaction` included. Curl can read `$CARBIUM_KEY` from the environment, and the key reaches the transcript only when the model inlines it in the command text. The server keeps the key in its own environment either way.

### Which commitment do the reads use?

All three reads run at confirmed, because none of the three calls sets commitment and kit 8.6.0 fills it in. The JSON-RPC server's own default is finalized. To change it, add `commitment` in the tool's `run` function.

### Where does the key live?

In the server's environment and in the transport header. The default-scope registration also stores its value in Claude Code's config file in your home folder. It appears in no tool argument or result, so your own logging is the only other place it can leak.

## Related

- [Read-only MCP server](https://carbium.sh/library/si/read-only-mcp-server) (AI and blockchain, SI0002)
- [Transaction version error -32015](https://carbium.sh/library/howsolana/transaction-version-error-32015) (How to use Solana, HS0012)
- [carbium.sh/docs#rpc](https://carbium.sh/docs#rpc)
- [carbium.sh/docs#limits](https://carbium.sh/docs#limits)
- [carbium.sh/docs#auth](https://carbium.sh/docs#auth)
- [carbium.sh/docs#errors](https://carbium.sh/docs#errors)
- [carbium.sh/docs#migrate](https://carbium.sh/docs#migrate)
