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): serve compact JSON in the tool result text (#3018)
Raghav Chamadiyab7524e4928ba
diff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.mdindex 1338dad04..9cf15ef17 100644--- a/docs/reference/MCP_RESPONSE_FIELDS.md+++ b/docs/reference/MCP_RESPONSE_FIELDS.md@@ -5,6 +5,7 @@ The field dictionary for every repowise MCP tool response. [MCP_TOOLS.md](../age## Contents- [The `_meta` envelope](#the-_meta-envelope)+- [On the wire](#on-the-wire)- [Truncation and recovery](#truncation-and-recovery)- [Ignored arguments](#ignored-arguments)- [Next-call shape](#next-call-shape)@@ -46,6 +47,12 @@ Routine responses carry a lean envelope. `get_overview`, called once per session---+## On the wire++Each result carries the payload twice, as MCP allows: `structuredContent` is `{"result": <payload>}` (the tools advertise an `outputSchema`), and the text block is the same payload as compact JSON, with no indentation. Clients that read `structuredContent` see no difference; clients that forward the text block send fewer tokens. Set `REPOWISE_MCP_PRETTY_JSON=1` in the server's environment to restore indented text for a client that depends on it.++---+## Truncation and recoveryResponses fit 24,000 serialized characters by default and 32,000 when the call passes an expansion argument (for most tools, a nonempty `include`; for `get_answer`, `include=["evidence"]`). When the budget cut something, `_meta.response_budget` reports which ceiling applied.diff --git a/packages/server/src/repowise/server/mcp_server/__init__.py b/packages/server/src/repowise/server/mcp_server/__init__.pyindex 0f7bd6322..cdc0906a2 100644--- a/packages/server/src/repowise/server/mcp_server/__init__.py+++ b/packages/server/src/repowise/server/mcp_server/__init__.py@@ -219,6 +219,51 @@ def tool_middleware(fn: Any) -> Any:return record(budget(timed(instrument(budget(quantize(trust(shield(fn))))))))+#: Restores FastMCP's indented text block, for a client that turns out to need it.+PRETTY_JSON_ENV = "REPOWISE_MCP_PRETTY_JSON"+++def wire_result(payload: Any) -> Any:+ """*payload* as FastMCP would serve it, with the text block compact.++ FastMCP renders the text with ``indent=2`` beside a structured copy that is+ already compact. The same ``fallback=str`` keeps a value JSON cannot hold+ rendering as before, and the structured copy is converted exactly as+ FastMCP converts it. Anything but a dict, or ``REPOWISE_MCP_PRETTY_JSON=1``,+ is left to FastMCP's own conversion.+ """+ import os++ pretty = os.environ.get(PRETTY_JSON_ENV, "").strip().lower() in {"1", "true", "yes", "on"}+ if pretty or not isinstance(payload, dict):+ return payload+ import pydantic_core+ from mcp.types import CallToolResult, TextContent++ text = pydantic_core.to_json(payload, fallback=str).decode()+ return CallToolResult(+ content=[TextContent(type="text", text=text)],+ structuredContent={"result": pydantic_core.to_jsonable_python(payload)},+ )+++def registered_tool(fn: Any) -> Any:+ """What the server registers: :func:`tool_middleware` plus the wire text.++ Kept out of ``tool_middleware`` because tests and the CLI await the+ middleware-wrapped functions directly and expect the dict back.+ """+ from functools import wraps++ inner = tool_middleware(fn)++ @wraps(inner)+ async def wrapped(*args: Any, **kwargs: Any) -> Any:+ return wire_result(await inner(*args, **kwargs))++ return wrapped++def ensure_full_surface() -> Any:"""Import every tool module and attach the registry to the FastMCP server.@@ -255,7 +300,7 @@ def ensure_full_surface() -> Any:from repowise.core.registry import mcp_tool_registryfrom repowise.server.mcp_server._tool_selection import snapshot_full_surface- mcp_tool_registry.apply(_mcp, middleware=tool_middleware)+ mcp_tool_registry.apply(_mcp, middleware=registered_tool)# Snapshot the full registered surface so per-server tool selection# (single-repo vs workspace, config/CLI overrides) can rebuild from it.diff --git a/tests/unit/server/mcp/test_wire_representation_contract.py b/tests/unit/server/mcp/test_wire_representation_contract.pyindex 8b881ee79..f480de8d7 100644--- a/tests/unit/server/mcp/test_wire_representation_contract.py+++ b/tests/unit/server/mcp/test_wire_representation_contract.py@@ -39,6 +39,9 @@ signature hygiene, in modules none of these tools mention.The seam under test is ``FuncMetadata.convert_result``, which is what``FastMCP.call_tool`` uses to build the ``CallToolResult``. It reads only thecallable's signature, so these tests need no index, no fixture and no I/O.+The registered callable hands it a ``CallToolResult`` already built by+``wire_result`` (compact text, the same structured copy), which it validates+against the output schema and passes through."""from __future__ import annotations@@ -46,7 +49,9 @@ from __future__ import annotationsimport inspectimport json+import pytestfrom mcp.server.fastmcp.utilities.func_metadata import func_metadata+from mcp.types import CallToolResultfrom repowise.core.registry import mcp_tool_registry@@ -83,14 +88,18 @@ def _registered_callables():`mcp_tool_registry.apply` registers `middleware(entry.fn)`, so building aschema from the bare function measures something the client never sees."""- from repowise.server.mcp_server import tool_middleware+ from repowise.server.mcp_server import registered_tool- return [tool_middleware(fn) for fn in _registry_entries()]+ return [registered_tool(fn) for fn in _registry_entries()]def _convert(fn):"""Return ``(text_blocks, structured_or_None)`` exactly as the server would."""- result = func_metadata(fn).convert_result(dict(SAMPLE_PAYLOAD))+ from repowise.server.mcp_server import wire_result++ result = func_metadata(fn).convert_result(wire_result(dict(SAMPLE_PAYLOAD)))+ if isinstance(result, CallToolResult):+ return list(result.content), result.structuredContentif isinstance(result, tuple):blocks, structured = resultreturn list(blocks), structured@@ -192,3 +201,41 @@ def test_declared_structured_annotations_do_not_reach_the_wire():"tool declaring a bare `dict` has stopped serving structuredContent ""entirely. That is a wire change for every client.")+++def test_every_tool_serves_compact_text():+ """The text block is what a text-forwarding client hands its model."""+ expected = json.dumps(SAMPLE_PAYLOAD, separators=(",", ":"))+ loose = {}+ for fn in _registered_callables():+ blocks, _structured = _convert(fn)+ if blocks[0].text != expected or "\n" in blocks[0].text:+ loose[fn.__name__] = blocks[0].text[:80]+ assert not loose, f"text blocks carry indentation or spacing: {loose}"+++def test_pretty_json_env_restores_the_indented_text(monkeypatch):+ from repowise.server.mcp_server import PRETTY_JSON_ENV++ monkeypatch.setenv(PRETTY_JSON_ENV, "1")+ blocks, structured = _convert(_registered_callables()[0])++ assert blocks[0].text.startswith('{\n "answer"')+ assert structured == {"result": SAMPLE_PAYLOAD}+++async def test_only_the_registered_callable_changes_shape():+ """Tests and the CLI await the middleware-wrapped tool and need the dict."""+ from repowise.server.mcp_server import registered_tool, tool_middleware++ async def get_risk(targets: list[str]) -> dict:+ return {"targets": {}, "_meta": {}}++ bare = await tool_middleware(get_risk)(["a.py"])+ served = await registered_tool(get_risk)(["a.py"])++ assert isinstance(bare, dict)+ assert isinstance(served, CallToolResult)+ assert json.loads(served.content[0].text) == bare+ assert served.structuredContent == {"result": bare}