Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(mcp): clamp response budget under the live MCP host token cap (#771)
Raghav Chamadiya47245470302c
diff --git a/packages/server/src/repowise/server/mcp_server/_budget/__init__.py b/packages/server/src/repowise/server/mcp_server/_budget/__init__.pyindex ae50f99de..d0e8140da 100644--- a/packages/server/src/repowise/server/mcp_server/_budget/__init__.py+++ b/packages/server/src/repowise/server/mcp_server/_budget/__init__.py@@ -19,8 +19,12 @@ from __future__ import annotationsfrom repowise.server.mcp_server._budget.budgeter import (CHAR_BUDGET,CHARS_PER_TOKEN,+ HOST_CAP_BUDGET_FRACTION,+ HOST_MCP_TOKEN_CAP_DEFAULT,TOKEN_BUDGET,+ effective_char_budget,estimate_response_tokens,+ host_token_cap,truncate_to_budget,)from repowise.server.mcp_server._budget.collector import OmissionCollector@@ -28,8 +32,12 @@ from repowise.server.mcp_server._budget.collector import OmissionCollector__all__ = ["CHARS_PER_TOKEN","CHAR_BUDGET",+ "HOST_CAP_BUDGET_FRACTION",+ "HOST_MCP_TOKEN_CAP_DEFAULT","TOKEN_BUDGET","OmissionCollector",+ "effective_char_budget","estimate_response_tokens",+ "host_token_cap","truncate_to_budget",]diff --git a/packages/server/src/repowise/server/mcp_server/_budget/budgeter.py b/packages/server/src/repowise/server/mcp_server/_budget/budgeter.pyindex 96c4fb64f..a4325c579 100644--- a/packages/server/src/repowise/server/mcp_server/_budget/budgeter.py+++ b/packages/server/src/repowise/server/mcp_server/_budget/budgeter.py@@ -8,24 +8,36 @@ every drop recoverable, and (b) a skeleton-stripping stage for the``include=["skeleton"]`` blocks that did not exist when the original waswritten.-The Claude Code harness rejects MCP tool results whose stringified form-exceeds ~10k tokens (it refuses to inline them and then refuses to Read the-spilled file). When that happens the agent falls back to multiple get_symbol-calls, each of which re-plays the cached system prompt — a significant cost-driver on dense files in long multi-turn agent sessions. We therefore cap-responses well below that ceiling: 8000 tokens leaves headroom for the-wrapping JSON envelope and the ``_meta`` fields the harness adds on top.+The MCP host caps the size of a tool result. Measured on Claude Code+2026-07-11: a result whose stringified form exceeds ``MAX_MCP_OUTPUT_TOKENS``+(default **25000 tokens**) is REJECTED with an isError+(``MCPContentTooLargeError`` — "response (N tokens) exceeds maximum allowed+tokens (25000)"), not silently truncated and not spilled to a file. That+isError matters twice over: the agent loses the answer AND — per the Phase 1+session-survival doctrine — one isError early in a session teaches it to+abandon the server entirely. So staying under the host cap is not a nicety.++Our default budget (``TOKEN_BUDGET`` = 8000) sits comfortably under the+default host cap, so the common case is unchanged. The risk is the inverse of+the one long assumed here: a user who *lowers* ``MAX_MCP_OUTPUT_TOKENS`` below+our budget would start tripping the reject path. :func:`effective_char_budget`+therefore reads the host cap at call time and clamps our ceiling under it.+(The earlier "~10k token" ceiling in this docstring was a guess; the measured+number is 25000, and the failure mode is rejection, not file spill.)The estimator is intentionally dependency-free: 4 chars/token is thewidely-quoted average for English + code on BPE tokenizers and is within-~20% of tiktoken for typical wiki content. Precise counting is unnecessary-because we only need to stay comfortably under the hard limit.+~20% of tiktoken for typical wiki content. Dense code can tokenize finer than+4 chars/token, so the host may count MORE tokens than we estimate — the+safety fraction below absorbs that gap plus the JSON envelope and ``_meta``+the host counts on top of our payload."""from __future__ import annotationsimport jsonimport logging+import osfrom typing import Anyfrom repowise.server.mcp_server._budget.collector import OmissionCollector@@ -36,6 +48,45 @@ TOKEN_BUDGET = 8000CHARS_PER_TOKEN = 4CHAR_BUDGET = TOKEN_BUDGET * CHARS_PER_TOKEN+# Claude Code's MAX_MCP_OUTPUT_TOKENS default (measured 2026-07-11). A result+# over this is rejected with an isError, so our ceiling must stay under it.+HOST_MCP_TOKEN_CAP_DEFAULT = 25000++# Fraction of the host cap we allow ourselves. The gap absorbs (a) estimator+# error — our 4-chars/token figure can undercount real tokens on dense code by+# up to ~30% — and (b) the JSON envelope + _meta the host tokenizes on top of+# our payload. 0.6 keeps even an undercounted response clear of the reject line.+HOST_CAP_BUDGET_FRACTION = 0.6+++def host_token_cap() -> int:+ """The MCP host's max-output-tokens: ``MAX_MCP_OUTPUT_TOKENS`` or the default.++ Read at call time (not import) so a mid-session env change is honoured and+ tests can monkeypatch it. A malformed or non-positive value falls back to+ the measured default rather than trusting a footgun.+ """+ raw = os.environ.get("MAX_MCP_OUTPUT_TOKENS", "").strip()+ if raw:+ try:+ parsed = int(raw)+ except ValueError:+ parsed = 0+ if parsed > 0:+ return parsed+ return HOST_MCP_TOKEN_CAP_DEFAULT+++def effective_char_budget(configured: int = CHAR_BUDGET) -> int:+ """``configured`` ceiling, lowered under the live host cap when that is tighter.++ Default host cap (25000) leaves our 8000-token budget untouched; a narrowed+ ``MAX_MCP_OUTPUT_TOKENS`` pulls us down with it so we never trip the host's+ reject-with-isError path (one isError = server abandonment, Phase 1).+ """+ host_char_ceiling = int(host_token_cap() * HOST_CAP_BUDGET_FRACTION) * CHARS_PER_TOKEN+ return min(configured, host_char_ceiling)+def estimate_response_tokens(obj: Any) -> int:"""Cheap upper-bound token estimate for an arbitrary JSON-serialisable object.@@ -102,12 +153,17 @@ def query_terms_for(target: str) -> set[str]:def truncate_to_budget(result: dict[str, Any],- char_budget: int = CHAR_BUDGET,+ char_budget: int | None = None,*,collector: OmissionCollector | None = None,) -> dict[str, Any]:"""Cap a targets-shaped response at roughly ``TOKEN_BUDGET`` tokens.+ ``char_budget`` defaults to :func:`effective_char_budget` — our configured+ ceiling, clamped under the live MCP host cap so the response can never trip+ the host's reject-with-isError path. Pass an explicit value to override+ (tests do; production callers should not).+Strategy (applied in order, stopping as soon as the budget is met):1. **Strip heavy optional doc fields** (``content_md``, ``documentation``,@@ -140,6 +196,8 @@ def truncate_to_budget(* Targets that carry an ``error`` field (not-found) are cheap and arepreserved unless literally nothing else fits."""+ if char_budget is None:+ char_budget = effective_char_budget()try:result = _run_stages(result, char_budget, collector)finally:diff --git a/tests/unit/server/mcp/test_budget.py b/tests/unit/server/mcp/test_budget.pyindex fd297f174..6c234ff49 100644--- a/tests/unit/server/mcp/test_budget.py+++ b/tests/unit/server/mcp/test_budget.py@@ -22,7 +22,15 @@ import pytestfrom repowise.core.distill.markers import MARKER_REfrom repowise.core.distill.store import OmissionStore, default_store_path-from repowise.server.mcp_server._budget import OmissionCollector, truncate_to_budget+from repowise.server.mcp_server._budget import (+ CHAR_BUDGET,+ CHARS_PER_TOKEN,+ HOST_MCP_TOKEN_CAP_DEFAULT,+ OmissionCollector,+ effective_char_budget,+ host_token_cap,+ truncate_to_budget,+)@pytest.fixture@@ -107,6 +115,52 @@ def test_collector_store_failure_degrades_silently(tmp_path: Path):assert "omitted" not in response["_meta"]+# ---------------------------------------------------------------------------+# Host-cap compliance — the response ceiling tracks MAX_MCP_OUTPUT_TOKENS so a+# result never trips the host's reject-with-isError path (plan 3.1).+# ---------------------------------------------------------------------------+++class TestHostCapCompliance:+ def test_host_token_cap_default_when_unset(self, monkeypatch):+ monkeypatch.delenv("MAX_MCP_OUTPUT_TOKENS", raising=False)+ assert host_token_cap() == HOST_MCP_TOKEN_CAP_DEFAULT++ def test_host_token_cap_reads_env_override(self, monkeypatch):+ monkeypatch.setenv("MAX_MCP_OUTPUT_TOKENS", "5000")+ assert host_token_cap() == 5000++ def test_host_token_cap_ignores_garbage_and_nonpositive(self, monkeypatch):+ for bad in ("", " ", "not-a-number", "0", "-100"):+ monkeypatch.setenv("MAX_MCP_OUTPUT_TOKENS", bad)+ assert host_token_cap() == HOST_MCP_TOKEN_CAP_DEFAULT++ def test_default_host_cap_leaves_configured_budget_untouched(self, monkeypatch):+ # 8000-token budget << 25000-token host cap: the common case is unchanged.+ monkeypatch.delenv("MAX_MCP_OUTPUT_TOKENS", raising=False)+ assert effective_char_budget() == CHAR_BUDGET++ def test_narrowed_host_cap_pulls_budget_under_it(self, monkeypatch):+ monkeypatch.setenv("MAX_MCP_OUTPUT_TOKENS", "5000")+ eff = effective_char_budget()+ assert eff < CHAR_BUDGET+ # Invariant: the ceiling always stays strictly under the host's raw cap+ # (in chars), with margin for estimator error + the JSON envelope.+ assert eff < host_token_cap() * CHARS_PER_TOKEN++ def test_effective_budget_never_exceeds_host_cap_across_range(self, monkeypatch):+ for cap in (1000, 5000, 12000, 25000, 100000):+ monkeypatch.setenv("MAX_MCP_OUTPUT_TOKENS", str(cap))+ assert effective_char_budget() < cap * CHARS_PER_TOKEN++ def test_truncate_default_budget_honors_narrowed_host_cap(self, monkeypatch):+ # With no explicit char_budget, a big response must truncate under a+ # narrowed host cap where it would have fit the flat 32000-char budget.+ monkeypatch.setenv("MAX_MCP_OUTPUT_TOKENS", "2000")+ out = truncate_to_budget(_big_response(n_targets=3, n_symbols=20))+ assert out["truncated"] is True++# ---------------------------------------------------------------------------# truncate_to_budget with a collector# ---------------------------------------------------------------------------