How to Build Your Own MCP Server: Safe, Read-Only Tools for AI Models
An MCP server is a small, typed API for a model, and the hard part is deciding what not to expose. This guide builds a read-only Solana data server and locks it down.
By OnChain Team11 min read
An MCP (Model Context Protocol) server is a program that lists a handful of typed tools and runs them when an AI client asks. Build one when you want several clients, such as Claude Code, an IDE or your own agent, to reach the same data without each team writing its own glue. The protocol is the easy part: a working server is about 20 lines. The work is in the decisions around it, which tools to expose, which inputs to refuse and who is allowed to call it. This guide builds a read-only Solana data server in TypeScript, runs it over stdio and HTTP, and adds the guardrails.
When an MCP server is the wrong tool
If one application talks to one model, you do not need MCP. A plain function tool in your own agent loop, like the one in our on-chain assistant guide, is simpler, faster and easier to test. MCP earns its keep when the tool should outlive any one client: the same server serving a desktop assistant today and a different agent framework next quarter.
It also moves a trust boundary. The model and its host application decide when your tools run, and you decide what they can reach. The spec itself says servers must validate all tool inputs, apply access controls, rate limit calls and sanitise outputs, according to the tools section of the specification. Treat the server as a public API whose caller is unusually creative.
How the pieces fit
Main flowSecondaryFailure pathSwipe to see the whole diagram →
The client lists your tools, the model picks one, and the client sends a tools/call request. Your server answers with content, or with a tool error the model can read and react to. Nothing else about your infrastructure is visible to the model.
One version note, because most tutorials you will find are older. The current protocol revision is 2026-07-28. Its Streamable HTTP transport has no protocol-level sessions and no standalone GET stream: every message is its own POST to a single endpoint, per the transport spec. Examples built around Mcp-Session-Id and per-session transport maps describe the previous revisions. We checked the packages on 17 November 2026: @modelcontextprotocol/server was at 2.4.0 and the older @modelcontextprotocol/sdk still at 1.x. Pin the major version, because this API is still moving.
Step 1: Decide the tools before writing code
A tool list is a prompt. The model reads every name and description on every request, so a long list costs tokens and makes wrong picks more likely. Our rules:
- Few, narrow, read-only. Three tools that each answer one question beat one
rpc_calltool that forwards anything. - Named for the question, not the endpoint.
get_sol_balance, notgetBalance. - Bounded output. Every list has a hard maximum. A model asking for "all transactions" should get 20 and a note, not 40,000 rows into its context window.
- Writes are a separate decision. Anything that moves funds or changes state belongs behind a human approval step in the client, and we would not put it in the first version.
Our example exposes three tools: a SOL balance, a token supply and a list of recent signatures.
Step 2: Set up the project
npm init -y && npm pkg set type=module
npm install @modelcontextprotocol/server@2 @modelcontextprotocol/node@2 \
@modelcontextprotocol/express@2 express zod@4
npm install -D typescript tsx @types/node @types/express
export RPC_URL=... # your Solana RPC endpoint, never hard-codedThe server package holds McpServer and the stdio transport. The node and express packages are thin adapters for HTTP. Tool schemas use Standard Schema, so Zod 4 works directly, as the SDK documentation shows.
Step 3: Wrap the data source defensively
The model should never choose an RPC method or a URL. Put a small function between your tools and the node that allows three methods, sets a timeout and turns every failure into an Error with a readable message.
const ALLOWED = new Set(["getBalance", "getTokenSupply", "getSignaturesForAddress"]);
export async function rpc<T>(method: string, params: unknown[]): Promise<T> {
if (!ALLOWED.has(method)) throw new Error(`RPC method ${method} is not allowed`);
const res = await fetch(process.env.RPC_URL!, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
signal: AbortSignal.timeout(5_000), // never let a slow node hang the agent
});
if (!res.ok) throw new Error(`RPC returned HTTP ${res.status}`);
const body = (await res.json()) as { result?: T; error?: { message: string } };
if (body.error) throw new Error(body.error.message);
return body.result as T;
}The allow-list looks redundant, since only your own code calls rpc. It is a tripwire for the day someone adds a tool in a hurry.
Step 4: Register typed tools
Each tool gets a name, a description written for a model, an input schema and, where the result has a stable shape, an output schema. Describe when to use the tool, not how it works inside.
import { McpServer } from "@modelcontextprotocol/server";
import * as z from "zod/v4";
import { rpc } from "./rpc.js";
// base58, 32 to 44 characters: rejects anything that is not an address
const Address = z
.string()
.regex(/^[1-9A-HJ-NP-Za-km-z]{32,44}$/)
.describe("A Solana address in base58, for example a wallet or token mint");
const readOnly = { readOnlyHint: true, openWorldHint: true } as const;
export function createServer() {
const server = new McpServer({ name: "chain-reader", version: "1.0.0" });
server.registerTool(
"get_sol_balance",
{
title: "SOL balance",
description:
"Current SOL balance of one wallet, in SOL. Use for 'how much SOL does X hold'.",
inputSchema: z.object({ wallet: Address }),
outputSchema: z.object({ wallet: z.string(), sol: z.number() }),
annotations: readOnly,
},
async ({ wallet }) => {
const { value } = await rpc<{ value: number }>("getBalance", [wallet]);
const out = { wallet, sol: value / 1e9 }; // lamports to SOL
return {
content: [{ type: "text", text: JSON.stringify(out) }],
structuredContent: out,
};
},
);
// ...the other two tools, and `return server`, follow belowThree details matter here. First, the SDK validates arguments against the schema before your handler runs, so a malformed address never reaches the RPC call. Second, structuredContent must match outputSchema, and the spec recommends also returning the same JSON as a text block for older clients (see structured content). Third, annotations such as readOnlyHint are hints, and the spec tells clients to treat them as untrusted unless the server is trusted. They help a well-behaved client decide when to skip a confirmation prompt, but they enforce nothing. Real enforcement is the read-only code behind them.
Step 5: Return failures the model can act on
MCP separates two kinds of error. Protocol errors, such as an unknown tool, are for problems the model is unlikely to fix. Tool execution errors, returned with isError: true, carry text the model can read, adjust its next call and retry, as the error handling section describes. Use the second kind for everything a caller could plausibly correct.
server.registerTool(
"get_token_supply",
{
title: "Token supply",
description: "Total supply of an SPL token, given its mint address.",
inputSchema: z.object({ mint: Address }),
annotations: readOnly,
},
async ({ mint }) => {
try {
const { value } = await rpc<{
value: { uiAmountString: string; decimals: number };
}>("getTokenSupply", [mint]);
const text = `Supply: ${value.uiAmountString} (${value.decimals} decimals)`;
return { content: [{ type: "text", text }] };
} catch (err) {
// a failure the model can read and react to, not a crashed call
const hint = "Check that this is a token mint, not a wallet.";
const text = `Lookup failed: ${(err as Error).message}. ${hint}`;
return { content: [{ type: "text", text }], isError: true };
}
},
);The third tool, recent_signatures, follows the same pattern with limit: z.number().int().min(1).max(20).default(10) in its schema. The cap lives in the schema, so the model sees it in the tool list and the server enforces it.
In our test run, a call with wallet: "drop table" never reached the handler. The SDK returned an isError result with the message Input validation error: Invalid arguments for tool get_sol_balance: wallet: Invalid string: must match pattern, which is exactly what a model needs to correct itself.
Step 6: Serve it over stdio first
Stdio is the simplest transport: the client launches your server as a child process and talks over standard input and output. Never write logs to stdout, because stdout is the protocol channel. Use console.error.
import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
import { createServer } from "./tools.js";
await createServer().connect(new StdioServerTransport());Stdio fits a server that one person runs on their own machine with their own credentials. It does not fit a team: every user would need your RPC key and your code installed locally.
Step 7: Serve it over HTTP, with auth
For shared use, run the server over Streamable HTTP behind a single /mcp endpoint. The transport spec says servers must validate the Origin header to prevent DNS rebinding, should bind to localhost when running locally, and should authenticate every connection. The Express helper does the first two by default.
import { createMcpExpressApp, requireBearerAuth } from "@modelcontextprotocol/express";
import { toNodeHandler } from "@modelcontextprotocol/node";
import {
createMcpHandler,
OAuthError,
OAuthErrorCode,
} from "@modelcontextprotocol/server";
import { createServer } from "./tools.js";
// a fresh server per request: nothing is shared between callers
const handler = toNodeHandler(createMcpHandler(() => createServer()));
const auth = requireBearerAuth({
verifier: {
async verifyAccessToken(token) {
if (token !== process.env.MCP_TOKEN) {
throw new OAuthError(OAuthErrorCode.InvalidToken, "Unknown token");
}
return {
token,
clientId: "internal",
scopes: ["read"],
expiresAt: Math.floor(Date.now() / 1000) + 3600, // a missing expiry is rejected
};
},
},
});
const app = createMcpExpressApp(); // binds to 127.0.0.1, validates Host and Origin
app.all("/mcp", auth, (req, res) => void handler(req, res, req.body));
app.listen(3000, "127.0.0.1");We ran this against a stub RPC node and checked the failure paths. A request without a token got 401 with a WWW-Authenticate: Bearer challenge. A request carrying Origin: https://evil.example got 403. A correct call returned the balance as both text and structuredContent.
The single static token is fine for a first internal deployment and nothing more. For anything user-facing, replace the verifier with real OAuth token validation, as the SDK authorization guide describes, and read the caller from ctx.http.authInfo inside handlers to apply per-user limits. If you bind to 0.0.0.0 instead of localhost, list your public hostnames in allowedHosts, or the default Host check no longer protects you. Servers that must also support older clients need a compatibility path, covered in the SDK's legacy clients page.
Step 8: Test it without a model
Do not debug a server through a chat window. The MCP Inspector has a command-line mode that lists tools and calls them directly, and it needs a recent Node (22.23.4 or later at the time of writing).
# list the tools your server advertises
npx @modelcontextprotocol/inspector --cli npx tsx src/stdio.ts --method tools/list
# call one, with a deliberately bad argument
npx @modelcontextprotocol/inspector --cli npx tsx src/stdio.ts \
--method tools/call --tool-name get_sol_balance --tool-arg wallet=nopeRun the second command in CI. A server whose validation errors stop being readable is a regression you want to catch before a model does. For unit tests, the SDK also offers an in-memory transport that links a client and a server in one process, though its docs note that it covers only the 2025-era protocol, so use the handler's fetch path to cover 2026-07-28 behaviour.
Step 9: Connect a client
Claude Code adds a local stdio server with one command, and a remote one with --transport http plus a header, per its MCP documentation.
# local, launched as a child process
claude mcp add --env RPC_URL=$RPC_URL --transport stdio chain-reader \
-- npx tsx /path/to/src/stdio.ts
# shared, over HTTP with a bearer token
claude mcp add --transport http chain-reader https://mcp.example.com/mcp \
--header "Authorization: Bearer $MCP_TOKEN"Ask something like "How much SOL does this wallet hold?" and watch the tool call in the client. The client shows you the arguments before it sends them, which is the human-in-the-loop check the spec asks hosts to provide.
The part nobody puts in the demo: tool output is untrusted
Your tools read data written by strangers. A token name, a transaction memo or an account label can contain text addressed to the model, such as an instruction to ignore its previous task. Claude Code's MCP documentation warns that servers that fetch external content can expose users to prompt injection.
The mitigations are unglamorous. Return structured fields instead of raw text where you can. Cap and strip free-text fields you do not need. Keep the server read-only, so an injected instruction has nothing destructive to call. And if you later add a write tool, make the client require approval for it. A read-only server cannot be talked into moving money, which is the strongest argument for starting there.
What we would do
Start with stdio and three read-only tools, and spend the effort on the descriptions and the input schemas rather than on the transport. Move to HTTP only when a second person needs the server, and put auth in front of it on day one, not after the demo. Log every call with the caller, tool and arguments, because that log is how you find out what the model actually does with your tools. Keep a short list of real prompts and the tool calls you expect, and rerun it whenever you change a description, since a rewording can change which tool the model picks.
If you need a server like this over your own data, or an agent on top of it, that is the work in our AI development service.
Key takeaways:
- Expose questions, not endpoints.
- Validate in the schema, and return errors the model can read.
- Read-only first; writes need a human approval step.
- Treat everything a tool returns as untrusted input.