---
id: SI0002
title: "Read-only MCP server"
url: https://carbium.sh/library/si/read-only-mcp-server
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
---

# Read-only MCP server

You get a Solana MCP server in one file that any MCP client can start over stdio. It exposes four read-only tools on Carbium RPC through a fixed method table, returns trimmed answers, and reports failures as tool results the model can read.

## What an MCP client expects

An MCP client, usually an app that hosts a model, starts your server as a child process and talks to it over stdin and stdout. Each message is one line of JSON-RPC 2.0. The client sends `initialize`, then a `notifications/initialized` notice that needs no reply, then `tools/list` to learn what exists, and `tools/call` each time the model picks a tool.

The server implements exactly that, plus `ping`. A tool result is a `content` array of text items. A failure inside a tool comes back as a normal result with `isError` set, so the model can read what went wrong. A call to a tool that does not exist is a protocol error with code -32602, and an unknown method gets -32601, JSON-RPC's method not found.

## The server file

One file. Node 24 runs the TypeScript directly, and the only dependency is `@solana/kit` 8.6.0. Set `CARBIUM_KEY` first; the file exits with a message when it is missing. `CARBIUM_RPC_URL` overrides the endpoint, which defaults to `https://services.carbium.sh`. The server holds the key, so the client and the model never see it.

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

```ts
// SI0002 · Read-only MCP server
// https://carbium.sh/library/si/read-only-mcp-server
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

// Read-only MCP server over stdio. Run: CARBIUM_KEY=... node main.ts   Check: node main.ts --demo [address]
import { address, 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 } }));

const one = { type: "object", properties: { address: { type: "string", description: "Base58 address" } }, required: ["address"], additionalProperties: false };
type Tool = { description: string; schema: object; run: (a: string) => Promise<unknown> };

// The model picks a name from this table. It never supplies a method, and no entry sends or signs.
const TOOLS: Record<string, Tool> = {
  get_slot: { description: "Current slot at confirmed commitment.", schema: { type: "object", properties: {} }, run: () => rpc.getSlot().send() },
  get_account_info: {
    description: "Lamports (1 SOL is 1,000,000,000), owner, executable flag and data length of one account.",
    schema: one,
    run: async (a) => {
      const { value } = await rpc.getAccountInfo(address(a), { encoding: "base64" }).send();
      if (!value) return "account not found";
      return { lamports: value.lamports, owner: value.owner, executable: value.executable, dataLength: Buffer.from(value.data[0], "base64").length };
    },
  },
  get_token_balance: {
    description: "Balance of one SPL token account (not a wallet or a mint).",
    schema: one,
    run: async (a) => {
      const { amount, decimals, uiAmountString } = (await rpc.getTokenAccountBalance(address(a)).send()).value;
      return { uiAmountString, decimals, amount };
    },
  },
  get_signatures: {
    description: "The 5 newest signatures of an address, within the last 30 days.",
    schema: one,
    run: async (a) => (await rpc.getSignaturesForAddress(address(a), { limit: 5 }).send()).map(({ signature, slot, err, confirmationStatus }) => ({ signature, slot, err, confirmationStatus })),
  },
};

const text = (v: unknown) => JSON.stringify(v, (_k, x) => (typeof x === "bigint" ? x.toString() : x));

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

if (process.argv[2] === "--demo") {
  const mint = process.argv[3] ?? "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
  const call = (id: number, name: string, args: object = {}) => ({ jsonrpc: "2.0", id, method: "tools/call", params: { name, arguments: args } });
  const requests = [
    { jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18" } },
    { jsonrpc: "2.0", method: "notifications/initialized" },
    { jsonrpc: "2.0", id: 2, method: "tools/list" },
    call(3, "get_account_info", { address: mint }),
    call(4, "get_slot"),
    call(5, "send_transaction"),
  ];
  for (const r of requests) console.log(text((await handle(r)) ?? "no reply (notification)"));
} 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
  }
}
```

`node main.ts --demo` pushes six messages through the same handler a client reaches: the handshake, the tool list, an account read on the USDC mint (pass another address second to read that one), a slot read and a call to `send_transaction`. The last one gets -32602 from the table with no request sent. For the mint, `owner` is the token program and `dataLength` is 82. Without the flag the file reads one request per line from stdin until the client closes it, and writes one reply per line to stdout.

## Keeping it read-only

The model sends a tool name and an address. It never sends a method. `TOOLS` maps each name to one function that calls one fixed RPC method, and `Object.hasOwn` refuses anything else, so `send_transaction` and an inherited name such as `constructor` both stop before any request goes out.

The endpoint does not do this for you. Carbium serves `sendTransaction` (20 cells without preflight, 70 with it), so to the door a send is a normal call. Some read methods are not served, `getTokenLargestAccounts` among them, and answer -32601: method not found, do not retry. The read-only rule has to live in your own file, in the `TOOLS` table.

The file has no keypair, no signing import and no send method. Adding a method means adding an entry, and reviewing that entry is the whole review. `address()` from kit checks that the argument decodes to a valid address before the call, so a sentence or a URL never reaches the RPC params.

## Results and errors

