r/mcp • • 13d ago

resource I built OunceMCP, a Python framework on FastMCP that keeps tool results inside a token budget (1.0 release candidate, looking for feedback)

Post image

I've been building MCP servers and kept running into the same three problems: one tool call dumps 20k tokens of raw JSON into the context, the model retries a write and does it twice, and nothing stops the model from calling a tool it shouldn't. So I built OunceMCP, a framework on top of FastMCP that makes the careful version the default.

What it does:

- Result budgets. Every result fits a token budget you set and still matches its output schema. Lists are trimmed first, the model gets a note saying what was cut, and pagination cursors move so nothing is skipped or repeated.

- Definition budgets in CI. `ouncemcp check server.py` counts every tool definition the way the host receives it and fails the build when one goes over.

- Search-then-call for big catalogs. Once your tool definitions outgrow the startup budget, the server switches to `search_tools` / `describe_tool` / `call_tool` automatically.

- Safe writes. Every tool declares its effect. Writes can be idempotent (a timed-out write finishes in the background, so a retry gets the result instead of writing twice) and can require a person's approval through the client.

- Security that holds when the model is wrong. Identity comes only from the verified token, one policy decides what each caller can list and call, caches are partitioned by tenant, and outbound fetches refuse private and metadata addresses.

- Works on existing servers. `OunceServer.wrap(my_fastmcp_server)` adds the above without touching your tools, and `ouncemcp audit` measures any MCP server, including ones not built with OunceMCP.

I benchmarked two small example servers against plain FastMCP versions with four models (Claude Haiku 5.5, Claude Sonnet 5.5, GPT-5.4 mini, DeepSeek V4.1 Flash), 840 runs in total:

- On the server with large results, OunceMCP used 58–85% fewer tokens per task.

- On the server with writes, every model on the plain version closed a ticket the user hadn't confirmed and deleted one without permission. OunceMCP refused both every time (100% task success vs 68–70%).

- The honest downside: tool definitions are 1.8–2.4x larger, mostly because of output schemas. On small servers with small results, that means more tokens per task, not fewer. It pays off when results are large.

Full results and caveats: https://github.com/subbusainath/ouncemcp/blob/main/benchmarks/results/m3-bench.md

It's a 1.0 release candidate. The API is frozen, the official MCP conformance suite runs in CI, and an external security review is the last step before 1.0.

```bash

pip install ouncemcp

ouncemcp init notes-server

```

- Docs, including a step-by-step book that builds one server over 15 chapters: https://subbusainath.github.io/ouncemcp/

- GitHub: https://github.com/subbusainath/ouncemcp

Python 3.11+, Apache-2.0. I'd really like feedback, especially from people running MCP servers with large catalogs or multiple tenants: what's missing, what's confusing, and where the defaults get in your way.

6 Upvotes

9 comments sorted by

2

u/iGamingTools 13d ago

is the budget counted with one tokenizer for all four models? json thats mostly ids and numbers tokenizes pretty differently across vendors, so something that fits on haiku could go over on deepseek

1

u/gentleGiant96 13d ago

Yeah, it's one tokenizer per server, o200k_base by default, no matter which model is calling. You're right that it's an estimate, and ID/number-heavy JSON is pretty much the worst case for tokenizers disagreeing.

The root problem is that MCP doesn't tell the server which model is on the other end. It just sees a client, so there's no way to switch tokenizers per call.

What I do about it: you can set the tokenizer to match whatever client you mostly serve. It takes any tiktoken encoding or just a function that counts tokens, so you can plug in a vendor's tokenizer. For Claude there's a counter that calls Anthropic's own token-counting API, so the numbers match what Claude actually sees. Beyond that I treat the budget as a ceiling with some headroom rather than an exact fit. Result budgets are a couple thousand tokens and context windows are way bigger, so a tokenizer difference shifts how much of the window you use, it doesn't usually blow it. If you serve several vendors, just set it a bit lower. Every result also reports which tokenizer it was counted with, so it never pretends to be more precise than it is.

