A single Rust binary with 4 tools, an SQLite FTS5 OpenAPI index and a Rhai sandbox to connect Notion, GitHub, Vercel and Supabase without dumping full schemas into the prompt
Published: November 7, 2026
Reading time: 11 min
Keywords: mcp code mode, reduce mcp tokens, cloudflare code mode, mcp rust
Before you type a single word in Claude Code, Codex, or Cursor, every connected MCP server dumps its entire tool catalog into the context window. I measured that upfront cost across the official servers on November 7, 2026 using tiktoken-rs (o200k_base): 57,436 tokens in github-mcp-server (46 tools), 17,500 tokens in Notion MCP (24 tools), and 8,036 tokens in Supabase MCP (36 tools). That is 82,972 tokens spent advertising 106 tools before you even ask a question.
My fix was to build mcp-code-mode: a single Rust binary that loads OpenAPI specs across multiple services and always exposes the same 4 tools (list_apis, search, describe, and execute), totaling 355 tokens in tool definitions. Instead of calling one tool per endpoint and feeding every intermediate JSON body back into the model's context window, the agent searches for the operation signature, writes a short Rhai script, and receives only the value of the final expression.
let found = search(#{ query: "Launch plan" });
let parent_id = found.results[0].id;
let page = create_page(#{
parent: #{ page_id: parent_id },
properties: #{
title: #{
title: [#{ type: "text", text: #{ content: "Launch checklist" } }]
}
}
});
let edited = update_page(#{
page_id: page.id,
properties: #{
title: #{
title: [#{ type: "text", text: #{ content: "Launch checklist (edited)" } }]
}
}
});
#{ page_id: edited.id, hits: found.results.len() }
The only thing that re-enters the conversation context is {"hits":1,"page_id":"..."}. The raw HTTP payloads from /v1/search and /v1/pages stay inside the sandbox and are discarded when the script finishes.
o200k_base tokens in tools/list alone; mcp-code-mode's 4 tools take 355 tokens.When an MCP client starts a session, it sends initialize and immediately requests tools/list. The server replies with a JSON array containing the name, description, and full input JSON Schema for every operation. That array sits in the model's context window so it knows which functions exist.
To measure the exact footprint without guessing, I built a token receipt generator into the repository (cargo run --bin token-receipt -- RECEIPT.md). It spawns the published official server binaries over stdio, captures the exact result.tools bytes without re-serializing them, and counts tokens with tiktoken-rs 0.6.0 using o200k_base (the GPT-4o / o-series encoding; these are not Claude tokenizer counts).
| MCP Server | Measured version | Tools in tools/list | Bytes | Tokens (o200k_base) |
|---|---|---|---|---|
github/github-mcp-server (default stdio) | 2.1.0 | 46 | 126,635 | 57,436 |
@notionhq/notion-mcp-server | 2.6.1 | 24 | 76,215 | 17,500 |
@supabase/mcp-server-supabase | 0.16.1 | 36 | 33,130 | 8,036 |
mcp.vercel.com (hosted OAuth) | n/a | unmeasured | n/a | unmeasured |
mcp-code-mode (with all 4 adapters loaded) | 0.1.0 | 4 | 1,647 | 355 |
Vercel's official server is a hosted OAuth endpoint (https://mcp.vercel.com), so I recorded its tools/list payload as unmeasured in the receipt rather than substituting a third-party npm package or guessing a number. For the other three, the captured raw payloads and their SHA-256 hashes are committed under fixtures/ in the repository.
Looking at individual tools inside Notion MCP 2.6.1 shows where the weight comes from: a single tool definition like API-update-page-markdown takes 1,282 tokens (5,862 bytes), and API-post-search takes another 1,097 tokens. You pay that toll even when you open your editor just to run a local unit test or edit a React component.
And tool definitions are only the first half of the bill. The second half shows up once the agent starts working: in a task that chains five API calls, the model takes five round-trips. On every turn, the full HTTP response JSON is appended to the conversation history and re-sent on every subsequent message.
In September 2025, Cloudflare published Code Mode: the better way to use MCP. Their argument starts from a plain observation about how LLMs work: language models train on millions of lines of real source code, whereas they only see synthetic tool calls during fine-tuning. When you turn every REST endpoint into a separate tool, you force the model to program in JSON across multiple conversation turns, using an interface it is worse at and that costs far more tokens.
Think of the difference between asking for records at a counter that only accepts one paper form at a time versus walking into a reading room with a notebook. In classic MCP, to find a page ID, create a child page, and update a database, the agent submits one form, receives an entire folder of metadata back, reads two lines, submits the second form, and piles every folder onto the desk. In Code Mode, the server hands over a compact catalog and an interpreter: the agent looks up the signature it needs, writes a short script that runs all the calls sequentially inside the server, and brings back only a note with the final IDs.
Cloudflare's original implementation runs TypeScript inside Worker isolates on their cloud. I wanted the same mechanics for the APIs I use every day in the terminal (Notion, GitHub, Vercel, and Supabase), running locally over stdio, starting in milliseconds, without a Node.js or Docker runtime dependency, and sharing a single binary across Claude Code, Codex, and Cursor.
I split the Cargo workspace into six small crates so each responsibility stays isolated and testable without network access:
| Crate | Role in the architecture |
|---|---|
code-mode-core | Domain types (Operation, Parameter), abstract Clock, errors, and the OperationInvoker trait |
code-mode-index | OpenAPI 3.0/3.1 JSON loader, SQLite FTS5 search index, and TTL HTTP response cache |
code-mode-sandbox | Rhai engine configured with no filesystem, eval disabled, and print discarded |
code-mode-adapters | ApiAdapter trait, generic OpenApiAdapter, named provider adapters, and ureq HTTP client |
code-mode-transport | Newline-delimited JSON-RPC 2.0 server over stdio |
mcp-code-mode | Main binary, adapter composition, and the deterministic token receipt generator |
Whether you load only the Notion pilot spec (7 operations) or enable Notion, GitHub, Vercel, and Supabase together, tools/list always returns 1,647 bytes and 355 tokens across these four tools:
| Tool | Tokens | What the agent sends | What the server returns |
|---|---|---|---|
list_apis | 42 | {} | Loaded API IDs (notion, github, vercel, supabase), base_url, and operation count |
search | 125 | query, optional adapter, limit (1 to 20, default 5) | Compact signatures: operation_id, binding, METHOD /path, one-line summary, and required parameters (name:location:type) |
describe | 92 | operation_id, optional adapter | Full parameter list plus request and response schemas (capped at 4,000 bytes each) for a single operation |
execute | 94 | code (Rhai source string) | Only the serialized value of the script's final expression |
In my first iteration of the server, I only exposed search and execute (201 tokens for tool definitions), and search inlined the full request and response schemas on every hit. In practice, a query for "page database" with limit 5 cost 1,979 tokens (8,604 bytes) because it dumped five full schemas at once.
Splitting search and describe fixed that leak. Today, the same "page database" search returns compact signatures and takes 231 tokens (966 bytes), saving 1,748 tokens per search. When the agent already knows the payload shape or only needs the required parameter list (parent:body:object, page_id:path:string), it skips describe altogether; when it needs the full schema for one operation, it pays 324 tokens for that single endpoint.
code-mode-index parses OpenAPI 3.0 and 3.1 JSON documents, resolves local references (#/components/schemas/, parameters, requestBodies, responses), merges simple allOf blocks, and guards against circular references and schema depths above 32 levels.
To avoid re-parsing large specs on every startup (such as GitHub's or Vercel's REST specs), the server hashes the JSON with SHA-256 (spec_hash) and stores it in the spec_meta table of a local SQLite database (~/.cache/mcp-code-mode/cache.db, using rusqlite with bundled). If the hash matches, the index is reused immediately.
Search combines an FTS5 virtual table (operations_fts with unicode61 tokenization and bm25 ranking) with a lexical score across operation_id, binding name, HTTP path, summary, description, and tags. If a query with partial terms returns no FTS5 hits, the store falls back to a full scan so substring matches still surface. The same SQLite file holds a response_cache table that stores 2xx responses for GET and HEAD requests for CODE_MODE_CACHE_TTL seconds (default 60). POST, PUT, PATCH, and DELETE calls are never cached.
To run the scripts written by the model, I chose Rhai, an embedded scripting language for Rust. It compiles into the binary with zero external dependencies, uses JSON-like object maps (#{ key: value }), and enforces strict resource limits on every run.
In crates/code-mode-sandbox/src/engine.rs, each execute call builds a fresh Engine with these limits:
fn configure(engine: &mut Engine, limits: &ScriptLimits) {
engine.set_max_operations(limits.max_operations);
engine.set_max_call_levels(limits.max_call_levels);
engine.set_max_expr_depths(limits.max_expr_depth, limits.max_expr_depth);
engine.set_max_string_size(limits.max_string_size);
engine.set_max_array_size(limits.max_array_size);
engine.set_max_map_size(limits.max_map_size);
engine.set_strict_variables(true);
// print/debug would write onto the MCP stdout stream and break framing.
engine.on_print(|_| {});
engine.on_debug(|_, _, _| {});
let _ = engine.disable_symbol("eval");
}
The sandbox has no filesystem access, no environment variable access, and no general network client. The only outbound functions are the bindings generated from the indexed OpenAPI operations, capped by CODE_MODE_MAX_CALLS (default 32 HTTP requests per script). When a single API is loaded, the agent can call create_page(#{ ... }); when multiple APIs are loaded in the same process, bindings are automatically prefixed (notion_create_page, github_repos_update, vercel_getProjects, supabase_v1_list_all_projects) so operation names never collide.
To make scripts ergonomic for the model to write, I unified parameter passing in crates/code-mode-adapters/src/invoke.rs: every binding takes a single argument map. If an HTTP operation requires path parameters (like /repos/{owner}/{repo}) or query parameters (like ?limit=20&teamId=...), the agent passes owner, repo, limit, and teamId as regular keys on that map. HttpInvoker extracts those keys, URL-encodes them into the path or query string, and strips them from the map before serializing the remaining keys as the JSON request body.
Free and paid products to turn ideas into a foundation you can actually ship.
13 products availableContinue exploring similar topics
My agent's telemetry ships disabled, points at localhost by default and excludes prompts. It still shows duration, fallbacks and routing decisions.
For HTTP-provider routes, lemon-code records score factors. This teaching example shows how to read the sum and distinguish it from the JEV layer.

Aprenda Model Context Protocol (MCP) na prática: conceitos, arquitetura e exemplos reais com Claude Code para criar agentes e workflows de IA escaláveis.
A practical checklist to validate security, cost, evals, and observability before you ship your AI app to production.
Production-tested templates trusted by developers. Save weeks of setup on your next project.
I did not want to publish vague percentage claims without showing exactly what was counted. So I split verification into two parts: a deterministic protocol receipt for Notion (verified in cargo test) and a live test against my real Vercel account.
The workflow chains five steps: search for a page by title ("Launch plan"), create a child page under it, edit that page's title, create a database inside the page, and update the database's title and description.
On the classic side, I measured five tools/call round-trips against @notionhq/notion-mcp-server 2.6.1. One technical detail worth noting: the official Notion MCP server 2.6.1 targets the 2025-09-03 data-source API (API-create-a-data-source and API-update-a-data-source), whereas the embedded pilot spec in mcp-code-mode uses the /v1/databases endpoints from the 2022-06-28 public REST API. Steps 1 through 3 use the exact same fixture bodies on both sides; steps 4 and 5 use the corresponding payloads for each API version.
| Step / Component | Classic MCP (o200k_base tokens) | mcp-code-mode (o200k_base tokens) |
|---|---|---|
Tool definitions (tools/list) | 17,500 (24 tools) | 355 (4 tools) |
Signature search round-trip (search for "page database") | 0 | 231 (16 call + 215 result) |
Step 1: search page (API-post-search) | 259 (30 call + 229 result) | runs inside script |
Step 2: create page (API-post-page) | 272 (72 call + 200 result) | runs inside script |
Step 3: edit page (API-patch-page) | 263 (55 call + 208 result) | runs inside script |
Step 4: create database (API-create-a-data-source) | 216 (60 call + 156 result) | runs inside script |
Step 5: edit database (API-update-a-data-source) | 254 (64 call + 190 result) | runs inside script |
Single execute round-trip (332-token script + 95-token final JSON) | 0 | 521 (426 call + 95 result) |
| Total resident in context | 18,764 | 1,107 |
That is 17,657 fewer tokens sitting in the session for the same 5-step job. Even if you ignore the 17,500 tool-definition tokens and compare only the call and response traffic, the five classic round-trips take 1,264 tokens versus 521 tokens for the single execute call, because four intermediate Notion objects never re-enter the model context.
Controlled fixtures prove the protocol mechanics, but production APIs return much heavier payloads. When I tested listing my 29 real projects on Vercel, the scale difference was stark: the classic response for listing projects cost 340,306 tokens, while the mcp-code-mode workflow listed all 29 projects in 5,078 tokens.
A GET /v10/projects call on Vercel blows up into hundreds of thousands of tokens because each project object carries deeply nested metadata: latest deployment histories, dozens of domain aliases, build and environment configurations, and Git repository links. In classic MCP, that entire JSON payload lands in the agent's context window before the model can extract the 29 project names and IDs. In Code Mode, the Rhai script iterates over projects inside the Rust process, picks only the fields needed (such as id, name, and framework), and returns a clean summary.
That said, I want to be upfront about two caveats in this Vercel comparison:
mcp-code-mode, the agent queries Vercel's public OpenAPI spec (https://vercel.com/openapi.json) and calls getProjects with a Bearer token (VERCEL_TOKEN), projecting fields inside the Rhai script. The answer I needed in the chat (my 29 projects) was the same, but the transport and field projection are different.mcp-code-mode, we hit three real issues that required fixes in both the script and the Rust sandbox:
teamId) and pagination (until): calling getProjects(#{}) with no arguments on Vercel either queries the personal account instead of the team or returns only the first page (20 items by default). To retrieve all 29 projects, the script had to pass teamId and follow the pagination.next cursor via the until query parameter in a second call inside the same execute block (which I later locked in as the vercel_projects_follow_pagination_cursor_and_team_scope test in provider_workflows.rs).max_string_size): because Vercel project objects include large string fields, a tight string limit or any attempt to serialize the raw response inside Rhai tripped the sandbox limit before the script could finish. I had to tune ScriptLimits (max_string_size: 200_000 and max_operations: 100_000) and verify with a dedicated unit test (small_script_string_limit_does_not_reject_large_api_response_fields) that large fields in parsed API responses do not reject a script that only reads project.id and project.name.Even counting the failed attempts while debugging pagination and string limits, total token usage stayed an order of magnitude below the 340,306 tokens of dumping raw project payloads into context. Once the sandbox limit and cursor pattern were in place, subsequent runs hit ~5k tokens on the first shot.
Replacing individual endpoint tools with script execution solves tools/list bloat and keeps intermediate payloads out of the prompt, but it introduces engineering trade-offs worth weighing before you switch:
max_string_size at 200 KB, max_array_size at 5,000 items, max_map_size at 5,000 keys, and max_operations at 100,000 instructions). If the agent writes a script that concatenates a huge report into a single string or loops over thousands of items, the sandbox aborts the run. My rule in AGENTS.md is explicit: filter early and return only IDs, titles, and counts in the final expression.mcp-code-mode generates bindings directly from OpenAPI operations, the Rhai script has to inspect pagination.next (or next_cursor in Notion, page in GitHub) and make the follow-up call within the CODE_MODE_MAX_CALLS cap (32 HTTP requests per script).POST / PATCH) and the fourth returns HTTP 400, execute halts immediately and returns the status and error body so the model can fix the script. However, the first three mutations have already been committed on the remote API. For write-heavy workflows, scripts should check preconditions first (such as searching before creating) or keep mutations small.multipart uploads or custom request signing beyond static headers and Bearer tokens. If an official spec has cryptic operationIds and empty summary fields, SQLite FTS5 ranking suffers until you enrich the spec descriptions.mcp-code-mode| Scenario | Recommended choice | Why |
|---|---|---|
| Large REST APIs (GitHub, Notion, Vercel, Supabase, Stripe) with dozens or hundreds of endpoints | mcp-code-mode | Shrinks tens of thousands of tools/list tokens down to 355 tokens and keeps intermediate JSON out of context |
| Multi-step workflows where step 1's output is just an ID passed into step 2 | mcp-code-mode | Runs the chain in a single execute call without paying multiple LLM generation turns |
| Small local toolsets (2 to 5 tools) that do not wrap HTTP APIs | Classic MCP | Definition overhead is already tiny, and writing a Rhai script to call a single local function adds unnecessary indirection |
| Operations that require local UI, a PTY, streaming output, or per-action human approval prompts | Classic MCP | execute batches multiple calls into one script; if you want an interactive confirmation dialog for every individual action, separate tools provide clearer boundaries |
That last point connects directly to what I covered in guardrails and approvals in coding agents: when a single execute call can trigger multiple HTTP requests, governance has to live in token scoping (such as project-scoped or read-only tokens) and executor limits. And as I wrote in why I built my own coding agent, keeping tool contracts small is one of the most reliable ways to keep the harness from swallowing the task context.
The full source code, vendored specs, wiremock integration tests, and token receipt generator are open source at github.com/Andersonlimahw/mcp-code-mode under the MIT license.
To build and install the binary onto your PATH:
git clone https://github.com/Andersonlimahw/mcp-code-mode.git
cd mcp-code-mode
cargo install --path crates/mcp-code-mode
When CODE_MODE_ADAPTERS is unset, the server automatically enables every adapter whose token environment variable is present (NOTION_TOKEN, GITHUB_TOKEN, VERCEL_TOKEN, and SUPABASE_ACCESS_TOKEN).
claude mcp add --transport stdio mcp-code-mode \
--env NOTION_TOKEN=ntn_your_token \
--env GITHUB_TOKEN=github_pat_your_token \
--env VERCEL_TOKEN=your_vercel_token \
--env SUPABASE_ACCESS_TOKEN=sbp_your_token \
-- mcp-code-mode
Add this block to ~/.codex/config.toml:
[mcp_servers.mcp-code-mode]
command = "mcp-code-mode"
enabled = true
[mcp_servers.mcp-code-mode.env]
NOTION_TOKEN = "ntn_your_token"
GITHUB_TOKEN = "github_pat_your_token"
VERCEL_TOKEN = "your_vercel_token"
SUPABASE_ACCESS_TOKEN = "sbp_your_token"
Add this entry to ~/.cursor/mcp.json:
{
"mcpServers": {
"mcp-code-mode": {
"command": "mcp-code-mode",
"env": {
"NOTION_TOKEN": "ntn_your_token",
"GITHUB_TOKEN": "github_pat_your_token",
"VERCEL_TOKEN": "your_vercel_token",
"SUPABASE_ACCESS_TOKEN": "sbp_your_token"
}
}
}
}
If you want to plug in another Bearer-token REST API without touching Rust code, point CODE_MODE_ADAPTER_ID, CODE_MODE_BASE_URL, CODE_MODE_SPEC, and CODE_MODE_TOKEN_ENV at any OpenAPI 3.x JSON document. The tool list exposed to the model will still be the same 4 tools and 355 tokens.
result.tools payload of every MCP server you keep enabled by default before optimizing in the dark.search + describe + execute.search responses compact (signatures and required parameters only) and load full schemas on demand with describe.If you want to cut token costs, design leaner agent architectures, and put AI into production with your engineering team without wasting context, talk to LEMON.DEV.
RECEIPT.md verified on November 7, 2026).tools/list and tools/call).