Skip to content
Merged
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
2 changes: 1 addition & 1 deletion ehrapy/mcp/dispatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from fastmcp import Context # noqa: TC002
from fastmcp.tools.tool import ToolResult
from fastmcp.tools import ToolResult
from fastmcp.utilities.types import Image

from ehrapy.mcp.catalog import get_callable, get_namespace_kind
Expand Down
2 changes: 1 addition & 1 deletion ehrapy/mcp/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

from typing import TYPE_CHECKING, Any

from fastmcp.tools.tool import ToolResult
from fastmcp.tools import ToolResult

if TYPE_CHECKING:
from ehrapy.mcp.policy import SecurityPolicyError
Expand Down
4 changes: 2 additions & 2 deletions ehrapy/mcp/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from ehrapy.mcp.tools import ALL_TOOLS_LIST

if TYPE_CHECKING:
from fastmcp.tools.tool import ToolResult
from fastmcp.tools import ToolResult

pass

Expand Down Expand Up @@ -45,7 +45,7 @@

def _append_note(result: ToolResult, note: str, folded: list[str]) -> ToolResult:
"""Append a steering note to a tool result on both channels."""
from fastmcp.tools.tool import ToolResult as _ToolResult
from fastmcp.tools import ToolResult as _ToolResult

try:
blocks = list(result.content or [])
Expand Down
56 changes: 46 additions & 10 deletions ehrapy/mcp/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
import threading
from typing import Any

from mcp_types.version import HANDSHAKE_PROTOCOL_VERSIONS

_SESSIONS_LOCK = threading.RLock()


Expand Down Expand Up @@ -38,22 +40,56 @@ def set_latest_edata_id(self, edata_id: str | None) -> None:
_SESSIONS: dict[str, _EHRapySession] = {}


def _probe(ctx: Any, attr: str) -> Any:
"""Read an attribute defensively: FastMCP raises outside an active request."""
try:
return getattr(ctx, attr, None)
except (RuntimeError, AttributeError):
return None


def _session_key(ctx: Any) -> str:
"""Derive a stable per-client key from a FastMCP Context.

Each attribute is probed defensively: FastMCP raises when these are touched
outside an active request context, and a server-wide fallback to "default" is
preferable to propagating that error into every tool call.
Not every attribute a Context exposes is an identity, and one of them used to
be mistaken for one.

``client_id`` is the only cross-era-stable identity FastMCP offers: it is
whatever the client puts in ``_meta.client_id``, and it reads the same on both
protocol eras. A supervisor may send it, so it is consulted first.

``session_id`` is **not** a per-client key on the modern ``2026-07-28``
protocol. MCP SDK v2 constructs a fresh ``Connection`` for every request on
that era (``mcp/server/runner.py``), so FastMCP finds no cached value, mints a
new ``uuid4``, and throws it away with the connection
(``fastmcp/server/context.py``). Its own docstring only promises "a generated
ID for other transports". It is trustworthy only where it is a real
negotiated identity: a stateful HTTP transport speaking a handshake-era
protocol version, where it is the client's ``mcp-session-id``. Everywhere else
it changes on every call, which silently loses the active dataset handle.

stdio serves exactly one client per process -- one stdin/stdout pair, one
connection -- so a process-global key is correct there by construction, on
either era. The in-process transport used by the test suite is treated the
same way, because it is single-tenant too.

Each attribute is probed defensively, and a server-wide fallback is
preferable to propagating an error into every tool call.
"""
if ctx is None:
return "default"
for attr in ("client_id", "session_id", "request_id"):
try:
value = getattr(ctx, attr, None)
except (RuntimeError, AttributeError):
continue
if value:
return str(value)

client_id = _probe(ctx, "client_id")
if client_id:
return f"client:{client_id}"

transport = _probe(ctx, "transport")
protocol = _probe(_probe(ctx, "request_context"), "protocol_version")
if transport not in ("stdio", None) and protocol in HANDSHAKE_PROTOCOL_VERSIONS:
session_id = _probe(ctx, "session_id")
if session_id:
return f"session:{session_id}"

return "default"


Expand Down
2 changes: 1 addition & 1 deletion ehrapy/mcp/tools/dispatch_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from typing import TYPE_CHECKING, Any, Literal

from fastmcp import Context # noqa: TC002
from fastmcp.tools.tool import ToolResult
from fastmcp.tools import ToolResult

