---
id: SI0077
title: "MCP tool contract tests"
url: https://carbium.sh/library/si/mcp-tool-contract-tests
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 tool contract tests

You get a Node test file for an MCP server's tool handlers. Each case is one of three kinds and asserts how many RPC calls it made. Drift is reported field by field and a failure exits nonzero for CI.

## Three kinds of case

A tool handler makes a promise to the model: this input shape goes in, this output shape comes out, and a bad input is turned away. A refactor can break that promise without changing anything the compiler checks. These tests call the handlers directly, with no client and no stdio, against Carbium RPC, so a repository's CI can run them on every pull request.

Each tool gets three kinds of case, and each kind asserts a transport call count.

| Kind | Input | Passes when | Transport calls |
|---|---|---|---|
| Accept | Valid arguments | The result matches the output schema | 1 per RPC method the tool reads |
| Refuse | Wrong shape, an extra field or an invalid address | The handler throws | 0 |
| Error passthrough | Valid arguments to a method Carbium does not serve | The error is the node's -32601, unchanged | 1 |

The file holds three tools. `get_balance` and `get_slot` take the accept and refuse cases, with a busy program address as the account (the token program unless you pass another). `getTokenLargestAccounts` is [not served](https://carbium.sh/docs/rpc) and answers -32601, so the third tool exists to give the passthrough case a real node error. Replace the `TOOLS` map with imports of your own handlers; the tools of [a read-only MCP server](https://carbium.sh/library/si/read-only-mcp-server) fit the same shape.

## Counting transport calls

The counter sits in the transport that `createSolanaRpcFromTransport` wraps. Every request goes through one function that adds 1 to a number and forwards to the real transport. Each case sets the number to 0 before it runs and reads it after.

A refuse case alone would see only an error, and a handler that forwards a bad argument also ends in an error, because the node turns it away. The count tells the two apart: 0 means the handler stopped the input itself, and 1 means a request was spent on it. In the file, `address()` from kit decodes the string locally, so an invalid address never reaches the transport.

The second mistake is a retry. Retries belong on 429 and network errors, since [a call over its limit gets 429](https://carbium.sh/docs/limits) with a retry-after hint. A method that is not served answers -32601, and [a retry gets the same answer](https://carbium.sh/docs/errors), so the fix is a different method. A retry that fires on every error sends the passthrough call again, the count reaches 2 or more, and the assertion on 1 fails. A retry limited to 429 and network errors leaves the count at 1.

A tool that reads two RPC methods expects 2 in its accept row. Write the number in the case, so adding a call to a handler is a visible edit in the test as well.

## Schema drift, field by field

Each tool declares an input and an output as a map from field name to `typeof` name. `check` compares a value with that map and returns one line per difference: a field of the wrong type, a missing field, or a field the map does not list. `call` joins the lines into the error, so the failure names the tool and every drifted field at once.

Say `get_balance` returns the raw bigint from kit and drops its `String()` conversion. The case prints `get_balance output drifted: lamports: expected string, got bigint`. If the same refactor also adds a `context` field to the result, the line carries a second part after a semicolon naming it. One run shows both problems, so one pass of fixes is enough.

## The test file

Set `CARBIUM_KEY` and run the file. It sends the key in the `x-api-key` header and reads `CARBIUM_RPC_URL` for the endpoint, which defaults to `https://services.carbium.sh`. The first argument overrides the account.

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

```ts
// SI0077 · MCP tool contract tests
// https://carbium.sh/library/si/mcp-tool-contract-tests
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

// MCP tool contract tests. Each case asserts an outcome and a transport call count. Run: CARBIUM_KEY=... node main.ts [address]
import assert from "node:assert/strict";
import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, isSolanaError, SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND } 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 inner = createDefaultRpcTransport({ url, headers: { "x-api-key": key } });
let calls = 0; // every request the RPC client sends passes through here
const counting = <T,>(req: Parameters<typeof inner>[0]) => {
  calls++;
  return inner<T>(req);
};
const rpc = createSolanaRpcFromTransport(counting);

type Fields = Record<string, string>; // field name -> typeof name
type Tool = { input: Fields; output: Fields; run: (a: any) => Promise<unknown> };
const TOOLS: Record<string, Tool> = {
  get_balance: {
    input: { address: "string" },
    output: { lamports: "string" },
    run: async (a) => ({ lamports: String((await rpc.getBalance(address(a.address)).send()).value) }),
  },
  get_slot: { input: {}, output: { slot: "string" }, run: async () => ({ slot: String(await rpc.getSlot().send()) }) },
  get_largest_holders: {
    input: { address: "string" },
    output: { holders: "object" },
    run: async (a) => ({ holders: (await rpc.getTokenLargestAccounts(address(a.address)).send()).value }),
  },
};

const check = (schema: Fields, value: unknown): string[] => {
  const v = (value ?? {}) as Record<string, unknown>;
  const wrong = Object.entries(schema).filter(([k, t]) => typeof v[k] !== t).map(([k, t]) => `${k}: expected ${t}, got ${typeof v[k]}`);
  return [...wrong, ...Object.keys(v).filter((k) => !(k in schema)).map((k) => `${k}: not in schema`)];
};

async function call(name: string, args: Record<string, unknown>) {
  const t = TOOLS[name] as Tool;
  const bad = check(t.input, args);
  if (bad.length) throw new Error(`${name} input refused: ${bad.join("; ")}`);
  const out = await t.run(args);
  const drift = check(t.output, out);
  if (drift.length) throw new Error(`${name} output drifted: ${drift.join("; ")}`);
  return out;
}

const addr = process.argv[2] ?? "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
const cases: [kind: string, tool: string, args: Record<string, unknown>, calls: number][] = [
  ["accept", "get_balance", { address: addr }, 1],
  ["accept", "get_slot", {}, 1],
  ["refuse", "get_balance", {}, 0],
  ["refuse", "get_balance", { address: "not an address" }, 0],
  ["refuse", "get_slot", { address: addr }, 0],
  ["error", "get_largest_holders", { address: addr }, 1],
];

let failed = 0;
for (const [kind, name, args, want] of cases) {
  calls = 0;
  const err = await call(name, args).then(() => undefined, (e: unknown) => e ?? "rejected");
  const msg = err instanceof Error ? err.message : "";
  try {
    if (kind === "accept") assert.equal(err, undefined, msg);
    else assert.ok(err, "expected an error");
    if (kind === "error") assert.ok(isSolanaError(err, SOLANA_ERROR__JSON_RPC__METHOD_NOT_FOUND) || /32601|method not found/i.test(msg), `not a method-not-found error: ${msg}`);
    assert.equal(calls, want, `${calls} transport calls, wanted ${want}`);
    console.log(`ok   ${kind.padEnd(6)} ${name} calls=${calls}`);
  } catch (e) {
    failed++;
    console.log(`FAIL ${kind.padEnd(6)} ${name} calls=${calls}: ${(e as Error).message}`);
  }
}
process.exitCode = failed ? 1 : 0;
```

Each case prints one line, `ok` or `FAIL`, with its kind, tool and call count, and the process exits 1 when any case fails, so a CI step needs no output parsing. A run makes three calls to Carbium, and the `getSlot` one costs 1 cell. `getBalance` and `getSlot` leave commitment out, and kit fills in confirmed. The lamports and the slot change between runs, so the test checks their type and never their value.

## Running it in CI

Add a job that runs `node main.ts` with `CARBIUM_KEY` taken from the repository's secret store. Node 24 runs the TypeScript file directly and `@solana/kit` 8.6.0 is the only package. The file never writes the key to output, and your own log lines should keep it out too.

[Limits are per account](https://carbium.sh/docs/limits): the CI key and every other key on the account draw on one budget. The suite makes three calls and runs its cases in order, which keeps the load small, but a long matrix of jobs adds up.

## Where it ends

- The stdio framing is untested here. The file calls handlers as functions, so a broken newline-delimited message, a log line written to stdout or a wrong `initialize` answer passes every case. Test your server through a client as well: start it as a child process, send `tools/list` and one `tools/call`, and compare the replies.
- The schema compare is simplified: `typeof` names, no nested fields, no ranges. If your server publishes JSON Schema, run its validator in `check` instead.
- Accept cases need the network and a key, so they are integration tests. A 429 or an outage fails them for reasons outside your code; read the message before calling a failure a regression.
- The passthrough case depends on `getTokenLargestAccounts` staying unserved. If that changes, pick another method that answers -32601.
- The counter sees requests through its one transport. A handler that opens its own `fetch` or WebSocket escapes it.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| A refuse case fails with calls=1. | The input reached the network. Put the shape check and `address()` ahead of the RPC call, then rerun; the case should print calls=0. |
| The passthrough case fails with calls=2 or more. | A retry fires on -32601. Limit retries to 429 and network errors, and honor the retry-after hint. |
| The passthrough case fails on the error pattern. | The handler rewrote the node's error into its own text. Pass the node's message through, or keep the code 32601 in it, so the model can tell the method is not served. |
| An accept case fails with `lamports: expected string, got bigint`. | Kit returns lamports and slots as bigint, and JSON has no bigint. Convert with `String()` in the handler before the result leaves it. |
| Every accept case fails with 401. | The key is unknown at the door. Check that the CI secret holds the whole key and that it reaches the job as `CARBIUM_KEY`. |
| Accept cases fail with 429 in CI. | Another key on the account is spending the shared budget, or several jobs run the suite at once. Stagger the jobs or give the suite its own account. |

## Questions

### Why count calls instead of mocking the transport?

A mock proves the handler's logic and nothing about the node's errors. The counter wraps the real transport, so the passthrough case sees a genuine -32601 and the accept cases read live lamports.

### Can I run the cases in parallel?

No. The counter is one number shared by all handlers, so concurrent cases would add to each other. Run them in order; the table is short.

### How do I add a tool that reads two RPC methods?

Add its row to the table and write 2 as the call count in its accept case. A count that differs from the number you wrote means a call was added or dropped.

### Does this replace testing through an MCP client?

No. It covers the handlers and their RPC behavior. Message framing, the handshake and the tool list belong to a second test that starts the server as a client would.

## Related

- [Read-only MCP server](https://carbium.sh/library/si/read-only-mcp-server) (AI and blockchain, SI0002)
- [Webhook-to-RPC fetch retries](https://carbium.sh/library/howsolana/webhook-to-rpc-fetch-retries) (How to use Solana, HS0041)
- [carbium.sh/docs/rpc](https://carbium.sh/docs/rpc)
- [carbium.sh/docs/errors](https://carbium.sh/docs/errors)
- [carbium.sh/docs/limits](https://carbium.sh/docs/limits)
- [carbium.sh/docs/auth](https://carbium.sh/docs/auth)
