Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 28 additions & 2 deletions src/mcp/client/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)."""
Expand Down Expand Up @@ -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:
Expand Down
41 changes: 41 additions & 0 deletions tests/client/test_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Loading