from ehrapy.mcp.catalog import (
function_help,
Expand Down
2 changes: 1 addition & 1 deletion ehrapy/mcp/tools/ingestion.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import ehrdata.io as ed_io
from fastmcp import Context # noqa: TC002
from fastmcp.tools.tool import ToolResult
from fastmcp.tools import ToolResult

from ehrapy.mcp.edata_store import load_edata, save_edata
from ehrapy.mcp.errors import mcp_error, path_access_error, policy_error_result, unknown_handle_error
Expand Down
2 changes: 1 addition & 1 deletion ehrapy/mcp/tools/meta.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from typing import Any

from fastmcp import Context # noqa: TC002
from fastmcp.tools.tool import ToolResult
from fastmcp.tools import ToolResult

import ehrapy as ep
from ehrapy.mcp.policy import get_allowed_roots, is_read_only_mode
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ dask = [
]
leiden = ["igraph"] # careful - GPL
mcp = [
"fastmcp>=3.4,<4",
"fastmcp>=4.0.11,<5",
"numpydoc",
"platformdirs",
"igraph", # careful - GPL; needed because the MCP workflow guide steers agents to leiden
Expand Down
142 changes: 142 additions & 0 deletions tests/mcp/test_session_key.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
"""Tests for how the per-client session key is derived.

`ctx.session_id` looks like a client identity and is not one. On the modern
`2026-07-28` protocol, MCP SDK v2 builds a fresh `Connection` per request, so
FastMCP mints a new `uuid4` for `session_id` on every tool call and discards it
with the connection. Keying sessions on it silently loses the active dataset
handle from the second call onward.

These tests pin the reasoning rather than the implementation, so the probe order
cannot be "simplified" back into the bug.
"""

from __future__ import annotations

from typing import Any

import pytest

from ehrapy.mcp.session import _session_key, get_session, reset_sessions

MODERN = "2026-07-28"
HANDSHAKE = "2025-11-25"


class FakeRequestContext:
def __init__(self, protocol_version: str | None) -> None:
self.protocol_version = protocol_version


class FakeContext:
"""Stands in for a FastMCP Context, including the era-dependent instability."""

def __init__(
self,
*,
transport: str | None,
protocol_version: str | None,
session_id: str | None = None,
client_id: str | None = None,
) -> None:
self.transport = transport
self.request_context = FakeRequestContext(protocol_version)
self._session_id = session_id
self.client_id = client_id

@property
def session_id(self) -> str:
# Mirrors FastMCP: a fresh uuid4 per call unless something cached it.
if self._session_id is None:
self._session_id = f"uuid-{id(self):x}-next"
return self._session_id


def test_modern_era_session_id_is_not_an_identity() -> None:
"""The core bug: on 2026-07-28, consecutive calls get different session ids."""
first = FakeContext(transport="stdio", protocol_version=MODERN)
second = FakeContext(transport="stdio", protocol_version=MODERN)

assert first.session_id != second.session_id, "premise: session_id must be unstable here"


@pytest.mark.parametrize("transport", ["stdio", None])
def test_stdio_and_in_process_fall_back_to_a_process_key(transport: str | None) -> None:
"""One client per process means one key, whichever era we are on.

A changing `session_id` must not change the key: for stdio the transport
carries a single client, so the id FastMCP mints is noise.
"""
keys = {
_session_key(FakeContext(transport=transport, protocol_version=era))
for era in (MODERN, HANDSHAKE)
for _ in range(3)
}
assert keys == {"default"}, f"expected one process-global key, got {keys}"


def test_stateful_handshake_http_may_use_the_negotiated_session_id() -> None:
"""Where `session_id` really is an identity, it is still used."""
a = FakeContext(transport="streamable-http", protocol_version=HANDSHAKE, session_id="sid-a")
b = FakeContext(transport="streamable-http", protocol_version=HANDSHAKE, session_id="sid-b")

assert _session_key(a) == "session:sid-a"
assert _session_key(b) == "session:sid-b"
assert _session_key(a) != _session_key(b)


def test_modern_http_does_not_trust_a_per_request_session_id() -> None:
"""Stateful HTTP still mints per call on the modern era, so it is not trusted."""
keys = {_session_key(FakeContext(transport="streamable-http", protocol_version=MODERN)) for _ in range(3)}
assert keys == {"default"}


def test_unknown_protocol_version_does_not_trust_session_id() -> None:
"""An unrecognised era falls back rather than guessing."""
ctx = FakeContext(transport="streamable-http", protocol_version="1999-01-01", session_id="sid")
assert _session_key(ctx) == "default"


def test_client_id_wins_and_isolates_clients() -> None:
"""`client_id` is stable on both eras, so it outranks everything else."""
a = FakeContext(transport="streamable-http", protocol_version=MODERN, client_id="renyi-1", session_id="x")
b = FakeContext(transport="streamable-http", protocol_version=MODERN, client_id="renyi-2", session_id="y")

assert _session_key(a) == "client:renyi-1"
assert _session_key(b) == "client:renyi-2"


def test_active_handle_survives_repeated_calls_on_the_modern_era() -> None:
"""The regression itself: an ingested dataset stays the active one.

Without the era check this fails on the second call with NO_ACTIVE_DATASET.
"""
reset_sessions()
try:
# Set the handle once, as ingest_dataset does...
get_session(FakeContext(transport="stdio", protocol_version=MODERN)).set_latest_edata_id("handle-abc")
# ...then every later call must find it, without being told again.
for _ in range(4):
session = get_session(FakeContext(transport="stdio", protocol_version=MODERN))
assert session.get_latest_edata_id() == "handle-abc"
finally:
reset_sessions()


def test_missing_context_attributes_fall_back() -> None:
"""Probing must never raise, whatever the context looks like."""

class Hostile:
@property
def client_id(self) -> Any:
raise RuntimeError("outside request context")

@property
def transport(self) -> Any:
raise RuntimeError("outside request context")

@property
def session_id(self) -> Any:
raise RuntimeError("outside request context")

assert _session_key(Hostile()) == "default"
assert _session_key(None) == "default"
Loading