From b812f93c030be7cec40104dfb158c500f5de682a Mon Sep 17 00:00:00 2001 From: EnesKartal Date: Wed, 25 Nov 2026 22:06:37 +0300 Subject: [PATCH] fix(client): clamp inbound ttlMs only for cacheable results --- src/mcp/client/session.py | 30 ++++++++++++++++++++++++-- tests/client/test_session.py | 41 ++++++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 2 deletions(-) diff --git a/src/mcp/client/session.py b/src/mcp/client/session.py index 35cae2d314..3152893a01 100644 --- a/src/mcp/client/session.py +++ b/src/mcp/client/session.py @@ -7,7 +7,20 @@ from functools import cache, reduce from operator import or_ from types import TracebackType, UnionType -from typing import TYPE_CHECKING, Annotated, Any, Final, Literal, Protocol, Self, TypeAlias, cast, get_args, overload +from typing import ( + TYPE_CHECKING, + Annotated, + Any, + Final, + Literal, + Protocol, + Self, + TypeAlias, + cast, + get_args, + get_origin, + overload, +) import anyio import anyio.abc @@ -78,6 +91,18 @@ def _clamp_inbound_ttl(raw: dict[str, Any]) -> None: raw["ttlMs"] = 0 +def _expects_cacheable_result(target: Any) -> bool: + """Return whether `target` (or any union arm inside it) is a `CacheableResult` subclass.""" + if isinstance(target, TypeAdapter): + target = getattr(cast(TypeAdapter[Any], target), "_type", None) + origin = get_origin(target) + if origin is Annotated: + return _expects_cacheable_result(get_args(target)[0]) + if isinstance(target, UnionType) or origin is not None: + return any(_expects_cacheable_result(arm) for arm in get_args(target)) + return isinstance(target, type) and issubclass(target, types.CacheableResult) + + @cache def _wire_fields(target: type[BaseModel] | UnionType) -> frozenset[str]: """Top-level wire keys `target` declares (its members', for a union).""" @@ -584,7 +609,8 @@ async def send_request( if metadata.on_resumption_token_update is not None: opts["on_resumption_token"] = metadata.on_resumption_token_update raw = await self._dispatcher.send_raw_request(method, data.get("params"), opts) - _clamp_inbound_ttl(raw) + if method in _methods.CACHEABLE_METHODS or _expects_cacheable_result(result_type): + _clamp_inbound_ttl(raw) # Literal fallback covers pre-handshake and stateless; matches runner.py. version = self._negotiated_version or "2025-11-25" try: diff --git a/tests/client/test_session.py b/tests/client/test_session.py index 7acbe01ce3..d9e724a917 100644 --- a/tests/client/test_session.py +++ b/tests/client/test_session.py @@ -2126,3 +2126,44 @@ def test_intercept_consumes_acks_for_live_routes_and_leaves_malformed_ones(): # Events deliver but are never consumed - they still tee to message_handler. assert intercept("notifications/tools/list_changed", meta) is False assert list(route._pending) == [ToolsListChanged()] # pyright: ignore[reportPrivateUsage] + + +@pytest.mark.anyio +async def test_non_cacheable_extension_result_preserves_negative_ttl_and_validates_strictly() -> None: + """Non-cacheable extension results must not have ttlMs clamped before validation, while CacheableResult does.""" + from typing import Annotated, Literal + + from pydantic import Field, ValidationError + + from mcp.shared.skills import ListSkillsRequest, ListSkillsResult + + class RetentionResult(types.Result): + result_type: Literal["task"] = "task" + ttl_ms: Annotated[int, Field(strict=True, ge=-9007199254740991, le=9007199254740991)] | None = None + + dispatcher = _ScriptedDispatcher( + _discover_result_dict(), + {"resultType": "task", "ttlMs": -1}, + {"resultType": "task", "ttlMs": -1.5}, + {"skills": [], "ttlMs": -5, "cacheScope": "private"}, + ) + with anyio.fail_after(5): + async with ClientSession(dispatcher=dispatcher) as session: + await session.discover() + ok = await session.send_request( + types.CallToolRequest(params=types.CallToolRequestParams(name="slow")), + RetentionResult, + ) + assert ok.ttl_ms == -1 + + with pytest.raises(ValidationError): + await session.send_request( + types.CallToolRequest(params=types.CallToolRequestParams(name="slow")), + RetentionResult, + ) + + skills = await session.send_request( + ListSkillsRequest(), # type: ignore[arg-type] + ListSkillsResult, + ) + assert skills.ttl_ms == 0