Skip to content

Cache TTL normalization changes non-cacheable extension retention values before validation #3866

Open

Description

@UncleSaurus

ClientSession.send_request() applies _clamp_inbound_ttl(raw) to every result before parsing it. A ClientExtension claiming a non-cacheable tools/call result therefore cannot preserve its own ttlMs semantics.

Reproduced through public Client(MCPServer(...)), ClientExtension, and ResultClaim, on published 2.3.0 (Python 3.14) and current main 77001c9 (Python 3.13). Each row makes exactly one tools/call:

Server value Expected extension validation Actual parsed value
-1 Preserve -1 0
-1.5 Reject fractional retention 0, accepted
-9007199254740992 Reject outside signed safe-integer range 0, accepted

This blocks Kestrel's implementation of the published Tasks extension: its retention schema is different from core cache freshness. The SDK's own CACHEABLE_METHODS excludes tools/call and extension task verbs. Ordinary extension requests using session.send_request also pass through the unconditional normalization. Declaring the extension's validation more strictly cannot recover values already changed by the SDK.

Expected: normalize cache hints only for cacheable results; leave other extension values intact for their own models to validate. Existing core cache normalization (including resources/read) and the native Skills cacheable extension must keep working. We can contribute a narrow correction and native regressions if useful; no new Tasks API is requested here.

Complete in-memory reproducer
from collections.abc import Sequence
from typing import Annotated, Any, Literal
import importlib.metadata
import json
import anyio
import mcp_types as types
from pydantic import Field, ValidationError
from mcp import Client
from mcp.client import ClaimContext, ClientExtension, ResultClaim
from mcp.server.context import ServerRequestContext
from mcp.server.context import CallNext, HandlerResult
from mcp.server.extension import Extension
from mcp.server.mcpserver import MCPServer

class RetentionResult(types.Result):
    result_type: Literal["task"] = "task"
    ttl_ms: Annotated[int, Field(strict=True, ge=-9007199254740991, le=9007199254740991)] | None

async def unresolved(result: RetentionResult, ctx: ClaimContext) -> types.CallToolResult:
    raise NotImplementedError

class RetentionClient(ClientExtension):
    identifier = "com.example/retention"
    def claims(self) -> Sequence[ResultClaim[Any]]:
        return [ResultClaim(result_type="task", model=RetentionResult, resolve=unresolved)]

class Issuer(Extension):
    identifier = "com.example/retention"
    def __init__(self, value: int | float) -> None:
        self.value = value
        self.calls = 0
    async def intercept_tool_call(self, params: types.CallToolRequestParams, ctx: ServerRequestContext[Any, Any], call_next: CallNext) -> HandlerResult:
        assert params.name == "issue"
        self.calls += 1
        return {"resultType": "task", "ttlMs": self.value}

async def main() -> None:
    rows = []
    for value in [-1, -1.5, -9007199254740992]:
        issuer = Issuer(value)
        server = MCPServer("retention", extensions=[issuer])
        @server.tool()
        def issue() -> types.CallToolResult:
            raise NotImplementedError
        with anyio.fail_after(5):
            async with Client(server, extensions=[RetentionClient()]) as client:
                try:
                    result = await client.session.call_tool("issue", allow_claimed=True)
                except ValidationError:
                    observed: int | None | str = "ValidationError"
                else:
                    assert isinstance(result, RetentionResult)
                    observed = result.ttl_ms
        assert issuer.calls == 1
        rows.append({"wire_ttl": value, "native_observed": observed, "tools_call_count": issuer.calls})
    print(json.dumps({"sdk": importlib.metadata.version("mcp"), "rows": rows}))

if __name__ == "__main__":
    anyio.run(main)

AI disclosure: Codex prepared this report and reproducer and ran the reproductions, under explicit authorization from Kestrel's human maintainer. No response rewriting or installed SDK modification was used.

Activity

  1. added
    bugSomething isn't working
    spec-2026-07-28Concerns the SDK's implementation of the 2026-07-28 MCP spec revision
    v2Affects the v2 line (2.x on main)
    on Nov 16, 2026
  2. UncleSaurus commented on Nov 16, 2026

    @UncleSaurus
    Author

    Implementation review found that restricting normalization to core cacheable methods and concrete CacheableResult classes is insufficient. This supported call would regress:

    await client.session.send_request(
        ListSkillsRequest(params=ListSkillsParams()),
        TypeAdapter(ListSkillsResult),
    )

    For a native Skills response with ttlMs: -1, the class form succeeds with zero freshness while the adapter form raises validation. I reproduced that difference through an in-memory Client(server) connection. I have not submitted that patch.

    Moving extension normalization into the hand-written CacheableResult, activated by inbound validation context from send_request, would handle class/adapter/union forms without guessing semantics from field names. Core wire validation and explicit discovery would still need their earlier normalization. However, this needs an explicit behavior decision: model-local normalization can run after subclass or enclosing BeforeValidator/WrapValidator code, and an unscoped context flag would also affect nested cacheable models. The current normalization happens only on the top-level response before those validators.

    Before expanding this into a two-module change, what should enclosing validators observe, and should tolerance remain strictly top-level? The essential requirement for our use case is that non-cacheable extension retention reaches its own validation unchanged; cacheable class and adapter forms should agree. I can prepare the corresponding regression tests and fix once that boundary is settled.

    AI-assisted investigation and testing, submitted at the Kestrel operator’s explicit direction. This is a validation bug report, not a claim of Tasks implementation or conformance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingspec-2026-07-28Concerns the SDK's implementation of the 2026-07-28 MCP spec revisionv2Affects the v2 line (2.x on main)

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions