diff --git a/AGENTS.md b/AGENTS.md index 2fa3970..f2c2e7f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -47,10 +47,25 @@ one, is answered with JSON, as before, where `MCP::Server` of the Perl `MCP` opens the stream for every result that is a promise. The stream needs a client that has `text/event-stream` in its `Accept`; for another one the notifications go nowhere and the result is JSON. The stream has no inactivity timeout, as a -tool may take long between two notifications, and `X-Accel-Buffering: no`, so -that nginx passes each event at once. The connection of the stream that closes -before the result cancels the `Context`, which emits `cancelled` once, and the -result of a cancelled request is not written. A notification that the client +tool may take long between two notifications, a comment every `heartbeat` +seconds, of the helper `heartbeat` of Pyjoyment, which keeps a proxy from +closing it, and `X-Accel-Buffering: no`, so that nginx passes each event at +once. The connection of the stream that closes before the result cancels the +`Context`, which emits `cancelled` once, and the result of a cancelled request +is not written. + +The promise of a tool, a prompt, a resource or a completion, or the one of its +coroutine, is cancelled with the `Context`, by `Context.cancellable` and +`cancel` of `Pyjo.Promise`, as Pyjoyment cancels an action that is a +coroutine when its connection closes: the coroutine gets the exception of the +cancellation of the reactor where it waits, and a request of `Pyjo.UserAgent` +that it waits for closes its connection, so that a request to a slow service +stops too. The action of `to_action` is not a coroutine, so Pyjoyment does not +cancel it itself. The cancellation is a `BaseException`, which +`Pyjo.JSON.RPC` would log as an error of the server, so `cancellable` rejects +its promise with an error of JSON-RPC instead, whose response is not written +anyway. With the reactor of asyncio, a coroutine whose task has not started +yet does not run at all, so its `finally` blocks do not run either. A notification that the client did not ask for, progress without a `progressToken` or a log message below its `logLevel`, is not sent at all. @@ -212,9 +227,8 @@ A server ends a subscription with a response, not with `notifications/cancelled` which the page of the cancellation names for it: the page of the subscriptions, which describes the graceful closure, gives the response. Over Streamable HTTP, the event `finish` of the event loop, which a graceful stop emits, ends the subscriptions of its connections, as a stream that stays -open would keep the server waiting until its timeout, and a recurring timer -writes a comment of the stream every `heartbeat` seconds, which keeps a proxy -from closing it. Over stdio, the end of the input ends the subscriptions of its +open would keep the server waiting until its timeout, and its comments every +`heartbeat` seconds are those of any stream of events. Over stdio, the end of the input ends the subscriptions of its peer, as `Pyjo.JSON.RPC.serve` closes the stream only once the requests in progress have their responses. @@ -296,7 +310,11 @@ mise exec -- uv run --group sdk --with-editable ../Pyjoyment python -m Pyjo.Prov ## Development The distribution depends on the release of Pyjoyment on PyPI, with the lowest -version that has what it uses, which `uv.lock` pins. A change of Pyjoyment that +version that has what it uses, which `uv.lock` pins. Until the release after +0.3.0, it uses `cancel` of `Pyjo.Promise` and the helper `heartbeat` of the +branch `main` of Pyjoyment, of `[tool.uv.sources]`, while its lowest version +stays 0.3.0, which the workflow Build installs from PyPI to import the wheel: +the release replaces both, the source and the lowest version. A change of Pyjoyment that is not released yet would be its Git repository in `[tool.uv.sources]` of `pyproject.toml`, until its release, and not a path to the checkout next to this one: uv applies the sources of a dependency of Git, so whoever installs diff --git a/Pyjo/MCP/Prompt.py b/Pyjo/MCP/Prompt.py index a561f54..a2758e9 100644 --- a/Pyjo/MCP/Prompt.py +++ b/Pyjo/MCP/Prompt.py @@ -204,7 +204,10 @@ def get_p(self, arguments: Mapping[str, Any], context: Any = None) -> Pyjo.Promi Call the function with the arguments, and return a :mod:`Pyjo.Promise` of the result of the prompt, as ``prompts/get`` gives it, without its ``resultType``, or rejected with a :class:`Pyjo.JSON.RPC.Error` of - arguments that are not valid, or an exception of the function. :: + arguments that are not valid, or an exception of the function. A + promise or a coroutine of the function is cancelled with the + :class:`Pyjo.MCP.Server.Context` of the request, as + :meth:`Pyjo.MCP.Server.Context.cancellable` does. :: # {'messages': [{'role': 'user', 'content': {'type': 'text', 'text': 'Review this Python code:\\nx = 1'}}]} prompt.get_p({'code': 'x = 1'}).then(print).wait() @@ -226,6 +229,8 @@ def get_p(self, arguments: Mapping[str, Any], context: Any = None) -> Pyjo.Promi if inspect.iscoroutine(value): value = Pyjo.Promise.new(value) if isinstance(value, Pyjo.Promise.object): + if context is not None: + value = context.cancellable(value) return value.then(self.result) return Pyjo.Promise.resolve(self.result(value)) diff --git a/Pyjo/MCP/Resource.py b/Pyjo/MCP/Resource.py index 6f8a0c9..588a7c3 100644 --- a/Pyjo/MCP/Resource.py +++ b/Pyjo/MCP/Resource.py @@ -167,7 +167,10 @@ def read_p(self, context: Any = None) -> Pyjo.Promise.object: Call the function, and return a :mod:`Pyjo.Promise` of the result of the resource, as ``resources/read`` gives it, without its - ``resultType``, or rejected with an exception of the function. :: + ``resultType``, or rejected with an exception of the function. A promise + or a coroutine of the function is cancelled with the + :class:`Pyjo.MCP.Server.Context` of the request, as + :meth:`Pyjo.MCP.Server.Context.cancellable` does. :: # {'contents': [{'uri': 'file:///project/README.md', 'mimeType': 'text/markdown', 'text': '# Pyjo-MCP'}]} resource.read_p().then(print).wait() @@ -179,6 +182,8 @@ def read_p(self, context: Any = None) -> Pyjo.Promise.object: if inspect.iscoroutine(value): value = Pyjo.Promise.new(value) if isinstance(value, Pyjo.Promise.object): + if context is not None: + value = context.cancellable(value) return value.then(self.result) return Pyjo.Promise.resolve(self.result(value)) diff --git a/Pyjo/MCP/Server.py b/Pyjo/MCP/Server.py index a1778e2..aec606d 100644 --- a/Pyjo/MCP/Server.py +++ b/Pyjo/MCP/Server.py @@ -186,7 +186,9 @@ def cancelled(context): Emitted once when the client abandons the request, as when it closes the connection of a response of Streamable HTTP before the result, or sends ``notifications/cancelled`` of the request over the transport stdio, so - that a tool that runs long stops. :: + that a tool that runs long stops. A coroutine of a tool, or the promise + that the tool returns, is cancelled by the server, with + :meth:`cancellable`, and another one subscribes to the event. :: id = Pyjo.IOLoop.recurring(1, lambda: ...) context.on('cancelled', lambda context: Pyjo.IOLoop.remove(id)) @@ -379,6 +381,46 @@ def cancel(self) -> Self: self.emit('cancelled') return self + def cancellable(self, promise: Pyjo.Promise.object) -> Pyjo.Promise.object: + """:: + + promise = context.cancellable(promise) + + Cancel the promise with :meth:`Pyjo.Promise.Pyjo_Promise.cancel` when + the client abandons the request, and return a promise of its value, + which the server does for the promise or the coroutine of a tool, a + prompt, a resource and a completion: a coroutine gets the exception of + the cancellation of the reactor, as :class:`asyncio.CancelledError`, + where it waits, so that its ``finally`` blocks run, and a request of + :meth:`Pyjo.UserAgent.Pyjo_UserAgent.start_p` that it waits for closes + its connection. That cancellation rejects the returned promise with an + error of JSON-RPC, not of the server, which is not logged, as nothing + reads its response anymore. :: + + # A coroutine that stops where it waits when the client goes away + async def slow() -> str: + await Pyjo.Promise.timer(60) + return 'Done' + + promise = context.cancellable(Pyjo.Promise.new(slow())) + """ + + def cancelled(context: Context) -> None: + promise.cancel() + + if self._cancelled: + promise.cancel() + else: + self.once('cancelled', cancelled) + + # The cancellation of the promise, not an error of the server + def failed(e: Any = None) -> Pyjo.Promise.object: + if self._cancelled and not isinstance(e, Exception): + return Pyjo.Promise.reject(Pyjo.JSON.RPC.Error.new(Pyjo.JSON.RPC.INTERNAL_ERROR, 'Request cancelled')) + return Pyjo.Promise.reject(e) + + return promise.catch(failed) + def elicit(self, key: str, message: str, schema: dict[str, Any] | None = None) -> dict[str, Any]: """:: @@ -579,10 +621,11 @@ def __init__(self, name: str = 'Pyjo.MCP', version: str = '1.0.0', instructions: interval = server.heartbeat server.heartbeat = 15 - How often a subscription of Streamable HTTP sends a comment of the - stream of events, which keeps a connection without notifications from - being closed by a proxy, in seconds, ``30`` by default, or ``0`` for - never. + How often a stream of events of Streamable HTTP, as a subscription or + a tool that runs long, sends a comment, with the helper ``heartbeat`` + of :mod:`Pyjoyment`, which keeps a connection without notifications + from being closed by a proxy, in seconds, ``30`` by default, or ``0`` + for never. """ self.instructions = instructions @@ -978,12 +1021,12 @@ def to_action(self) -> Callable[['Pyjoyment.Controller.object'], Any]: notification of the request, of :meth:`Context.notify`, turns the response into a stream of events, ``text/event-stream``, where the ``Accept`` of the request has it, with the notifications and then the - response, and a connection that closes before the result cancels the - :class:`Context`. A subscription of ``subscriptions/listen`` is such a - stream, which needs the ``Accept`` and stays open, with a comment every - :attr:`heartbeat` seconds, until the client closes the connection, or - until the event loop stops gracefully, which ends the subscription with - its response. :: + response, with a comment every :attr:`heartbeat` seconds, and a + connection that closes before the result cancels the :class:`Context`. + A subscription of ``subscriptions/listen`` is such a stream, which + needs the ``Accept`` and stays open, until the client closes the + connection, or until the event loop stops gracefully, which ends the + subscription with its response. :: # Pyjoyment.Lite any('/mcp', server.to_action()) @@ -1017,6 +1060,8 @@ def stream(notification: dict[str, Any]) -> None: c.helpers.inactivity_timeout(0) c.res.headers.header('X-Accel-Buffering', 'no') c.write_sse() + if self.heartbeat: + c.helpers.heartbeat(self.heartbeat) c.write_sse({'text': Pyjo.JSON.to_json(notification)}) if 'text/event-stream' in (c.req.headers.accept or ''): @@ -1115,7 +1160,9 @@ def _complete(self, context: Context, /, **params: Any) -> Pyjo.Promise.object: return Pyjo.Promise.reject(e) if inspect.iscoroutine(values): values = Pyjo.Promise.new(values) - promise = values if isinstance(values, Pyjo.Promise.object) else Pyjo.Promise.resolve(values) + promise = ( + context.cancellable(values) if isinstance(values, Pyjo.Promise.object) else Pyjo.Promise.resolve(values) + ) def result(values: Any = None) -> dict[str, Any]: values = [str(v) for v in cast(list[Any], values or [])] @@ -1247,14 +1294,11 @@ def _listen(self, context: Context, **params: Any) -> Pyjo.Promise.object: promise = Pyjo.Promise.new() subscriptions = self._subscriptions loop = Pyjo.IOLoop.singleton - timer: str | None = None finish: Any = None def remove() -> None: if subscription in subscriptions: subscriptions.remove(subscription) - if timer is not None: - loop.remove(timer) if finish is not None: loop.unsubscribe('finish', finish) @@ -1273,10 +1317,8 @@ def cancelled(context: Context) -> None: subscriptions.append(subscription) subscription.notify('notifications/subscriptions/acknowledged', {'notifications': honored}) - # A connection of HTTP gets the comments that keep it open, and ends with a graceful stop of the event loop - if (c := context.controller) is not None: - if self.heartbeat: - timer = loop.recurring(self.heartbeat, lambda loop: c.write_sse({'comment': 'keepalive'})) + # A connection of HTTP ends with a graceful stop of the event loop + if context.controller is not None: def stopping(loop: Any) -> None: end() diff --git a/Pyjo/MCP/Tool.py b/Pyjo/MCP/Tool.py index 4e57545..6d57100 100644 --- a/Pyjo/MCP/Tool.py +++ b/Pyjo/MCP/Tool.py @@ -248,7 +248,9 @@ def call_p(self, arguments: Mapping[str, Any], context: Any = None) -> Pyjo.Prom Call the function with the arguments, and return a :mod:`Pyjo.Promise` of the result of the tool, as ``tools/call`` gives it, without its ``resultType``, or rejected with an exception of the function that is not an - :class:`Error`, an error of the server. :: + :class:`Error`, an error of the server. A promise or a coroutine of the + function is cancelled with the :class:`Pyjo.MCP.Server.Context` of the + request, as :meth:`Pyjo.MCP.Server.Context.cancellable` does. :: # {'content': [{'type': 'text', 'text': '3'}], 'structuredContent': 3, 'isError': False} tool.call_p({'a': 1, 'b': 2}).then(print).wait() @@ -269,6 +271,8 @@ def call_p(self, arguments: Mapping[str, Any], context: Any = None) -> Pyjo.Prom if inspect.iscoroutine(value): value = Pyjo.Promise.new(value) if isinstance(value, Pyjo.Promise.object): + if context is not None: + value = context.cancellable(value) def failed(e: Any = None) -> Any: if isinstance(e, Error): diff --git a/docs/guides/tutorial.rst b/docs/guides/tutorial.rst index f1d0990..4f32a86 100644 --- a/docs/guides/tutorial.rst +++ b/docs/guides/tutorial.rst @@ -141,10 +141,12 @@ asks for them in the ``_meta`` of its request, with a ``progressToken`` and the lowest level of the log messages that it wants, and the notifications that it did not ask for go nowhere. Over Streamable HTTP, the first notification turns the response into a stream of events, which ends with the result, when -the client accepts one, and a client that closes the connection before the -result cancels the request, which -:attr:`~Pyjo.MCP.Server.Context.is_cancelled` tells. Over the transport stdio, -the notifications are messages of the same stream: +the client accepts one, and which a comment keeps open while the tool is +silent. A client that closes the connection before the result cancels the +request, which stops a tool that is a coroutine where it waits, with the +requests of :mod:`Pyjo.UserAgent` that it waits for, and which +:attr:`~Pyjo.MCP.Server.Context.is_cancelled` tells another one. Over the +transport stdio, the notifications are messages of the same stream: .. literalinclude:: tutorial/progress.py :language: python diff --git a/pyproject.toml b/pyproject.toml index e3ecc9b..6e897c4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -34,6 +34,11 @@ sdk = ["mcp>=2.3.0"] [tool.uv.dependency-groups] docs = { requires-python = ">=3.14" } +# Pyjoyment of Git until its release after 0.3.0, with Pyjo.Promise.cancel and the helper heartbeat, when the lowest +# version of the dependency becomes that release +[tool.uv.sources] +pyjoyment = { git = "https://github.com/pyjoyment/Pyjoyment", branch = "main" } + # Only the package Pyjo.MCP: the package Pyjo is the one of Pyjoyment, whose namespace extend_path keeps open [tool.hatch.build.targets.wheel] only-include = ["Pyjo/MCP"] diff --git a/t/MCP_Prompt.py b/t/MCP_Prompt.py index 20a28b6..c51e965 100644 --- a/t/MCP_Prompt.py +++ b/t/MCP_Prompt.py @@ -1,5 +1,7 @@ +import Pyjo.IOLoop import Pyjo.JSON.RPC import Pyjo.MCP.Prompt +import Pyjo.MCP.Server import Pyjo.Promise from Pyjo.Test import * @@ -162,6 +164,23 @@ async def broken() -> str: isa_ok(get(Pyjo.MCP.Prompt.new(broken), {}), ValueError, 'exception of a coroutine rejects') + # A coroutine that the cancellation of the context stops where it waits + stopped = [] + + async def slow() -> str: + try: + await Pyjo.Promise.timer(5) + finally: + stopped.append(True) + return 'Too late' + + context = Pyjo.MCP.Server.Context.new() + Pyjo.IOLoop.timer(0.01, lambda loop: context.cancel()) + error = get(Pyjo.MCP.Prompt.new(slow), {}, context) + isa_ok(error, Pyjo.JSON.RPC.Error, 'cancelled') + is_ok(error.message, 'Request cancelled', 'message') + is_deeply_ok(stopped, [True], 'finally of the coroutine') + with subtest('Errors'): def explain(topic: str) -> str: diff --git a/t/MCP_Resource.py b/t/MCP_Resource.py index 2168ca9..d921209 100644 --- a/t/MCP_Resource.py +++ b/t/MCP_Resource.py @@ -1,4 +1,7 @@ +import Pyjo.IOLoop +import Pyjo.JSON.RPC import Pyjo.MCP.Resource +import Pyjo.MCP.Server import Pyjo.Promise from Pyjo.Test import * @@ -123,6 +126,23 @@ async def broken() -> str: isa_ok(read(Pyjo.MCP.Resource.new('file:///broken', broken)), ValueError, 'exception of a coroutine rejects') + # A coroutine that the cancellation of the context stops where it waits + stopped = [] + + async def slow() -> str: + try: + await Pyjo.Promise.timer(5) + finally: + stopped.append(True) + return 'Too late' + + context = Pyjo.MCP.Server.Context.new() + Pyjo.IOLoop.timer(0.01, lambda loop: context.cancel()) + error = read(Pyjo.MCP.Resource.new('file:///slow', slow), context) + isa_ok(error, Pyjo.JSON.RPC.Error, 'cancelled') + is_ok(error.message, 'Request cancelled', 'message') + is_deeply_ok(stopped, [True], 'finally of the coroutine') + with subtest('Errors'): def broken(): diff --git a/t/MCP_Server.py b/t/MCP_Server.py index 3433489..de68b06 100644 --- a/t/MCP_Server.py +++ b/t/MCP_Server.py @@ -786,6 +786,34 @@ async def owners(context, value, arguments): tc.error_is({'code': -32602, 'message': 'Invalid argument'}) tc.ua.close() + # The coroutine of a completion that the cancellation of the request stops where it waits + stopped = [] + exceptions = [] + completing.on('exception', lambda server, e, context: exceptions.append(e)) + + async def slowly(value, arguments): + try: + await Pyjo.Promise.timer(5) + finally: + stopped.append(True) + return [] + + completing.resource('slow://{n}', lambda n: n, name='slow', complete={'n': slowly}) + context = Pyjo.MCP.Server.Context.new() + params = { + 'ref': {'type': 'ref/resource', 'uri': 'slow://{n}'}, + 'argument': {'name': 'n', 'value': ''}, + '_meta': META, + } + results = [] + promise = completing.dispatch_p( + {'jsonrpc': '2.0', 'id': 1, 'method': 'completion/complete', 'params': params}, context + ) + Pyjo.IOLoop.timer(0.01, lambda loop: context.cancel()) + promise.then(results.append).wait() + is_deeply_ok(results[0]['error'], {'code': -32603, 'message': 'Request cancelled'}, 'cancelled') + is_deeply_ok((stopped, exceptions), ([True], []), 'coroutine cancelled without an error of the server') + plain = Pyjo.MCP.Server.new() plain.prompt('review', lambda code: code) result = plain.dispatch_p({'jsonrpc': '2.0', 'id': 1, 'method': 'server/discover', 'params': {'_meta': META}}) @@ -873,6 +901,45 @@ def interrupt(content, event): is_deeply_ok(cancelled, [True], 'cancelled') Pyjo.Promise.timer(0.5).wait() is_deeply_ok(cancelled, [True], 'once') + + # The coroutine of a tool that the client abandons stops where it waits, which is not an error of the server + stopped = [] + exceptions = [] + notifying.on('exception', lambda server, e, context: exceptions.append(e)) + + @notifying.tool(context=True) + async def sleepy(context) -> str: + context.notify_progress(0) + try: + await Pyjo.Promise.timer(5) + finally: + stopped.append(True) + return 'Too late' + + request = n.client.build_request('tools/call', {'name': 'sleepy', 'arguments': {}, '_meta': meta}) + tx = n.client.build_tx(request) + tx.res.content.on('sse', interrupt) + n.ua.start(tx) + Pyjo.Promise.timer(0.1).wait() + is_deeply_ok(stopped, [True], 'coroutine cancelled') + is_deeply_ok(exceptions, [], 'no error of the server') + + # The comments of a stream of a tool that runs long + notifying.heartbeat = 0.05 + + @notifying.tool(context=True) + def pause(context) -> str: + context.notify_progress(0) + return Pyjo.Promise.timer(0.2, 'Paused') + + tx = n.client.build_tx(n.client.build_request('tools/call', {'name': 'pause', 'arguments': {}, '_meta': meta})) + read = [] + tx.on('connection', lambda tx, id: n.ua.ioloop.stream(id).on('read', lambda stream, chunk: read.append(chunk))) + n.ua.start(tx, lambda ua, tx: None) + Pyjo.Promise.timer(0.3).wait() + ok(b''.join(read).count(b'\r\n: heartbeat\r\n') > 1, 'comments of the stream of a tool') + ok(b'Paused' in b''.join(read), 'result after the comments') + notifying.heartbeat = 0 n.ua.close() # The transport stdio, whose notifications are messages of the stream before the response @@ -969,7 +1036,7 @@ def send(self, message): tx.res.content.on('sse', lambda content, event=None: event and events.append(json.loads(event['text']))) s.ua.start(tx, lambda ua, tx: None) Pyjo.Promise.timer(0.2).wait() - ok(b''.join(read).count(b'\r\n: keepalive\r\n') > 1, 'comments of the stream of events') + ok(b''.join(read).count(b'\r\n: heartbeat\r\n') > 1, 'comments of the stream of events') is_deeply_ok( events[0]['params']['notifications'], {'promptsListChanged': True, 'resourceSubscriptions': ['a']}, 'honored' ) @@ -1043,6 +1110,25 @@ def listen(id, notifications): ok(waiting[0][0].is_cancelled, 'tool cancelled') is_ok(len(peer.sent), 4, 'no responses of cancelled requests') + # The coroutine of a tool that the peer cancels stops where it waits + stopped = [] + + @listening.tool + async def sleepy() -> str: + try: + await Pyjo.Promise.timer(5) + finally: + stopped.append(True) + return 'Too late' + + params = {'name': 'sleepy', 'arguments': {}, '_meta': META} + peer.emit('message', json.dumps({'jsonrpc': '2.0', 'id': 5, 'method': 'tools/call', 'params': params})) + Pyjo.Promise.timer(0.01).wait() + peer.emit('message', json.dumps({**cancel, 'params': {'requestId': 5}})) + Pyjo.Promise.timer(0.01).wait() + is_deeply_ok(stopped, [True], 'coroutine cancelled') + is_ok(len(peer.sent), 4, 'no response of the cancelled coroutine') + peer.emit('end') Pyjo.Promise.timer(0.01).wait() is_deeply_ok( diff --git a/t/MCP_Tool.py b/t/MCP_Tool.py index b547a39..9fa519a 100644 --- a/t/MCP_Tool.py +++ b/t/MCP_Tool.py @@ -1,4 +1,7 @@ +import Pyjo.IOLoop +import Pyjo.JSON.RPC import Pyjo.JSON.Schema +import Pyjo.MCP.Server import Pyjo.MCP.Tool import Pyjo.Promise @@ -222,6 +225,23 @@ async def broken() -> int: isa_ok(call(Pyjo.MCP.Tool.new(broken), {}), ValueError, 'exception of a coroutine rejects') + # A coroutine that the cancellation of the context stops where it waits + stopped = [] + + async def slow() -> str: + try: + await Pyjo.Promise.timer(5) + finally: + stopped.append(True) + return 'Too late' + + context = Pyjo.MCP.Server.Context.new() + Pyjo.IOLoop.timer(0.01, lambda loop: context.cancel()) + error = call(Pyjo.MCP.Tool.new(slow), {}, context) + isa_ok(error, Pyjo.JSON.RPC.Error, 'cancelled') + is_ok(error.message, 'Request cancelled', 'message') + is_deeply_ok(stopped, [True], 'finally of the coroutine') + with subtest('Errors'): def book(date: str) -> str: diff --git a/t/docs/MCP_Server.py b/t/docs/MCP_Server.py index 98ede9a..c1fb48e 100644 --- a/t/docs/MCP_Server.py +++ b/t/docs/MCP_Server.py @@ -2,6 +2,7 @@ import Pyjo.JSON.RPC import Pyjo.MCP.Server import Pyjo.MCP.Test +import Pyjo.Promise import Pyjoyment from Pyjo.Test import * @@ -200,6 +201,28 @@ def cancelled(context): ok(context.is_cancelled, 'cancelled') is_ok(context.notify('notifications/message'), False, 'no notification of an abandoned request') +with subtest('Context.cancellable'): + context = Pyjo.MCP.Server.Context.new() + stopped = [] + + # A coroutine that stops where it waits when the client goes away + async def slow() -> str: + try: + await Pyjo.Promise.timer(60) + finally: + stopped.append(True) + return 'Done' + + promise = context.cancellable(Pyjo.Promise.new(slow())) + Pyjo.IOLoop.timer(0.01, lambda loop: context.cancel()) + errors = [] + promise.catch(errors.append).wait() + is_ok(errors[0].message, 'Request cancelled', 'error of JSON-RPC') + is_deeply_ok(stopped, [True], 'coroutine cancelled') + errors.clear() + context.cancellable(Pyjo.Promise.new(slow())).catch(errors.append).wait() + is_ok(errors[0].code, Pyjo.JSON.RPC.INTERNAL_ERROR, 'already cancelled') + with subtest('Context.elicit'): context = Pyjo.MCP.Server.Context.new() context.client_capabilities = {'elicitation': {}} diff --git a/uv.lock b/uv.lock index ebdbba2..8e81f50 100644 --- a/uv.lock +++ b/uv.lock @@ -809,7 +809,7 @@ sdk = [ docs = ">=3.14" [package.metadata] -requires-dist = [{ name = "pyjoyment", specifier = ">=0.3.0" }] +requires-dist = [{ name = "pyjoyment", git = "https://github.com/pyjoyment/Pyjoyment?branch=main" }] [package.metadata.requires-dev] docs = [{ name = "sphinx", marker = "python_full_version >= '3.14'", specifier = ">=9.2.0" }] @@ -817,12 +817,8 @@ sdk = [{ name = "mcp", specifier = ">=2.3.0" }] [[package]] name = "pyjoyment" -version = "0.3.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/68/8b/a884c5adcda58db4b93ed48fd5dbd1124f51c43aecb346f1df4d6acaa818/pyjoyment-0.3.0.tar.gz", hash = "sha256:7cc7a6766f60c4b807b4d52643fc3b6a008dcb2378635158201b727a95cb23d8", size = 2086251, upload-time = "2026-11-05T16:11:40.5Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/2a/63/e91e7992501d15fe09bbeeb07ee9ed1002c7c9d7e64a28dd953f5891188a/pyjoyment-0.3.0-py3-none-any.whl", hash = "sha256:ed58806bdd0dc333c042afaf88eba3d30a7a7f6670d2375fc57555f800d14e60", size = 1266314, upload-time = "2026-11-05T16:11:38.891Z" }, -] +version = "0.3.1.dev1" +source = { git = "https://github.com/pyjoyment/Pyjoyment?branch=main#11e47e8259283f590d4f6f46382dd3146c370fb5" } [[package]] name = "pyjwt"