---
id: SI0085
title: "MCP address input validation"
url: https://carbium.sh/library/si/mcp-address-input-validation
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
---

# MCP address input validation

You get two checks to run on every address a model passes to your MCP tool: an offline shape check that costs nothing, and one batched account read for the addresses that pass, with error text the model can act on in its next turn.

## Gate one: the offline check

A model fills a tool argument with whatever looks right in its context. Sometimes that is a transaction signature, a token symbol or an address with a character dropped. If the server forwards the string, the result is a round trip and an error message the model has to interpret. Two gates stop that. The first runs in your process and costs nothing. The second is one read for the addresses that pass the first.

A Solana address is 32 bytes written in base58. That is the whole rule, and it holds in every language. In Dart you decode the string with a base58 package and check that the result is exactly 32 bytes; Python, Go and Rust take the same two steps. The sample is TypeScript for a TypeScript MCP server of your own, and `isAddress` from `@solana/kit` 8.6.0 does both steps. It checks the character count, then decodes and compares the byte count.

`isAddress` returns a boolean and never throws, and it narrows a `string` to the `Address` type. That suits a tool boundary, where the argument arrives as an unknown string and you want to write your own message. `address()` from kit applies the same test and throws, which is fine inside code that already trusts its input.

## Mistakes models make

- A transaction signature. It is 64 bytes, so it encodes to 87 or 88 characters. Length alone catches it, and the message can say what it looks like.
- A name or a sentence. `USDC`, `my wallet` or a whole phrase fails on length or on characters. Resolving names is a separate job.
- The characters 0, O, I and l. Base58 leaves them out so they cannot be mistaken for 1 and for each other. A model that misreads one writes a character that cannot occur in any address.
- Padding. Quotes, spaces or a trailing newline around the address. You can trim, or you can reject. Pick one and tell the model; the sample rejects, so the model learns to send a clean string.
- A cut-off string. Models that copy a long value from a table sometimes drop characters. A string missing four or more characters decodes to too few bytes and fails gate one. A string missing one character often still decodes to 32 bytes and passes, which is why the second gate exists.
- A valid address of the wrong kind, such as a mint where a wallet was wanted. It passes gate one, and gate two shows what it is.

One wrong character in the middle of an address gives a different valid address, and a Solana address carries no checksum, so no offline test can catch a swapped character.

## The code and what it prints

Set `CARBIUM_KEY` and run the file. It builds a list of inputs. Three are fixed: the USDC mint, the System program, and an address made from 32 bytes of the value 7 that nobody holds an account at. The rest come from a wallet found at run time. The file reads the newest three signatures of the System program, fetches the first transaction that comes back and takes its fee payer. That wallet is real and active, and from it the file derives the signature itself, a copy cut by four characters, a copy with a zero in place of its first character and a copy padded with a space and a newline.

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

