refactor: improve lifespan context typing and documentation

- Add proper generic parameter for lifespan context type
- Update README with TypedDict example for strong typing
- Fix context variable initialization in server
- Improve property return type safety
- Remove redundant documentation
- Ensure compatibility with existing tests
This commit is contained in:
David Soria Parra
2025-02-12 22:12:09 +00:00
parent fddba00723
commit 4d3e05f6f6
4 changed files with 22 additions and 16 deletions

View File

@@ -85,7 +85,10 @@ from mcp.shared.session import RequestResponder
logger = logging.getLogger(__name__)
request_ctx: contextvars.ContextVar[RequestContext[ServerSession]] = (
LifespanResultT = TypeVar("LifespanResultT")
# This will be properly typed in each Server instance's context
request_ctx: contextvars.ContextVar[RequestContext[ServerSession, Any]] = (
contextvars.ContextVar("request_ctx")
)
@@ -102,9 +105,6 @@ class NotificationOptions:
self.tools_changed = tools_changed
LifespanResultT = TypeVar("LifespanResultT")
@asynccontextmanager
async def lifespan(server: "Server") -> AsyncIterator[object]:
"""Default lifespan context manager that does nothing.
@@ -212,7 +212,7 @@ class Server(Generic[LifespanResultT]):
)
@property
def request_context(self) -> RequestContext[ServerSession]:
def request_context(self) -> RequestContext[ServerSession, LifespanResultT]:
"""If called outside of a request context, this will raise a LookupError."""
return request_ctx.get()
@@ -510,7 +510,7 @@ class Server(Generic[LifespanResultT]):
message: RequestResponder,
req: Any,
session: ServerSession,
lifespan_context: object,
lifespan_context: LifespanResultT,
raise_exceptions: bool,
):
logger.info(f"Processing request of type {type(req).__name__}")