- `get_account_info` returns `lamports`, `owner`, `executable` and the byte length of `data`. The bytes stay out of the model's context. The description states that 1 SOL is 1,000,000,000 lamports, because a model handed a raw count sometimes places the decimal point wrong.
- `get_token_balance` returns `uiAmountString`, `decimals` and the raw `amount`, in that order. It reads a token account only. A wallet or mint address comes back as the node's error.
- `get_signatures` returns the five newest signatures with `slot`, `err` and `confirmationStatus`. It leaves memos out, since a memo is text a stranger wrote.
- `get_slot` returns the slot number. JSON has no bigint, so the `text` helper turns bigint values into strings.

A tool that throws becomes a result with `isError: true` and the message as text. That covers a malformed address, a token read on the wrong kind of account and a 429, whose HTTP status shows in the error text. The file does not retry. The model's next call is the retry, and the client decides when it goes.

## Cost and limits

| Tool | RPC method | Cells per call | Req/s on Free, Dev, Business, Pro |
|---|---|---|---|
| `get_slot` | `getSlot` | 1 | 5, 30, 100, 500 |
| `get_account_info` | `getAccountInfo` | 10 | 0.5, 15, 50, 400 |
| `get_token_balance` | `getTokenAccountBalance` | 10 | 0.5, 15, 50, 400 |
| `get_signatures` | `getSignaturesForAddress` | 50 | 0.24, 1.2, 100, 500 |

[Limits are per account](https://carbium.sh/docs#limits) and an account's keys share one budget, so another service on the same account can spend what the model needs. On Free an account read has a ceiling of 0.5 req/s, one read every 2 s, so a model that chains reads reaches it quickly. The server does not count calls. Put a cap per task in the client's loop.

## Wiring it to a client

Register the file in your MCP client as a stdio server: command `node`, arguments the absolute path to `main.ts`, and `CARBIUM_KEY` in the server's `env` block. Config syntax differs between clients, and those three values are the same in all of them. Check in order: run `--demo` and read the replies, start the server from the client and see the four tool names listed, then ask the model for the current slot.

> Everything on stdout must be a protocol message. A stray `console.log` in the file breaks the client's parser, so write diagnostics to stderr and never print the key.

The [read-only tool entry](https://carbium.sh/library/si/read-only-model-tools) shows the same allowlist idea for a model API's own tool loop, and the [SPL token balance entry](https://carbium.sh/library/howsolana/spl-token-balance) covers the token balance read in detail.

## Where it ends

- Tools only. There are no resources, prompts or server notifications. A watch tool would sit on a WebSocket subscription such as `logsSubscribe`, which this file does not open.
- The protocol side is a hand-written subset. The server answers `initialize` with whatever version the client asked for and checks no argument beyond `address()`. An MCP SDK covers version negotiation, schema validation and other transports; move to one when you need them.
- `getSignaturesForAddress` on Carbium reaches back 30 days at most, from its own address index. An empty page past that marks the index's 30-day limit, and the address may hold older transactions. The tool returns one page of five and does not page.
- The file returns numbers, addresses and signatures. A tool that returns token names or memos hands strangers' text to the model and needs that text treated as untrusted input.
- There is no signing here. A tool that spends needs its own design, a separate process and a human approval step.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| The client reports a broken connection or a parse error right after you add a log line. | Stdout carries the protocol. Move the log to `console.error`, which goes to stderr, and keep the key out of it. |
| `get_token_balance` returns an error for a wallet or mint address. | It reads a token account only, and the description says so. Pass the token account's own address; the error text comes back as an `isError` result. |
| Tool calls start failing with 429 after a few turns. | Cap tool calls per task in the client's loop, and check whether other keys on the same account spend the shared budget. |
| The model asks for a tool that is not in the table, such as `send_transaction`. | The server answers -32602 and sends no request. Leave it out of `TOOLS`; a tool that spends belongs in a separate process. |
| Serialising a result throws that a BigInt cannot be serialised. | Slots and lamports arrive from kit as bigint. Send every result through the `text` helper, whose replacer turns them into strings. |
| `get_signatures` returns an empty list for an address you know is old. | The address index keeps up to 30 days. An empty page past that is the index's limit, so read older activity from your own records. |

## Questions

### Do I need an MCP SDK to run this?

No. A tools-only server needs five message types, and the file handles them in about thirty lines. An SDK pays off when you add version negotiation, input schemas it validates for you, or a transport other than stdio.

### Can the model move funds through this server?

No. The file has no keypair and no signing code, and its table holds no send method. Carbium serves `sendTransaction`, so the table in your file is what stops it.

### How do I add a tool?

Add an entry to `TOOLS` with a description, an input schema and a function that makes one read-only call. Cached reads such as `getSlot` cost 1 cell, account reads 10 and `getSignaturesForAddress` 50.

### Can the key reach the model?

The key lives in the transport's header and in the server's environment. It appears in no tool argument or result. Your own logging is the one place it could leak, so keep it out.

## 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#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#endpoints](https://carbium.sh/docs#endpoints)
- [carbium.sh/docs#migrate](https://carbium.sh/docs#migrate)
- [carbium.sh/docs#websocket](https://carbium.sh/docs#websocket)
