π The fast, Pythonic way to build MCP servers and clients.
Fix unbounded Apps dev log retention (#5549)
mika0a9a48238005
diff --git a/fastmcp_slim/fastmcp/cli/apps_dev.py b/fastmcp_slim/fastmcp/cli/apps_dev.pyindex 3c5784e44..62e8e3f9e 100644--- a/fastmcp_slim/fastmcp/cli/apps_dev.py+++ b/fastmcp_slim/fastmcp/cli/apps_dev.py@@ -37,7 +37,6 @@ import signalimport sysimport tarfileimport tempfile-import timeimport webbrowserfrom pathlib import Pathfrom typing import Any@@ -52,6 +51,7 @@ from starlette.requests import Requestfrom starlette.responses import HTMLResponse, Response, StreamingResponsefrom starlette.routing import Route+from fastmcp.cli.apps_dev_log import _log_response_bytes, _MessageLogfrom fastmcp.cli.apps_dev_security import DevSessionMiddlewarefrom fastmcp.utilities.json_schema_type import safe_create_modelfrom fastmcp.utilities.logging import get_logger@@ -71,123 +71,6 @@ def _json_for_script(value: Any) -> str:)-# ----------------------------------------------------------------------------# MCP message log (captures proxy traffic for the dev UI log panel)-# ------------------------------------------------------------------------------class _MessageLog:- """In-memory buffer of MCP JSON-RPC messages flowing through the proxy."""-- def __init__(self) -> None:- self._entries: list[dict[str, Any]] = []- self._counter = 0- self._request_methods: dict[int | str, str] = {}- self._request_times: dict[int | str, float] = {}-- def log_request(self, body: dict[str, Any]) -> None:- method = body.get("method", "unknown")- jsonrpc_id = body.get("id")- timestamp = time.time()- if jsonrpc_id is not None:- self._request_methods[jsonrpc_id] = method- self._request_times[jsonrpc_id] = timestamp- self._counter += 1- self._entries.append(- {- "id": self._counter,- "timestamp": timestamp,- "direction": "request",- "method": method,- "body": body,- }- )-- def log_response(self, body: dict[str, Any]) -> None:- # Server-initiated notifications have "method" but no "id"- if "method" in body and "id" not in body:- self._counter += 1- self._entries.append(- {- "id": self._counter,- "timestamp": time.time(),- "direction": "notification",- "method": body.get("method", "unknown"),- "body": body,- }- )- return-- jsonrpc_id = body.get("id")- method = (- self._request_methods.pop(jsonrpc_id, None)- if jsonrpc_id is not None- else None- )- request_time = (- self._request_times.pop(jsonrpc_id, None)- if jsonrpc_id is not None- else None- )- timestamp = time.time()- duration_ms = (- round((timestamp - request_time) * 1000, 1) if request_time else None- )- self._counter += 1- self._entries.append(- {- "id": self._counter,- "timestamp": timestamp,- "direction": "response",- "method": method,- "body": body,- "duration_ms": duration_ms,- }- )-- def get_since(self, since_id: int = 0) -> list[dict[str, Any]]:- return [e for e in self._entries if e["id"] > since_id]-- def log_bridge(self, body: dict[str, Any]) -> None:- method = body.get("method", "unknown")- self._counter += 1- self._entries.append(- {- "id": self._counter,- "timestamp": time.time(),- "direction": "bridge",- "method": method,- "body": body,- }- )-- def clear(self) -> None:- self._entries.clear()- self._request_methods.clear()- self._request_times.clear()---def _log_response_bytes(log: _MessageLog, raw: bytes, content_type: str) -> None:- """Parse accumulated proxy response bytes and log as message entries."""- if not raw:- return- try:- if "text/event-stream" in content_type:- for line in raw.decode("utf-8", errors="replace").splitlines():- if line.startswith("data: "):- with contextlib.suppress(json.JSONDecodeError):- log.log_response(json.loads(line[6:]))- else:- body = json.loads(raw)- if isinstance(body, list):- for item in body:- log.log_response(item)- else:- log.log_response(body)- except (json.JSONDecodeError, TypeError):- pass--_EXT_APPS_VERSION = "1.0.1"# Pin to the SDK version ext-apps 1.0.1 was compiled against so the client# and transport modules are API-compatible with the app-bridge internals.@@ -607,6 +490,7 @@ _LOG_PANEL_HTML = """\<script>(function() {var lastId = 0, totalCount = 0, panelWidth = 360;+ var maxRenderedEntries = 500;var panel = document.getElementById("mcp-log-panel");var entries = document.getElementById("mcp-log-entries");var countEl = document.getElementById("mcp-log-count");@@ -893,6 +777,9 @@ _LOG_PANEL_HTML = """\if (!shouldShow(el)) el.style.display = "none";entries.appendChild(el);}+ while (entries.children.length > maxRenderedEntries) {+ entries.removeChild(entries.firstElementChild);+ }if (atBottom || (firstPoll && panelVisible)) entries.scrollTop = entries.scrollHeight;firstPoll = false;})@@ -1558,7 +1445,7 @@ def _make_dev_app(body = await request.body()# Log MCP requests- if body and request.method == "POST":+ if log_panel and body and request.method == "POST":try:req_json = json.loads(body)if isinstance(req_json, list):@@ -1593,7 +1480,7 @@ def _make_dev_app(try:async for chunk in resp.aiter_bytes():yield chunk- if is_sse:+ if log_panel and is_sse:# Parse SSE events incrementallysse_buf += chunk.decode("utf-8", errors="replace")while "\r\n\r\n" in sse_buf or "\n\n" in sse_buf:@@ -1608,7 +1495,7 @@ def _make_dev_app(if line.startswith("data: "):with contextlib.suppress(json.JSONDecodeError):message_log.log_response(json.loads(line[6:]))- else:+ elif log_panel:buf.append(chunk)except (httpx2.RemoteProtocolError,@@ -1619,7 +1506,7 @@ def _make_dev_app(pass # Connection closed during shutdown β not an errorfinally:# Log non-SSE responses (JSON) after stream completes- if buf:+ if log_panel and buf:_log_response_bytes(message_log, b"".join(buf), "application/json")with contextlib.suppress(Exception):await resp.aclose()@@ -1674,7 +1561,8 @@ def _make_dev_app(async def api_logs_bridge(request: Request) -> Response:"""Log a bridge message (postMessage between app iframe and host)."""data = await request.json()- message_log.log_bridge(data.get("body", data))+ if log_panel:+ message_log.log_bridge(data.get("body", data))return Response(content="{}", media_type="application/json")async def api_logs_clear(request: Request) -> Response:diff --git a/fastmcp_slim/fastmcp/cli/apps_dev_log.py b/fastmcp_slim/fastmcp/cli/apps_dev_log.pynew file mode 100644index 000000000..258dd54f9--- /dev/null+++ b/fastmcp_slim/fastmcp/cli/apps_dev_log.py@@ -0,0 +1,211 @@+"""Bounded message capture for the FastMCP Apps development log panel."""++from __future__ import annotations++import contextlib+import json+import time+from collections import deque+from typing import Any++_MAX_LOG_ENTRIES = 1000+_MAX_LOG_BYTES = 8 * 1024 * 1024+_MAX_LOG_ENTRY_BYTES = 256 * 1024+_MAX_TRACKED_REQUESTS = 1000+_MAX_JSONRPC_ID_LENGTH = 128+++class _MessageLog:+ """Bounded in-memory buffer of MCP JSON-RPC messages for the dev UI."""++ def __init__(+ self,+ *,+ max_entries: int = _MAX_LOG_ENTRIES,+ max_bytes: int = _MAX_LOG_BYTES,+ max_entry_bytes: int = _MAX_LOG_ENTRY_BYTES,+ max_tracked_requests: int = _MAX_TRACKED_REQUESTS,+ ) -> None:+ self._entries: deque[dict[str, Any]] = deque()+ self._entry_sizes: deque[int] = deque()+ self._max_entries = max(0, max_entries)+ self._max_bytes = max(0, max_bytes)+ # Leave room for the method name and entry metadata when deciding+ # whether to truncate a body.+ self._max_entry_bytes = max(1024, max_entry_bytes)+ self._max_tracked_requests = max(0, max_tracked_requests)+ self._retained_bytes = 0+ self._counter = 0+ self._request_methods: dict[int | str, str] = {}+ self._request_times: dict[int | str, float] = {}++ @staticmethod+ def _method_name(body: dict[str, Any]) -> str:+ method = body.get("method", "unknown")+ if not isinstance(method, str):+ return "unknown"+ try:+ method[:64].encode("utf-8")+ except UnicodeEncodeError:+ return "unknown"+ return method[:64]++ def _bounded_body(self, body: dict[str, Any]) -> dict[str, Any]:+ """Copy JSON bodies and replace unusually large payloads with a marker."""+ try:+ encoded = json.dumps(+ body, ensure_ascii=False, separators=(",", ":")+ ).encode("utf-8")+ except (TypeError, ValueError, RecursionError, UnicodeEncodeError):+ return {"_fastmcp_log_truncated": True, "reason": "not JSON serializable"}++ if len(encoded) > self._max_entry_bytes - 768:+ return {+ "_fastmcp_log_truncated": True,+ "original_size_bytes": len(encoded),+ }+ # Detach retained data from mutable request objects and normalize it to+ # the same JSON values that the API will return.+ return json.loads(encoded)++ def _append(self, entry: dict[str, Any]) -> None:+ entry["body"] = self._bounded_body(entry["body"])+ encoded = json.dumps(entry, ensure_ascii=False, separators=(",", ":")).encode(+ "utf-8"+ )+ size = len(encoded)+ self._entries.append(entry)+ self._entry_sizes.append(size)+ self._retained_bytes += size++ while self._entries and (+ len(self._entries) > self._max_entries+ or self._retained_bytes > self._max_bytes+ ):+ self._entries.popleft()+ self._retained_bytes -= self._entry_sizes.popleft()++ def _remember_request(+ self, jsonrpc_id: int | str | None, method: str, timestamp: float+ ) -> None:+ if (+ jsonrpc_id is None+ or isinstance(jsonrpc_id, bool)+ or not isinstance(jsonrpc_id, (int, str))+ or len(str(jsonrpc_id)) > _MAX_JSONRPC_ID_LENGTH+ or self._max_tracked_requests == 0+ ):+ return++ # Repeated IDs replace their older timing record and move to the newest+ # position in the insertion-ordered dictionaries.+ self._request_methods.pop(jsonrpc_id, None)+ self._request_times.pop(jsonrpc_id, None)+ while len(self._request_times) >= self._max_tracked_requests:+ oldest_id = next(iter(self._request_times))+ self._request_times.pop(oldest_id, None)+ self._request_methods.pop(oldest_id, None)+ self._request_methods[jsonrpc_id] = method+ self._request_times[jsonrpc_id] = timestamp++ def log_request(self, body: dict[str, Any]) -> None:+ method = self._method_name(body)+ jsonrpc_id = body.get("id")+ timestamp = time.time()+ self._remember_request(jsonrpc_id, method, timestamp)+ self._counter += 1+ self._append(+ {+ "id": self._counter,+ "timestamp": timestamp,+ "direction": "request",+ "method": method,+ "body": body,+ }+ )++ def log_response(self, body: dict[str, Any]) -> None:+ # Server-initiated notifications have "method" but no "id"+ if "method" in body and "id" not in body:+ self._counter += 1+ self._append(+ {+ "id": self._counter,+ "timestamp": time.time(),+ "direction": "notification",+ "method": self._method_name(body),+ "body": body,+ }+ )+ return++ jsonrpc_id = body.get("id")+ method = (+ self._request_methods.pop(jsonrpc_id, None)+ if jsonrpc_id is not None+ else None+ )+ request_time = (+ self._request_times.pop(jsonrpc_id, None)+ if jsonrpc_id is not None+ else None+ )+ timestamp = time.time()+ duration_ms = (+ round((timestamp - request_time) * 1000, 1) if request_time else None+ )+ self._counter += 1+ self._append(+ {+ "id": self._counter,+ "timestamp": timestamp,+ "direction": "response",+ "method": method,+ "body": body,+ "duration_ms": duration_ms,+ }+ )++ def get_since(self, since_id: int = 0) -> list[dict[str, Any]]:+ return [entry for entry in self._entries if entry["id"] > since_id]++ def log_bridge(self, body: dict[str, Any]) -> None:+ method = self._method_name(body)+ self._counter += 1+ self._append(+ {+ "id": self._counter,+ "timestamp": time.time(),+ "direction": "bridge",+ "method": method,+ "body": body,+ }+ )++ def clear(self) -> None:+ self._entries.clear()+ self._entry_sizes.clear()+ self._retained_bytes = 0+ self._request_methods.clear()+ self._request_times.clear()+++def _log_response_bytes(log: _MessageLog, raw: bytes, content_type: str) -> None:+ """Parse accumulated proxy response bytes and log as message entries."""+ if not raw:+ return+ try:+ if "text/event-stream" in content_type:+ for line in raw.decode("utf-8", errors="replace").splitlines():+ if line.startswith("data: "):+ with contextlib.suppress(json.JSONDecodeError):+ log.log_response(json.loads(line[6:]))+ else:+ body = json.loads(raw)+ if isinstance(body, list):+ for item in body:+ log.log_response(item)+ else:+ log.log_response(body)+ except (json.JSONDecodeError, TypeError):+ passdiff --git a/tests/cli/test_apps_dev_server.py b/tests/cli/test_apps_dev_server.pyindex 13f48a04d..56b4bf4de 100644--- a/tests/cli/test_apps_dev_server.py+++ b/tests/cli/test_apps_dev_server.py@@ -15,13 +15,19 @@ TOKEN = "test-process-session-token"COOKIE = "fastmcp_dev_session_8080"-def build_client(*, host: str = "127.0.0.1", session: bool = False) -> TestClient:+def build_client(+ *,+ host: str = "127.0.0.1",+ session: bool = False,+ log_panel: bool = False,+ message_log: apps_dev._MessageLog | None = None,+) -> TestClient:app = apps_dev._make_dev_app("http://127.0.0.1:1/mcp","","",- apps_dev._MessageLog(),- False,+ message_log if message_log is not None else apps_dev._MessageLog(),+ log_panel,host=host,port=8080,session_token=TOKEN,@@ -32,6 +38,60 @@ def build_client(*, host: str = "127.0.0.1", session: bool = False) -> TestClienreturn client+class TestMessageLog:+ def test_entry_count_eviction_keeps_ids_monotonic(self):+ log = apps_dev._MessageLog(max_entries=2)++ for name in ("one", "two", "three"):+ log.log_bridge({"method": name})++ assert [entry["id"] for entry in log.get_since()] == [2, 3]+ assert [entry["id"] for entry in log.get_since(1)] == [2, 3]+ assert [entry["id"] for entry in log.get_since(2)] == [3]++ log.clear()+ log.log_bridge({"method": "four"})++ assert [entry["id"] for entry in log.get_since()] == [4]++ def test_byte_and_entry_limits_truncate_large_bodies(self):+ log = apps_dev._MessageLog(max_entries=10, max_bytes=450, max_entry_bytes=1024)++ log.log_bridge({"method": "large", "payload": "x" * 2048})+ first_entry = log.get_since()[0]+ assert first_entry["body"]["_fastmcp_log_truncated"] is True+ assert first_entry["body"]["original_size_bytes"] > 2048++ for index in range(8):+ log.log_bridge({"method": f"event-{index}"})++ assert len(log.get_since()) <= 10+ assert log._retained_bytes <= 450+ assert sum(log._entry_sizes) == log._retained_bytes+ assert all(size <= 1024 for size in log._entry_sizes)++ def test_request_and_response_entries_keep_correlation(self):+ log = apps_dev._MessageLog()++ log.log_request({"id": "call-1", "method": "tools/call"})+ log.log_response({"id": "call-1", "result": {"content": []}})++ entries = log.get_since()+ assert [entry["direction"] for entry in entries] == ["request", "response"]+ assert entries[1]["method"] == "tools/call"+ assert entries[1]["duration_ms"] is not None++ def test_unanswered_request_correlation_is_bounded(self):+ log = apps_dev._MessageLog(max_tracked_requests=2)++ for request_id in range(5):+ log.log_request({"id": request_id, "method": "tools/call"})++ assert len(log._request_methods) == 2+ assert len(log._request_times) == 2+ assert set(log._request_times) == {3, 4}++def create_launch(client: TestClient, tool: str = "ping") -> str:response = client.post("/api/launch", json={"tool": tool, "value": "x"})return response.json()@@ -464,7 +524,7 @@ class TestOrigin:assert response.json().startswith("/launch?id=")def test_log_endpoints_work_for_the_session(self):- client = build_client(session=True)+ client = build_client(session=True, log_panel=True)client.post("/api/logs/bridge", json={"body": {"method": "legitimate"}})logged = client.get("/api/logs").text@@ -559,6 +619,7 @@ class TestPages:):captured: list[httpx2.Request] = []original_client = httpx2.AsyncClient+ message_log = apps_dev._MessageLog()def backend(request: httpx2.Request) -> httpx2.Response:captured.append(request)@@ -576,7 +637,9 @@ class TestPages:monkeypatch.setattr(apps_dev.httpx2, "AsyncClient", client_factory)- response = build_client(session=True).post(+ client = build_client(session=True, message_log=message_log)+ client.post("/api/logs/bridge", json={"body": {"method": "bridge"}})+ response = client.post("/mcp",json={"jsonrpc": "2.0", "id": 1, "method": "ping"},headers={@@ -587,6 +650,8 @@ class TestPages:)assert response.status_code == 200+ assert response.json() == {"jsonrpc": "2.0", "id": 1, "result": {}}+ assert message_log.get_since() == []forwarded = {key.lower() for key in captured[0].headers}assert forwarded.isdisjoint({"cookie", "origin", "referer", "sec-fetch-site"})assert "set-cookie" not in response.headers