-
Notifications
You must be signed in to change notification settings - Fork 1.8k
feat: add lifespan context manager support #203
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 5 commits
2c7bd83
d3ea900
e598750
e5815bd
fddba00
4d3e05f
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
|
@@ -68,7 +68,8 @@ async def main(): | |||||
import logging | ||||||
import warnings | ||||||
from collections.abc import Awaitable, Callable | ||||||
from typing import Any, Sequence | ||||||
from contextlib import AbstractAsyncContextManager, asynccontextmanager | ||||||
from typing import Any, AsyncIterator, Generic, Sequence, TypeVar | ||||||
|
||||||
from anyio.streams.memory import MemoryObjectReceiveStream, MemoryObjectSendStream | ||||||
from pydantic import AnyUrl | ||||||
|
@@ -101,13 +102,36 @@ def __init__( | |||||
self.tools_changed = tools_changed | ||||||
|
||||||
|
||||||
class Server: | ||||||
LifespanResultT = TypeVar("LifespanResultT") | ||||||
|
||||||
|
||||||
@asynccontextmanager | ||||||
async def lifespan(server: "Server") -> AsyncIterator[object]: | ||||||
"""Default lifespan context manager that does nothing. | ||||||
|
||||||
Args: | ||||||
server: The server instance this lifespan is managing | ||||||
|
||||||
Returns: | ||||||
An empty context object | ||||||
""" | ||||||
yield {} | ||||||
|
||||||
|
||||||
class Server(Generic[LifespanResultT]): | ||||||
def __init__( | ||||||
self, name: str, version: str | None = None, instructions: str | None = None | ||||||
self, | ||||||
name: str, | ||||||
version: str | None = None, | ||||||
instructions: str | None = None, | ||||||
lifespan: Callable[ | ||||||
["Server"], AbstractAsyncContextManager[LifespanResultT] | ||||||
] = lifespan, | ||||||
): | ||||||
self.name = name | ||||||
self.version = version | ||||||
self.instructions = instructions | ||||||
self.lifespan = lifespan | ||||||
self.request_handlers: dict[ | ||||||
type, Callable[..., Awaitable[types.ServerResult]] | ||||||
] = { | ||||||
|
@@ -446,9 +470,14 @@ async def run( | |||||
raise_exceptions: bool = False, | ||||||
): | ||||||
with warnings.catch_warnings(record=True) as w: | ||||||
async with ServerSession( | ||||||
read_stream, write_stream, initialization_options | ||||||
) as session: | ||||||
from contextlib import AsyncExitStack | ||||||
|
||||||
async with AsyncExitStack() as stack: | ||||||
lifespan_context = await stack.enter_async_context(self.lifespan(self)) | ||||||
session = await stack.enter_async_context( | ||||||
ServerSession(read_stream, write_stream, initialization_options) | ||||||
) | ||||||
Comment on lines
+475
to
+479
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Is this different from doing There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The AsyncExitStack() version provides more granular control over multiple context managers. If an error occurs during the second enter_async_context, the first one will still be properly cleaned up. Chatted more with Claude about it, we came to the. conclusion that AsyncExitStack is better here. |
||||||
|
||||||
async for message in session.incoming_messages: | ||||||
logger.debug(f"Received message: {message}") | ||||||
|
||||||
|
@@ -460,21 +489,28 @@ async def run( | |||||
): | ||||||
with responder: | ||||||
await self._handle_request( | ||||||
message, req, session, raise_exceptions | ||||||
message, | ||||||
req, | ||||||
session, | ||||||
lifespan_context, | ||||||
raise_exceptions, | ||||||
) | ||||||
case types.ClientNotification(root=notify): | ||||||
await self._handle_notification(notify) | ||||||
|
||||||
for warning in w: | ||||||
logger.info( | ||||||
f"Warning: {warning.category.__name__}: {warning.message}" | ||||||
"Warning: %s: %s", | ||||||
warning.category.__name__, | ||||||
warning.message, | ||||||
) | ||||||
|
||||||
async def _handle_request( | ||||||
self, | ||||||
message: RequestResponder, | ||||||
req: Any, | ||||||
session: ServerSession, | ||||||
lifespan_context: object, | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
raise_exceptions: bool, | ||||||
): | ||||||
logger.info(f"Processing request of type {type(req).__name__}") | ||||||
|
@@ -491,6 +527,7 @@ async def _handle_request( | |||||
message.request_id, | ||||||
message.request_meta, | ||||||
session, | ||||||
lifespan_context, | ||||||
) | ||||||
) | ||||||
response = await handler(req) | ||||||
|
Uh oh!
There was an error while loading. Please reload this page.