```ts
// SI0085 · MCP address input validation
// https://carbium.sh/library/si/mcp-address-input-validation
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

// Two-gate address check for MCP tool arguments. Run: CARBIUM_KEY=... node main.ts
import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, getAddressDecoder, isAddress, type Address } 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 url = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";
const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url, headers: { "x-api-key": key } }));

// Gate one, offline: undefined when the shape is right, else a reason the model can act on.
function shapeError(v: string): string | undefined {
  if (isAddress(v)) return undefined;
  if (v !== v.trim()) return "remove the spaces or line breaks around the address";
  if (v.length > 44) return `${v.length} characters; an address has 32 to 44 (87 or 88 is a transaction signature)`;
  const bad = v.match(/[^1-9A-HJ-NP-Za-km-z]/g);
  if (bad) return `contains ${[...new Set(bad)].map((c) => JSON.stringify(c)).join(" ")}; base58 has no 0, O, I or l`;
  if (v.length < 32) return `${v.length} characters; an address has 32 to 44, so it is cut off`;
  return "decodes to the wrong number of bytes; it is probably truncated or edited";
}

// Test input only: the fee payer of a recent System program transaction is a live wallet.
async function findWallet() {
  const sigs = await rpc.getSignaturesForAddress(address("11111111111111111111111111111111"), { limit: 3 }).send();
  for (const { signature } of sigs) {
    const tx: any = await rpc.getTransaction(signature, { encoding: "jsonParsed", maxSupportedTransactionVersion: 1 }).send().catch(() => null);
    const wallet = tx?.transaction?.message?.accountKeys?.[0]?.pubkey;
    if (typeof wallet === "string") return { wallet, signature: String(signature) };
  }
  return undefined;
}

const found = await findWallet().catch((e) => {
  console.error("wallet lookup failed:", e.message);
  return undefined;
});
const inputs: [string, string][] = [
  ["USDC mint", "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"],
  ["System program", "11111111111111111111111111111111"],
  ["unused address", getAddressDecoder().decode(new Uint8Array(32).fill(7))],
  ["a sentence", "the wallet I mean"],
];
if (found) {
  const { wallet, signature } = found;
  inputs.push(["fee payer", wallet], ["its signature", signature], ["cut by 4 characters", wallet.slice(0, -4)]);
  inputs.push(["zero for first char", "0" + wallet.slice(1)], ["padded", ` ${wallet}\n`]);
} else console.log("no wallet found, fixed inputs only");

// Gate two: one read for everything that passed gate one, at most 100 pubkeys a call.
const ok: Address[] = [];
for (const [, v] of inputs) if (isAddress(v) && !ok.includes(v)) ok.push(v);
const batch = ok.slice(0, 100);
const accounts = new Map<string, { owner: string; bytes: number } | null>();
try {
  const { value } = await rpc.getMultipleAccounts(batch, { encoding: "base64" }).send();
  batch.forEach((a, i) => {
    const acc = value[i];
    accounts.set(a, acc ? { owner: acc.owner, bytes: Buffer.from(acc.data[0], "base64").length } : null);
  });
} catch (e) {
  console.error("getMultipleAccounts failed:", (e as Error).message);
}

for (const [label, v] of inputs) {
  const why = shapeError(v);
  const acc = accounts.get(v);
  const verdict = why ? `REJECT ${why}` : acc === undefined ? "valid, existence not checked" : acc === null ? "valid, no account" : `valid, owner ${acc.owner}, ${acc.bytes} bytes`;
  console.log(`${label.padEnd(22)} ${verdict}`);
}
```

`getTransaction` takes `maxSupportedTransactionVersion: 1`, because mainnet carries v1 transactions and a lower value answers -32015 for them. It can also return null for an older signature, so the loop moves to the next one. Each line of output names the input and gives the verdict: a rejection with its reason, or a valid address with its owner and data size, or the words `valid, no account`. A plain wallet shows the System program as owner and 0 bytes. The USDC mint shows the Token program as owner and 82 bytes. The address built from sevens has no account.

## Gate two: does the account exist

A valid address says nothing about whether an account sits at it. Most 32-byte values are addresses nobody holds a key for, and a wallet that has never received SOL has no account. `getMultipleAccounts` answers null in that slot. Treat null as a result. The address is valid, and at confirmed commitment, the level kit fills in when a call leaves it out, nothing is stored there. A model told `invalid address` for a fresh wallet goes looking for a different one, which is the wrong next step.

One call covers the batch. `getMultipleAccounts` takes a list of pubkeys and answers in the same order. It charges 10 cells per pubkey, so 100 pubkeys cost 1000 cells. The code never sends more than 100 in a call: a rate class absorbs a burst of 1,024 cells, which caps a call at 100 pubkeys below Pro, and the 300-pubkey call is Pro's. A tool that receives a longer list from the model should answer with an error asking for fewer, before any request leaves your process.

| Plan | Account reads per second |
|---|---|
| Free | 0.5 |
| Dev | 15 |
| Business | 50 |
| Pro | 400 |

