Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(mcp): report timing_ms for every tool, not just the ones that ask (#2271)

Raghav Chamadiya8196e6b6e84a
diff --git a/packages/server/src/repowise/server/mcp_server/__init__.py b/packages/server/src/repowise/server/mcp_server/__init__.py
index f63f7656d..a9a32469d 100644
--- a/packages/server/src/repowise/server/mcp_server/__init__.py
+++ b/packages/server/src/repowise/server/mcp_server/__init__.py
@@ -101,13 +101,15 @@ def tool_middleware(fn: Any) -> Any:
the ledger measures the payload as actually delivered.
4. ``budget`` — caps the delivered shape before savings are measured.
5. ``instrument`` — records the bounded result and adds savings metadata.
- 6. ``budget`` — accounts for those final middleware fields and rechecks.
+ 6. ``timed`` — stamps ``_meta.timing_ms`` for any tool that did not.
+ 7. ``budget`` — accounts for those final middleware fields and rechecks.
Named rather than inlined at the ``apply`` call so tests can wrap a tool in
the real composition; ``tests/unit/server/mcp/test_number_precision.py``
relies on that to prove no raw double reaches an agent.
"""
import inspect
+ import time
from functools import wraps
from repowise.server.mcp_server._budget import (
@@ -131,6 +133,25 @@ def tool_middleware(fn: Any) -> Any:
return wrapped
+ def timed(inner: Any) -> Any:
+ """Stamp elapsed time for the tools that do not thread it themselves.
+
+ A tool that already reports ``timing_ms`` keeps its own number, which
+ measures its retrieval rather than the middleware around it.
+ """
+
+ @wraps(inner)
+ async def wrapped(*args: Any, **kwargs: Any) -> Any:
+ started = time.perf_counter()
+ result = await inner(*args, **kwargs)
+ if isinstance(result, dict):
+ meta = result.setdefault("_meta", {})
+ if isinstance(meta, dict) and meta.get("timing_ms") is None:
+ meta["timing_ms"] = round((time.perf_counter() - started) * 1000, 2)
+ return result
+
+ return wrapped
+
def budget(inner: Any) -> Any:
@wraps(inner)
async def wrapped(*args: Any, **kwargs: Any) -> Any:
@@ -155,7 +176,7 @@ def tool_middleware(fn: Any) -> Any:
return wrapped
- return budget(instrument(budget(quantize(trust(shield(fn))))))
+ return budget(timed(instrument(budget(quantize(trust(shield(fn)))))))
def ensure_full_surface() -> Any:
diff --git a/tests/unit/server/mcp/test_tool_timing_uniform.py b/tests/unit/server/mcp/test_tool_timing_uniform.py
new file mode 100644
index 000000000..bfad6c808
--- /dev/null
+++ b/tests/unit/server/mcp/test_tool_timing_uniform.py
@@ -0,0 +1,57 @@
+"""Every advertised tool reports how long it took."""
+
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+
+from repowise.server.mcp_server import tool_middleware
+
+
+async def _run(fn: Any, *args: Any, **kwargs: Any) -> dict[str, Any]:
+ return await tool_middleware(fn)(*args, **kwargs)
+
+
+async def test_timing_stamped_for_a_tool_that_does_not_thread_it() -> None:
+ async def get_risk(targets: list[str], repo: str | None = None) -> dict[str, Any]:
+ return {"targets": {}, "_meta": {"contract_version": 1}}
+
+ result = await _run(get_risk, ["src/a.py"])
+
+ assert isinstance(result["_meta"]["timing_ms"], float)
+ assert result["_meta"]["timing_ms"] >= 0
+
+
+async def test_a_tool_that_reports_its_own_timing_keeps_it() -> None:
+ async def get_answer(question: str) -> dict[str, Any]:
+ return {"answer": "yes", "_meta": {"contract_version": 1, "timing_ms": 1234.5}}
+
+ result = await _run(get_answer, "why?")
+
+ # Preserved, not replaced by the middleware's own near-zero elapsed. The
+ # quantize layer rounds it, so compare with a tolerance.
+ assert result["_meta"]["timing_ms"] == pytest.approx(1234.5, abs=1)
+
+
+async def test_timing_survives_the_final_budget_pass() -> None:
+ async def get_why(query: str | None = None) -> dict[str, Any]:
+ return {
+ "mode": "search",
+ "decisions": [{"id": i, "body": "x" * 2000} for i in range(60)],
+ "_meta": {"contract_version": 1},
+ }
+
+ result = await _run(get_why, "why is auth shaped this way?")
+
+ assert result["_meta"]["timing_ms"] is not None
+ budget = result["_meta"]["response_budget"]
+ assert budget["serialized_chars"] <= budget["limit_chars"]
+
+
[email protected]("returned", [None, [], "not a dict"])
+async def test_non_dict_results_are_passed_through(returned: Any) -> None:
+ async def odd_tool() -> Any:
+ return returned
+
+ assert await _run(odd_tool) == returned