library / AI and blockchain / Your own MCP server on Carbium RPC / SI0082
MCP server response cache
You get a small in-memory response cache for your MCP server's RPC reads, keyed by method, params and commitment, with a lifetime per read. The worked case is the latest blockhash, whose own lastValidBlockHeight shows how many blocks it has left.
The kit call
A model that checks the chain asks the same few questions again and again: what is the latest blockhash, how much SOL does a 165-byte account need, which node version answers. Each ask is a request against your account's budget, and limits are per account, so a chatty model spends what your other services need.
The latest blockhash comes from the JSON-RPC method getLatestBlockhash. In @solana/web3.js 1.x you call connection.getLatestBlockhash(). In @solana/kit the same method is rpc.getLatestBlockhash().send(). The reply holds context.slot and a value with blockhash and lastValidBlockHeight, which kit returns as a bigint.
The file passes { commitment: "confirmed" } so the level is written down in the code. Kit fills in confirmed when a call leaves commitment out, and the node's own default is finalized, so a call copied between the two can change level without anyone noticing. Kit sends one request per call and keeps nothing between calls.
The cache key
The cache is a Map from a string to a value and an expiry time. The string is the JSON of the method name, the params and the commitment. Params separate getMinimumBalanceForRentExemption for 165 bytes from the same call for 0 bytes. Commitment separates a confirmed answer from a finalized one, so a caller who asked for finalized never receives a confirmed value from the cache.
Kit takes some params as bigint, and JSON.stringify refuses bigint, so the key function converts them to strings. A method with no commitment, such as getVersion, puts a null in that slot. The key holds the read's inputs and nothing else. Your API key stays in the transport header and never reaches the cache.
A lifetime per read
A lifetime is how long an answer stays true enough for the caller. Set it from what changes the answer, one read at a time.
| Read | What changes it | Lifetime in this file |
|---|---|---|
| getLatestBlockhash | A new block | 2 s, and the answer states its own expiry |
| getMinimumBalanceForRentExemption | A change to the network's rent parameters, which is rare | 10 minutes |
| getVersion | A node upgrade | 10 minutes |
| getBlockHeight | Every block | None. It is the clock the blockhash is judged by |
| getBalance | Any transaction that touches the account | None here. If you add it, keep it well under a second |
The lifetimes are choices for this file. The network publishes none of them. getVersion is a 1-cell read, 5 req/s on Free and 500 on Pro, so caching it saves little budget. It stays in the file as the example of a value that almost never changes, and a rent minimum for a fixed data length behaves the same way.
The cache file
makeCache() returns get and stats. get takes a read (method, params, commitment), a lifetime in milliseconds and a loader function. A live entry returns at once and counts a hit. Otherwise the loader runs, the result is stored and the call counts a miss. A loader that throws stores nothing, so the next call tries again.
// SI0082 · MCP server response cache// https://carbium.sh/library/si/mcp-server-response-cache// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Response cache for MCP server reads. Run: CARBIUM_KEY=... node main.tsimport { createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";type Read = { method: string; params?: unknown[]; commitment?: string };function makeCache() { const store = new Map<string, { value: unknown; until: number }>(); const stats = { hits: 0, misses: 0 }; // Key is method + params + commitment; bigint params become strings so JSON can hold them. const keyOf = (r: Read) => JSON.stringify([r.method, r.params ?? [], r.commitment ?? null], (_k, v) => (typeof v === "bigint" ? String(v) : v)); async function get<T>(read: Read, lifetimeMs: number, load: () => Promise<T>): Promise<T> { const key = keyOf(read); const found = store.get(key); if (found !== undefined && found.until > Date.now()) { stats.hits += 1; return found.value as T; } stats.misses += 1; const value = await load(); // a throw stores nothing store.set(key, { value, until: Date.now() + lifetimeMs }); return value; } return { get, stats };}const apiKey = process.env.CARBIUM_KEY;if (!apiKey) { console.error("Set CARBIUM_KEY to your Carbium API key."); process.exit(1);}const endpoint = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url: endpoint, headers: { "x-api-key": apiKey } }));const cache = makeCache();const pause = (ms: number) => new Promise((done) => setTimeout(done, ms));for (let n = 1; n <= 5; n++) { try { const read = { method: "getLatestBlockhash", commitment: "confirmed" }; const { blockhash, lastValidBlockHeight } = await cache.get(read, 2_000, async () => { const reply = await rpc.getLatestBlockhash({ commitment: "confirmed" }).send(); return reply.value; }); const height = await rpc.getBlockHeight({ commitment: "confirmed" }).send(); console.log(`blockhash call ${n}: ${blockhash.slice(0, 8)}... valid to ${lastValidBlockHeight}, height ${height}, blocks left ${lastValidBlockHeight - height}`); } catch (e) { console.log(`blockhash call ${n} failed:`, (e as Error).message); } await pause(700);}for (let n = 0; n < 2; n++) { try { const rent = await cache.get({ method: "getMinimumBalanceForRentExemption", params: [165n] }, 600_000, () => rpc.getMinimumBalanceForRentExemption(165n).send()); console.log(`rent minimum, 165 bytes: ${rent} lamports`); } catch (e) { console.log("rent minimum failed:", (e as Error).message); } try { const info = await cache.get({ method: "getVersion" }, 600_000, () => rpc.getVersion().send()); console.log("version:", info["solana-core"]); } catch (e) { console.log("version failed:", (e as Error).message); }}console.log(`hits ${cache.stats.hits}, misses ${cache.stats.misses}`);
run: node main.ts
Set CARBIUM_KEY and run it. It makes five blockhash calls 700 ms apart, each next to a getBlockHeight read, then asks for the rent minimum and the version twice each, and ends with the hit and miss totals. Each read sits in its own try, so one failure prints a line and the run goes on.
With a 2 s lifetime and 700 ms gaps, calls 1 and 4 typically miss and the others hit. Request time shifts the exact split. The rent minimum and the version each miss once and hit once.
Expiry by block height
A blockhash is valid for a window of blocks, and lastValidBlockHeight is the last block height at which a transaction naming it can still land. The file subtracts the current getBlockHeight from it and prints the result as blocks left. The number comes from the chain, so the run measures it. Read it on your own account before you size a lifetime.
Slots run about 200 ms since the Alpenglow switch, and block height moves at most once per slot, so a 2 s lifetime uses at most about ten blocks of the window. Skipped slots add no block height, so the real cost is often less. Compare that figure with the blocks left on the first call. When the lifetime takes a small share of the window, 2 s is cheap. Stretch it to minutes and the cached hash may be dead on arrival.
The lifetime governs how fresh a read is. The block count governs whether the hash can still be used. A caller that builds a transaction checks blocks left at the moment of use and asks for a new hash when the margin is thin. A flow with a human approval between building and signing, such as the unsigned transaction handoff, fetches fresh when the approval arrives. This file only reads. Signing and sending belong to another process.
The same pattern fits the rent-exempt minimum behind most account-creation questions, and the read-only MCP server is where this wrapper goes: put each tool's RPC call inside cache.get().
Where it ends
- The cache lives in the server process. A restart empties it, and two server processes each hold their own copy. A stdio MCP server runs once per client, so every client warms its own.
- Two calls that arrive together on a cold key each miss and each reach the RPC. Storing the promise in the map in place of the value closes that gap. The file keeps the plainer form.
- Nothing evicts. The keys here are few. Reads keyed by address grow the map with every address the model asks about, so add a size cap before you cache those.
- A hit hides change. A balance cached for a few seconds can contradict a transfer the model just watched land. Cache only reads whose staleness the caller can tolerate, and put the age in the tool result when the model reasons from it.
- A hit returns the answer at the commitment of the original fetch. The key keeps levels apart, and it cannot tell you how old the fetch was.
- There is no signing and no sending here. A cached blockhash is an input to a transaction someone else builds.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| Building the key throws that a BigInt cannot be serialised. | Kit takes some params, such as a data length, as bigint. The replacer in the key function turns them into strings, so keep it and route every key through it. |
| Every blockhash call misses. | Look at the key. A param that changes per call, such as a timestamp or a request id, makes each key new. Keep only the read's own inputs in it, and check that the lifetime is longer than the gap between calls. |
| A transaction built from a cached blockhash is rejected as expired. | The lifetime outran the blocks left, or a human approval sat between building and signing. Fetch a fresh hash at the moment of use and check blocks left before building. |
| The blocks left figure is negative. | The blockhash is past its window. Fetch a new one, and shorten the lifetime if a cache hit produced the dead hash. |
| The model quotes a balance that a transfer it just watched has already changed. | A hit served the old value. Drop the cache from that read, or give it a lifetime under a second and return the age with the answer. |
Questions
Which function gets the latest blockhash in web3.js?
connection.getLatestBlockhash() in @solana/web3.js 1.x, and rpc.getLatestBlockhash().send() in @solana/kit. Both answer with the blockhash and lastValidBlockHeight.
How long can I cache a blockhash?
Long enough that the blocks it uses stay a small share of its window, and short enough that blocks left is still comfortable when the hash is used. Run the file, read blocks left on your own account and pick from that.
Does a cache hit cost credits?
A hit makes no request, so nothing is metered. Each miss is an ordinary call against the account's shared budget.
Should the model choose the lifetime?
No. The server sets it per read in code. The model asks for a read, and your table decides what a fresh answer means.
Can I cache getBalance the same way?
Yes, with a lifetime well under a second or none. A balance changes with any transaction that touches the account, and an agent that just saw a transfer land expects to see it.