[Limits are per account](https://carbium.sh/docs/limits), so every key on the account draws from one budget. A model that validates in a loop reaches the Free ceiling quickly. Validate each list once per task and keep the verdicts.

The owner field tells you what the address is:

- The System program, `11111111111111111111111111111111`: a wallet. Data size is 0.
- The Token program, `TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA`: a mint (82 bytes) or a token account (165 bytes). The Token-2022 program owns its own variants, which grow with their extensions.
- Null: no account at that address.
- Any other owner: an account that program controls, with a layout only that program defines.

The [address type explainer](https://carbium.sh/library/si/address-type-explainer) turns that table into plain English for the model, and the [send recipient preflight](https://carbium.sh/library/usecase/send-recipient-preflight) applies the same two gates before a payment.

## Error wording for the model

The model reads your message and tries again, so the message is the interface. Say what was received, what is wrong with it and what a correct value looks like. `invalid address` makes the model guess. `88 characters; an address has 32 to 44 (87 or 88 is a transaction signature)` tells it which value it passed and that it should pass the wallet instead. Return the text as a tool result with `isError` set, the way the [read-only MCP server](https://carbium.sh/library/si/read-only-mcp-server) does, so it reaches the model as plain text.

- Name the problem once. A string with a space and a wrong length gets the first problem found, in a fixed order, so the model fixes one thing per turn.
- Give the next step. `remove the spaces or line breaks around the address` can be acted on; `bad input` cannot.
- Keep the existence message separate from the shape message. `valid address, but no account exists at it` tells the model to ask the user to confirm the address, where a shape error tells it to fix the string.
- Keep the key and any internal URL out of the message, because the model may quote it back to the user.

## Where it ends

- Shape and existence only. A wrong character in a pasted address gives another valid address, and if an account exists there both gates pass. Confirm the address with the user before anything depends on it.
- Off-curve addresses are valid. Program derived addresses are off the ed25519 curve by design, so an on-curve test would refuse addresses you want. The file does not test for it.
- A fresh wallet reads as no account until its first transfer lands. The verdict is a snapshot at confirmed commitment, and the same address can read differently a minute later.
- Names such as `.sol` domains are not resolved. The tool accepts the 32-byte form only.
- The wallet finder in the sample spends a `getSignaturesForAddress` call (50 cells) and up to three `getTransaction` calls (50 cells each) to build test input. The tool in your server needs none of them. The finder also depends on the 30-day address index and on the newest signatures being readable.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| A wallet the user says is funded reads as `valid, no account`. | Compare the string with what the user gave. A one-character slip still decodes to a valid address with no account. If the string matches, read again, since a first transfer may have landed after the earlier read. |
| The model keeps sending a transaction signature as the address. | Put the length and the word signature in the message, and say which tool takes a signature. A message that only says invalid sends it round again. |
| A batch of 100 addresses gets a 429 on a Free key. | The call spends 1001 of the 1,024 burst cells, and Free account reads run at 0.5 req/s, so a second call straight after has to wait for the retry-after hint. Cut the batch or space the calls. |
| A mint passes both gates in a tool that wants a wallet. | Check `owner` and data size in the tool. A wallet is owned by the System program; reply with what the account is, such as a token mint, so the model asks again. |
| The sample prints that it found no wallet. | `getTransaction` can answer null for a signature it cannot serve, or a call can be refused for rate. Run it again; the fixed inputs still print. |

## Questions

### How do I validate a Solana address in Dart?

Decode the string with a base58 package and check that the result is exactly 32 bytes, after checking that the string is 32 to 44 characters long. The rule is the same in every language, so both gates carry over to a server written in Dart.

### Does isAddress check that the account exists?

No. It checks that the string decodes to 32 bytes and says nothing about the chain. Existence needs a read such as `getMultipleAccounts`.

### Should the tool trim whitespace or reject it?

Either works if you choose one. Trimming accepts a pasted newline without comment. Rejecting with a clear message teaches the model to send a clean value, which is what the sample does.

### Is an address with no account an error?

No. It is valid and it is what a fresh wallet looks like. Return it as not found in the result text; the model picks the next call, or asks the user which address was meant.

### Can I check many addresses at once?

Yes. Send up to 100 pubkeys per `getMultipleAccounts` call below Pro, at 10 cells each. A Pro plan takes up to 300.

## Related

- [Address type explainer](https://carbium.sh/library/si/address-type-explainer) (AI and blockchain, SI0031)
- [Send recipient preflight](https://carbium.sh/library/usecase/send-recipient-preflight) (Use cases, UC0061)
- [carbium.sh/docs/rpc](https://carbium.sh/docs/rpc)
- [carbium.sh/docs/limits](https://carbium.sh/docs/limits)
- [carbium.sh/docs/errors](https://carbium.sh/docs/errors)
- [carbium.sh/docs/auth](https://carbium.sh/docs/auth)
