Skip to content

Commit 7ed57dc

Browse files
committed
refactor: make BaseContext/Context covariant in their type params
LifespanT and TransportT are only exposed via read-only properties (lifespan, transport), so covariance is sound. This lets a Context[AppState, HttpTC] be passed where a Context[object, TransportContext] is expected — needed for ServerRunner's middleware chain to compose without casts, and for reusable middleware to be typed Context[object, TransportContext] instead of relying on Any-slack.
1 parent 05a031a commit 7ed57dc

2 files changed

Lines changed: 3 additions & 3 deletions

File tree

src/mcp/server/context.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,8 @@ class ServerRequestContext(RequestContext[ServerSession], Generic[LifespanContex
3030
close_standalone_sse_stream: CloseSSEStreamCallback | None = None
3131

3232

33-
LifespanT = TypeVar("LifespanT", default=Any)
34-
TransportT = TypeVar("TransportT", bound=TransportContext, default=TransportContext)
33+
LifespanT = TypeVar("LifespanT", default=Any, covariant=True)
34+
TransportT = TypeVar("TransportT", bound=TransportContext, default=TransportContext, covariant=True)
3535

3636

3737
class Context(BaseContext[TransportT], PeerMixin, TypedServerRequestMixin, Generic[LifespanT, TransportT]):

src/mcp/shared/context.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222

2323
__all__ = ["BaseContext"]
2424

25-
TransportT = TypeVar("TransportT", bound=TransportContext, default=TransportContext)
25+
TransportT = TypeVar("TransportT", bound=TransportContext, default=TransportContext, covariant=True)
2626

2727

2828
class BaseContext(Generic[TransportT]):

0 commit comments

Comments
 (0)