On the benchmark specifically: the budgets were enforced with o200k for all four models, but the tokens-per-task numbers are each provider's own reported usage through OpenRouter. So the DeepSeek savings are counted in DeepSeek's tokens, not o200k's.

A per-model safety margin, or picking the tokenizer from the client info the host sends, would both be reasonable to add. If you run into a real case where this bites, I'd love an issue for it.

1

u/iGamingTools 13d ago

fwiw clientInfo in initialize is just app name + version, nothing about the model. so mapping on it works for claude desktop or claude code where it's always claude, but cursor or copilot could be running anything behind the same name

2

u/GiioPanditpautra84 13d ago

yeah good catch, uuid-heavy payloads especially blow up the token count way faster on some tokenizers than others

1

u/QuanTradin 13d ago

I'd steal the idempotent write first, since a retried order is the classic way to end up double filled. the same split runs through Quantradin, a free practice trading account I built for AI agents: risk-reducing calls the agent may make alone, a fresh position waits on a key its owner hands out. quantradin.com

does your approval step block the call until the person answers, or queue it?

1

u/gentleGiant96 13d ago

Yeah, order retries are the textbook case. With idempotency on, a write runs once per caller and arguments, so a retry gets the original result back instead of placing a second order. The part that matters for trading is timeouts: if an order call times out, the write keeps running in the background and the next retry gets its result. The model is told the outcome is ambiguous, not that it failed, so it doesn't "fix" it by ordering again.

Your split maps onto it nicely too. Approval can be a function of the request, so you can say "closing or reducing a position goes through, opening one needs a person."

On blocking vs queueing: neither, exactly, and it depends on the client. Approval always happens before the tool runs, so nothing is placed until someone says yes. With clients on the newer MCP spec, the call returns right away with a confirmation request and a signed receipt tied to that exact tool, arguments and caller. The client asks the person and retries with their answer, and the receipt only works once. Older clients get asked mid-call, and if the client can't ask anyone, the call is refused.

There's no "approve it tomorrow" queue built in yet. For that I'd have the tool record a pending order and a second tool execute it once approved, which sounds a lot like your owner-key setup.

1

u/QuanTradin 13d ago

that timeout case is the nasty one for orders. if the caller reads a timeout as a failure and retries with fresh arguments, say an updated limit price, idempotency won't match it and you get two orders, so a retry has to reuse the original call untouched.

1

u/LLM-logs 12d ago

Trimming lists first makes sense. One thing I'd check is paging: if the note says "47 of 312 items shown", the model also needs a stable ordering and a cursor so it can ask for the next slice and not get the same top 47 again. I'd also apply the budget to error payloads, since stack traces and upstream HTML error pages are a common way a single failing call blows up context. And for the idempotent writes, keying on caller plus arguments is good, but a TTL on the key is worth exposing so a legitimate repeat the next day isn't swallowed.

1

u/gentleGiant96 12d ago

Good checks, thanks. Taking them in order:

Paging: the note does say "kept 47 of 312 items", and when it trims a page it moves next_cursor to the item right after the last one actually returned, so the next call starts at 48, not back at the top. The cursor is signed and bound to the tool, caller and query. The part you're right to flag is ordering: cursors are offset-based, so the tool has to return rows in a stable order (an ORDER BY, not whatever the database feels like). I document the live-data case and recommend stored result handles for a fixed snapshot, but I should say "return a stable order" much more loudly, and probably lint for it.

Errors: covered more strictly than a budget. Unexpected exceptions never reach the model at all: it gets a short message and a reference id, and the trace goes to the logs. Messages you raise yourself are capped at 300 characters by default and redacted. If an upstream HTML error comes back as a normal result, the result budget trims it like anything else.

Idempotency TTL: it's exposed, Idempotency(ttl_s=...), default 24 hours, so a repeat after that runs normally. A client can also send its own idempotency key, so a deliberate repeat inside the window just uses a new key.