holon-sh 0.0.1.dev15__tar.gz → 0.0.1.dev17__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev17}/PKG-INFO +1 -1
- {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev17}/holon/ext/events/_server.py +29 -95
- {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev17}/holon/serve.py +1 -8
- {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev17}/pyproject.toml +1 -1
- {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev17}/tests/test_events.py +64 -94
- {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev17}/.gitignore +0 -0
- {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev17}/LICENSE +0 -0
- {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev17}/README.md +0 -0
- {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev17}/holon/client.py +0 -0
- {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev17}/holon/context.py +0 -0
- {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev17}/holon/ext/__init__.py +0 -0
- {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev17}/holon/ext/events/__init__.py +0 -0
- {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev17}/holon/ext/events/_client.py +0 -0
- {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev17}/holon/ext/events/_wire.py +0 -0
- {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev17}/holon/ext/files/__init__.py +0 -0
- {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev17}/holon/ext/files/_client.py +0 -0
- {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev17}/holon/ext/files/_server.py +0 -0
- {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev17}/holon/ext/files/_wire.py +0 -0
- {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev17}/holon/py.typed +0 -0
- {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev17}/scripts/verify_distribution.py +0 -0
- {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev17}/tests/fixtures/caller/holon/apps/__init__.py +0 -0
- {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev17}/tests/test_context.py +0 -0
- {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev17}/tests/test_elicit.py +0 -0
- {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev17}/tests/test_files.py +0 -0
- {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev17}/tests/test_package.py +0 -0
- {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev17}/tests/test_runtime.py +0 -0
- {holon_sh-0.0.1.dev15 → holon_sh-0.0.1.dev17}/tests/test_serve.py +0 -0
|
@@ -22,10 +22,7 @@ import anyio
|
|
|
22
22
|
from mcp.server.context import CallNext, HandlerResult, ServerRequestContext
|
|
23
23
|
from mcp.server.extension import Extension, MethodBinding
|
|
24
24
|
from mcp.server.lowlevel.server import Server
|
|
25
|
-
from mcp.server.streamable_http_manager import StreamableHTTPSessionManager
|
|
26
|
-
from mcp.server.transport_security import RequestBodyLimitMiddleware
|
|
27
25
|
from mcp.shared.exceptions import MCPError
|
|
28
|
-
from mcp.shared.inbound import MCP_METHOD_HEADER
|
|
29
26
|
from mcp.shared.subscriptions import SUBSCRIPTION_ID_META_KEY
|
|
30
27
|
from mcp.types import (
|
|
31
28
|
INTERNAL_ERROR,
|
|
@@ -38,7 +35,6 @@ from mcp.types import (
|
|
|
38
35
|
)
|
|
39
36
|
from pydantic import Field, StrictInt, StrictStr, TypeAdapter, ValidationError
|
|
40
37
|
from pydantic_core import to_json, to_jsonable_python
|
|
41
|
-
from starlette.types import ASGIApp, Receive, Scope, Send
|
|
42
38
|
|
|
43
39
|
from holon.context import RequestContext, get_context
|
|
44
40
|
from holon.ext.events._wire import (
|
|
@@ -55,8 +51,6 @@ from holon.ext.events._wire import (
|
|
|
55
51
|
logger = logging.getLogger(__package__)
|
|
56
52
|
|
|
57
53
|
_MAX_POLL_EVENTS = 1000
|
|
58
|
-
# Set on a request that came through `Events.asgi`, whose answer can be a stream.
|
|
59
|
-
_STREAMS = "holon.ext.events.streams"
|
|
60
54
|
# What each event type keeps of what it emits: seconds, events, and bytes of JSON data.
|
|
61
55
|
_KEEP_AGE = 600.0
|
|
62
56
|
_KEEP_EVENTS = 10_000
|
|
@@ -77,7 +71,10 @@ T = TypeVar("T")
|
|
|
77
71
|
Match: TypeAlias = Callable[[RequestContext, Event[D], A], bool]
|
|
78
72
|
Transform: TypeAlias = Callable[[RequestContext, Event[D], A], object]
|
|
79
73
|
Authorize: TypeAlias = Callable[[RequestContext, A], bool | Awaitable[bool]]
|
|
80
|
-
|
|
74
|
+
Cleanup: TypeAlias = Callable[[], None | Awaitable[None]]
|
|
75
|
+
SubscriptionHook: TypeAlias = Callable[
|
|
76
|
+
[RequestContext, A, str], Cleanup | None | Awaitable[Cleanup | None]
|
|
77
|
+
]
|
|
81
78
|
|
|
82
79
|
|
|
83
80
|
class _SubscribeParams(RequestParams):
|
|
@@ -138,9 +135,7 @@ class _Kept:
|
|
|
138
135
|
class _Entry:
|
|
139
136
|
"""A subscription, held by one or more streams or poll leases."""
|
|
140
137
|
|
|
141
|
-
|
|
142
|
-
"""The request that began it."""
|
|
143
|
-
setup: asyncio.Future[None]
|
|
138
|
+
setup: asyncio.Future[Cleanup | None]
|
|
144
139
|
holds: set[_Hold] = field(default_factory=set)
|
|
145
140
|
teardown: asyncio.Future[None] | None = None
|
|
146
141
|
|
|
@@ -171,7 +166,6 @@ class EventType(Generic[A, D]):
|
|
|
171
166
|
_delivery: list[Delivery]
|
|
172
167
|
_authorize: Authorize[A] | None
|
|
173
168
|
_on_subscribe: SubscriptionHook[A] | None
|
|
174
|
-
_on_unsubscribe: SubscriptionHook[A] | None
|
|
175
169
|
# Emitted events, oldest first; `_dropped` is the last sequence evicted.
|
|
176
170
|
_kept: list[_Kept] = field(default_factory=list)
|
|
177
171
|
_sequence: int = 0
|
|
@@ -358,42 +352,11 @@ class EventType(Generic[A, D]):
|
|
|
358
352
|
await asyncio.shield(entry.teardown)
|
|
359
353
|
|
|
360
354
|
|
|
361
|
-
# The SDK's private handler, which streams a 2026-07-28 request even on a JSON endpoint, when this SDK has it.
|
|
362
|
-
def _streaming(manager: StreamableHTTPSessionManager) -> ASGIApp | None:
|
|
363
|
-
try:
|
|
364
|
-
from mcp.server._streamable_http_modern import handle_modern_request
|
|
365
|
-
except ImportError:
|
|
366
|
-
return None
|
|
367
|
-
expected = ["app", "security_settings", "json_response", "lifespan_state"]
|
|
368
|
-
expected += ["scope", "receive", "send"]
|
|
369
|
-
taken = list(inspect.signature(handle_modern_request).parameters)
|
|
370
|
-
if taken != expected or not hasattr(manager, "_lifespan_state"):
|
|
371
|
-
return None
|
|
372
|
-
|
|
373
|
-
async def stream(scope: Scope, receive: Receive, send: Send) -> None:
|
|
374
|
-
await handle_modern_request(
|
|
375
|
-
manager.app,
|
|
376
|
-
manager.security_settings,
|
|
377
|
-
False,
|
|
378
|
-
manager._lifespan_state,
|
|
379
|
-
scope,
|
|
380
|
-
receive,
|
|
381
|
-
send,
|
|
382
|
-
)
|
|
383
|
-
|
|
384
|
-
return RequestBodyLimitMiddleware(stream, manager.max_request_body_size)
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
def _streams(ctx: ServerRequestContext[Any, Any]) -> bool:
|
|
388
|
-
# Over stdio every request can stream; over HTTP, only one that came through `Events.asgi`.
|
|
389
|
-
return ctx.request is None or bool(ctx.request.scope.get(_STREAMS))
|
|
390
|
-
|
|
391
|
-
|
|
392
355
|
class Events(Extension):
|
|
393
356
|
"""The event types an app serves as MCP Events.
|
|
394
357
|
|
|
395
358
|
Pass it to ``MCPServer(extensions=[events], middleware=[events])``, or call :meth:`serve` on a low-level
|
|
396
|
-
``Server``.
|
|
359
|
+
``Server``. Push needs an endpoint whose answers can stream: over Streamable HTTP, not ``json_response=True``.
|
|
397
360
|
"""
|
|
398
361
|
|
|
399
362
|
identifier = EVENTS_EXTENSION
|
|
@@ -420,7 +383,6 @@ class Events(Extension):
|
|
|
420
383
|
delivery: Sequence[Delivery] = ("poll", "push"),
|
|
421
384
|
authorize: Authorize[A] | None = None,
|
|
422
385
|
on_subscribe: SubscriptionHook[A] | None = None,
|
|
423
|
-
on_unsubscribe: SubscriptionHook[A] | None = None,
|
|
424
386
|
) -> EventType[A, D]:
|
|
425
387
|
"""Declare an event type.
|
|
426
388
|
|
|
@@ -434,7 +396,7 @@ class Events(Extension):
|
|
|
434
396
|
delivery: The delivery modes offered.
|
|
435
397
|
authorize: ``(context, arguments)``: whether the caller may subscribe, checked again while subscribed.
|
|
436
398
|
on_subscribe: ``(context, arguments, subscription_id)``: called when a subscription begins.
|
|
437
|
-
|
|
399
|
+
May return a zero-argument cleanup function, called when the subscription ends.
|
|
438
400
|
"""
|
|
439
401
|
if name in self._types:
|
|
440
402
|
raise ValueError(f"Event {name} is already declared.")
|
|
@@ -461,7 +423,6 @@ class Events(Extension):
|
|
|
461
423
|
list(delivery),
|
|
462
424
|
authorize,
|
|
463
425
|
on_subscribe,
|
|
464
|
-
on_unsubscribe,
|
|
465
426
|
)
|
|
466
427
|
self._types[name] = declared
|
|
467
428
|
return declared
|
|
@@ -500,25 +461,6 @@ class Events(Extension):
|
|
|
500
461
|
}
|
|
501
462
|
return result
|
|
502
463
|
|
|
503
|
-
def asgi(self, manager: StreamableHTTPSessionManager) -> ASGIApp:
|
|
504
|
-
"""The endpoint of ``manager``, with push.
|
|
505
|
-
|
|
506
|
-
Mount it where ``manager.handle_request`` would be, inside any authentication.
|
|
507
|
-
"""
|
|
508
|
-
streaming = _streaming(manager)
|
|
509
|
-
|
|
510
|
-
async def app(scope: Scope, receive: Receive, send: Send) -> None:
|
|
511
|
-
method = dict(scope.get("headers", [])).get(MCP_METHOD_HEADER.encode())
|
|
512
|
-
if scope["type"] == "http" and not manager.json_response:
|
|
513
|
-
scope = {**scope, _STREAMS: True}
|
|
514
|
-
elif scope["type"] == "http" and streaming and method is not None:
|
|
515
|
-
scope = {**scope, _STREAMS: True}
|
|
516
|
-
if method == b"events/stream":
|
|
517
|
-
return await streaming(scope, receive, send)
|
|
518
|
-
await manager.handle_request(scope, receive, send)
|
|
519
|
-
|
|
520
|
-
return app
|
|
521
|
-
|
|
522
464
|
async def _list(
|
|
523
465
|
self, ctx: ServerRequestContext[Any, Any], params: PaginatedRequestParams
|
|
524
466
|
) -> HandlerResult:
|
|
@@ -527,14 +469,12 @@ class Events(Extension):
|
|
|
527
469
|
if not cursor.isdigit():
|
|
528
470
|
raise MCPError(INVALID_PARAMS, "Invalid cursor for events/list")
|
|
529
471
|
start = int(cursor)
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
listed.append({**each._descriptor, "delivery": delivery})
|
|
537
|
-
result: dict[str, Any] = {"events": listed}
|
|
472
|
+
listed = list(self._types.values())[start : start + _LIST_PAGE_SIZE]
|
|
473
|
+
result: dict[str, Any] = {
|
|
474
|
+
"events": [
|
|
475
|
+
{**each._descriptor, "delivery": each._delivery} for each in listed
|
|
476
|
+
]
|
|
477
|
+
}
|
|
538
478
|
if start + _LIST_PAGE_SIZE < len(self._types):
|
|
539
479
|
result["nextCursor"] = str(start + _LIST_PAGE_SIZE)
|
|
540
480
|
return result
|
|
@@ -542,7 +482,7 @@ class Events(Extension):
|
|
|
542
482
|
async def _poll(
|
|
543
483
|
self, ctx: ServerRequestContext[Any, Any], params: _SubscribeParams
|
|
544
484
|
) -> HandlerResult:
|
|
545
|
-
request = await self._subscription(params, "poll"
|
|
485
|
+
request = await self._subscription(params, "poll")
|
|
546
486
|
declared = request.type
|
|
547
487
|
opened = declared._sequence
|
|
548
488
|
await self._lease(request)
|
|
@@ -578,13 +518,13 @@ class Events(Extension):
|
|
|
578
518
|
|
|
579
519
|
# Checked in the order of https://github.com/modelcontextprotocol/experimental-ext-triggers-events/blob/main/docs/design-sketch-proposal.md#error-codes
|
|
580
520
|
async def _subscription(
|
|
581
|
-
self, params: _SubscribeParams, delivery: Delivery
|
|
521
|
+
self, params: _SubscribeParams, delivery: Delivery
|
|
582
522
|
) -> _Request:
|
|
583
523
|
self._loop = self._loop or asyncio.get_running_loop()
|
|
584
524
|
declared = self._types.get(params.name)
|
|
585
525
|
if declared is None:
|
|
586
526
|
raise MCPError.from_error_data(_NOT_FOUND)
|
|
587
|
-
if delivery not in declared._delivery
|
|
527
|
+
if delivery not in declared._delivery:
|
|
588
528
|
raise MCPError(
|
|
589
529
|
UNSUPPORTED,
|
|
590
530
|
"Unsupported",
|
|
@@ -661,16 +601,16 @@ class Events(Extension):
|
|
|
661
601
|
entry = subscriptions.get(request.id)
|
|
662
602
|
if entry is None:
|
|
663
603
|
setup = asyncio.ensure_future(self._set_up(request))
|
|
664
|
-
entry = subscriptions[request.id] = _Entry(
|
|
604
|
+
entry = subscriptions[request.id] = _Entry(setup)
|
|
665
605
|
hold = _Hold(request, entry)
|
|
666
606
|
entry.holds.add(hold)
|
|
667
607
|
return hold
|
|
668
608
|
|
|
669
|
-
async def _set_up(self, request: _Request) -> None:
|
|
609
|
+
async def _set_up(self, request: _Request) -> Cleanup | None:
|
|
670
610
|
if request.type._on_subscribe is None:
|
|
671
|
-
return
|
|
611
|
+
return None
|
|
672
612
|
async with asyncio.timeout(_SUBSCRIBE_TIMEOUT):
|
|
673
|
-
await _settle(
|
|
613
|
+
return await _settle(
|
|
674
614
|
request.type._on_subscribe(
|
|
675
615
|
request.context, request.arguments, request.id
|
|
676
616
|
)
|
|
@@ -688,23 +628,17 @@ class Events(Extension):
|
|
|
688
628
|
entry.holds.discard(hold)
|
|
689
629
|
_release(self._held, hold.request.caller, 1)
|
|
690
630
|
if not entry.holds:
|
|
691
|
-
entry.teardown = asyncio.ensure_future(self._tear_down(
|
|
631
|
+
entry.teardown = asyncio.ensure_future(self._tear_down(hold))
|
|
692
632
|
|
|
693
|
-
#
|
|
694
|
-
async def _tear_down(self,
|
|
695
|
-
request =
|
|
633
|
+
# Cleanup follows only a setup that succeeded; a failing hook is logged.
|
|
634
|
+
async def _tear_down(self, hold: _Hold) -> None:
|
|
635
|
+
request = hold.request
|
|
696
636
|
try:
|
|
697
|
-
await entry.setup
|
|
698
|
-
if
|
|
699
|
-
await _settle(
|
|
700
|
-
request.type._on_unsubscribe(
|
|
701
|
-
request.context, request.arguments, request.id
|
|
702
|
-
)
|
|
703
|
-
)
|
|
637
|
+
cleanup = await hold.entry.setup
|
|
638
|
+
if cleanup is not None:
|
|
639
|
+
await _settle(cleanup())
|
|
704
640
|
except Exception:
|
|
705
|
-
logger.exception(
|
|
706
|
-
"An event subscription's on_subscribe or on_unsubscribe failed"
|
|
707
|
-
)
|
|
641
|
+
logger.exception("An event subscription's setup or cleanup failed")
|
|
708
642
|
finally:
|
|
709
643
|
del request.type._subscriptions[request.id]
|
|
710
644
|
|
|
@@ -753,7 +687,7 @@ class Events(Extension):
|
|
|
753
687
|
async def _stream(
|
|
754
688
|
self, ctx: ServerRequestContext[Any, Any], params: _SubscribeParams
|
|
755
689
|
) -> HandlerResult:
|
|
756
|
-
request = await self._subscription(params, "push"
|
|
690
|
+
request = await self._subscription(params, "push")
|
|
757
691
|
declared = request.type
|
|
758
692
|
await declared._settled(request.id)
|
|
759
693
|
hold = self._open(request)
|
|
@@ -28,7 +28,6 @@ from starlette.responses import FileResponse, PlainTextResponse, Response
|
|
|
28
28
|
from starlette.types import ASGIApp, Receive, Scope, Send
|
|
29
29
|
|
|
30
30
|
from holon.context import _Request, _request
|
|
31
|
-
from holon.ext.events import Events
|
|
32
31
|
|
|
33
32
|
__all__ = ["App", "load", "serve"]
|
|
34
33
|
|
|
@@ -92,13 +91,7 @@ def _asgi(app: App) -> ASGIApp:
|
|
|
92
91
|
enable_dns_rebinding_protection=False
|
|
93
92
|
),
|
|
94
93
|
)
|
|
95
|
-
|
|
96
|
-
events = next(
|
|
97
|
-
(each for each in server.middleware if isinstance(each, Events)), None
|
|
98
|
-
)
|
|
99
|
-
mcp = AuthContextMiddleware(
|
|
100
|
-
manager.handle_request if events is None else events.asgi(manager)
|
|
101
|
-
)
|
|
94
|
+
mcp = AuthContextMiddleware(server.session_manager.handle_request)
|
|
102
95
|
platform = os.environ.get("HOLON_PLATFORM") == "1"
|
|
103
96
|
|
|
104
97
|
async def dispatch(scope: Scope, receive: Receive, send: Send) -> None:
|
|
@@ -2,7 +2,6 @@ import asyncio
|
|
|
2
2
|
import base64
|
|
3
3
|
import json
|
|
4
4
|
import socket
|
|
5
|
-
import sys
|
|
6
5
|
from contextlib import asynccontextmanager
|
|
7
6
|
from functools import partial, wraps
|
|
8
7
|
|
|
@@ -30,7 +29,7 @@ from starlette.applications import Starlette
|
|
|
30
29
|
from starlette.routing import Mount
|
|
31
30
|
|
|
32
31
|
from holon.client import Apps
|
|
33
|
-
from holon.ext.events import Events, EventType,
|
|
32
|
+
from holon.ext.events import Events, EventType, _server
|
|
34
33
|
from holon.serve import App, _asgi
|
|
35
34
|
|
|
36
35
|
IDENTITY = {"name": "watcher", "version": "1", "requires": {"boards": {}}}
|
|
@@ -187,25 +186,25 @@ async def test_a_subscription_hears_what_its_arguments_match_as_shaped_across_a_
|
|
|
187
186
|
await stop()
|
|
188
187
|
|
|
189
188
|
|
|
189
|
+
@pytest.mark.parametrize("user", ["ann", None])
|
|
190
190
|
@asynchronous
|
|
191
|
-
async def
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
191
|
+
async def test_targeted_events_follow_shared_identity_but_isolate_anonymous_readers(
|
|
192
|
+
user,
|
|
193
|
+
):
|
|
194
|
+
subscribed = asyncio.Queue()
|
|
195
|
+
events, changed = declare(
|
|
196
|
+
on_subscribe=lambda context, arguments, id: subscribed.put_nowait(id)
|
|
196
197
|
)
|
|
197
198
|
async with served(events) as port:
|
|
198
|
-
|
|
199
|
-
async with (
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
async with ann.subscribe("board.changed", {"board": "b1"}):
|
|
208
|
-
assert began[3] == began[0]
|
|
199
|
+
reader = client(port, user=user)
|
|
200
|
+
async with reader.subscribe("board.changed", {"board": "b1"}) as first:
|
|
201
|
+
subscription_id = await subscribed.get()
|
|
202
|
+
async with reader.subscribe("board.changed", {"board": "b1"}) as second:
|
|
203
|
+
say(changed, "b1", "private", to=subscription_id)
|
|
204
|
+
say(changed, "b1", "public")
|
|
205
|
+
assert await take(first, 2) == ["private", "public"]
|
|
206
|
+
for expected in ["private", "public"] if user else ["public"]:
|
|
207
|
+
assert (await anext(second)).event_id == expected
|
|
209
208
|
|
|
210
209
|
|
|
211
210
|
@pytest.mark.parametrize("targeted", [False, True])
|
|
@@ -215,9 +214,9 @@ async def test_a_subscription_behind_what_is_kept_is_told_of_the_gap_and_carries
|
|
|
215
214
|
monkeypatch, delivery, targeted
|
|
216
215
|
):
|
|
217
216
|
monkeypatch.setattr(_server, "_KEEP_EVENTS", 2)
|
|
218
|
-
|
|
217
|
+
subscribed, heard = asyncio.Queue(), []
|
|
219
218
|
events, changed = declare(
|
|
220
|
-
on_subscribe=lambda context, arguments, id:
|
|
219
|
+
on_subscribe=lambda context, arguments, id: subscribed.put_nowait(id)
|
|
221
220
|
)
|
|
222
221
|
owed = delivery == "push" and targeted
|
|
223
222
|
async with (
|
|
@@ -229,8 +228,9 @@ async def test_a_subscription_behind_what_is_kept_is_told_of_the_gap_and_carries
|
|
|
229
228
|
on_gap=lambda: heard.append("gap"),
|
|
230
229
|
) as changes,
|
|
231
230
|
):
|
|
231
|
+
subscription_id = await subscribed.get()
|
|
232
232
|
for text in ["a", "b", "c", "d"]:
|
|
233
|
-
say(changed, "b1", text, to=
|
|
233
|
+
say(changed, "b1", text, to=subscription_id if targeted else None)
|
|
234
234
|
heard.extend(await take(changes, 2))
|
|
235
235
|
assert heard == (["a", "b"] if owed else ["gap", "c", "d"])
|
|
236
236
|
|
|
@@ -263,9 +263,11 @@ async def test_what_a_subscribe_hook_emits_reaches_its_subscription_first_and_a_
|
|
|
263
263
|
@asynchronous
|
|
264
264
|
async def test_a_subscription_the_app_ends_is_sent_what_was_emitted_to_it_unless_it_lost_access():
|
|
265
265
|
ids = {}
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
266
|
+
|
|
267
|
+
def on_subscribe(context, arguments, id):
|
|
268
|
+
ids[arguments.board] = id
|
|
269
|
+
|
|
270
|
+
events, changed = declare(on_subscribe=on_subscribe)
|
|
269
271
|
async with served(events) as port:
|
|
270
272
|
boards = client(port, user="ann")
|
|
271
273
|
async with (
|
|
@@ -324,25 +326,25 @@ async def test_the_messages_on_the_wire_are_the_sketchs():
|
|
|
324
326
|
)
|
|
325
327
|
async with served(events) as port, httpx2.AsyncClient(timeout=10) as http:
|
|
326
328
|
discovered = await call(http, port, "server/discover", {})
|
|
327
|
-
assert discovered["result"]["capabilities"]["events"]
|
|
328
|
-
|
|
329
|
-
"
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
assert listed ==
|
|
333
|
-
|
|
329
|
+
assert discovered["result"]["capabilities"]["events"]["listChanged"] is False
|
|
330
|
+
listed = {
|
|
331
|
+
event["name"]: event
|
|
332
|
+
for event in (await call(http, port, "events/list", {}))["result"]["events"]
|
|
333
|
+
}
|
|
334
|
+
assert listed["board.locked"]["payloadSchema"] == recursive
|
|
335
|
+
assert set(listed["board.changed"]["delivery"]) == {"poll", "push"}
|
|
336
|
+
expected = {
|
|
334
337
|
"description": "A board changed",
|
|
335
|
-
"delivery": ["poll", "push"],
|
|
336
338
|
"inputSchema": Board.model_json_schema(),
|
|
337
339
|
"payloadSchema": Change.model_json_schema(),
|
|
338
340
|
}
|
|
341
|
+
assert {key: listed["board.changed"][key] for key in expected} == expected
|
|
339
342
|
# A poll from null has no events, and a cursor from before its setup's welcome.
|
|
340
343
|
now = (await call(http, port, "events/poll", changed_on("b1")))["result"]
|
|
341
|
-
assert (now["events"], now["truncated"], now["hasMore"]
|
|
344
|
+
assert (now["events"], now["truncated"], now["hasMore"]) == (
|
|
342
345
|
[],
|
|
343
346
|
False,
|
|
344
347
|
False,
|
|
345
|
-
1000,
|
|
346
348
|
)
|
|
347
349
|
for text in ["one", "bad", "two", "three"]:
|
|
348
350
|
say(changed, "b1", text)
|
|
@@ -358,7 +360,6 @@ async def test_the_messages_on_the_wire_are_the_sketchs():
|
|
|
358
360
|
"one",
|
|
359
361
|
True,
|
|
360
362
|
)
|
|
361
|
-
assert set(one) == {"eventId", "name", "timestamp", "data"}
|
|
362
363
|
rest = await call(
|
|
363
364
|
http, port, "events/poll", changed_on("b1", page["result"]["cursor"])
|
|
364
365
|
)
|
|
@@ -391,9 +392,11 @@ async def test_the_messages_on_the_wire_are_the_sketchs():
|
|
|
391
392
|
frames = (
|
|
392
393
|
json.loads(frame.data) async for frame in httpx2.EventSource(stream)
|
|
393
394
|
)
|
|
394
|
-
meta = {"_meta": {SUBSCRIPTION_ID_META_KEY: 7}}
|
|
395
395
|
active = await anext(frames)
|
|
396
|
-
assert active["params"]
|
|
396
|
+
assert (active["params"]["cursor"], active["params"]["truncated"]) == (
|
|
397
|
+
opened,
|
|
398
|
+
False,
|
|
399
|
+
)
|
|
397
400
|
assert (await anext(frames))["params"]["eventId"] == "welcome"
|
|
398
401
|
say(changed, "b1", "bad")
|
|
399
402
|
say(changed, "b1", "four")
|
|
@@ -403,19 +406,19 @@ async def test_the_messages_on_the_wire_are_the_sketchs():
|
|
|
403
406
|
INTERNAL_ERROR,
|
|
404
407
|
)
|
|
405
408
|
event = (await anext(frames))["params"]
|
|
406
|
-
|
|
409
|
+
expected = {
|
|
407
410
|
"eventId": "four",
|
|
408
411
|
"name": "board.changed",
|
|
409
|
-
"timestamp": event["timestamp"],
|
|
410
412
|
"data": {"board": "b1", "text": "four"},
|
|
411
413
|
"cursor": changed.cursor(),
|
|
412
|
-
**meta,
|
|
413
414
|
}
|
|
415
|
+
assert {key: event[key] for key in expected} == expected
|
|
416
|
+
assert event["_meta"][SUBSCRIPTION_ID_META_KEY] == 7
|
|
414
417
|
changed.terminate()
|
|
415
418
|
terminated = await anext(frames)
|
|
416
|
-
assert (terminated["method"], terminated["params"]["error"]) == (
|
|
419
|
+
assert (terminated["method"], terminated["params"]["error"]["code"]) == (
|
|
417
420
|
"notifications/events/terminated",
|
|
418
|
-
|
|
421
|
+
-32024,
|
|
419
422
|
)
|
|
420
423
|
assert "result" in await anext(frames)
|
|
421
424
|
|
|
@@ -426,16 +429,18 @@ async def test_a_poll_that_gives_up_while_it_is_set_up_holds_its_place_until_its
|
|
|
426
429
|
):
|
|
427
430
|
monkeypatch.setattr(_server, "_POLL_SUBSCRIPTION_TTL", 0.1)
|
|
428
431
|
monkeypatch.setattr(_server, "_MAX_SUBSCRIPTIONS", 1)
|
|
429
|
-
setting_up, release, ended = asyncio.Event(), asyncio.Event(),
|
|
432
|
+
setting_up, release, ended = asyncio.Event(), asyncio.Event(), asyncio.Event()
|
|
430
433
|
|
|
431
434
|
async def on_subscribe(context, arguments, id):
|
|
432
435
|
setting_up.set()
|
|
433
436
|
await release.wait()
|
|
434
437
|
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
438
|
+
async def cleanup():
|
|
439
|
+
ended.set()
|
|
440
|
+
|
|
441
|
+
return cleanup
|
|
442
|
+
|
|
443
|
+
events, _ = declare(on_subscribe=on_subscribe)
|
|
439
444
|
app, left = mounted(events), asyncio.Event()
|
|
440
445
|
|
|
441
446
|
# Tells when the server sees the poll that gives up disconnect.
|
|
@@ -458,72 +463,36 @@ async def test_a_poll_that_gives_up_while_it_is_set_up_holds_its_place_until_its
|
|
|
458
463
|
await setting_up.wait()
|
|
459
464
|
async with httpx2.AsyncClient(timeout=10) as http:
|
|
460
465
|
exhausted = await call(http, port, "events/poll", changed_on("b2"))
|
|
461
|
-
|
|
466
|
+
limit = exhausted["error"]["data"]
|
|
467
|
+
assert (limit["limit"], limit["max"]) == ("subscriptions", 1)
|
|
462
468
|
giving_up.cancel()
|
|
463
469
|
await left.wait()
|
|
464
470
|
release.set()
|
|
465
|
-
await
|
|
471
|
+
await ended.wait()
|
|
466
472
|
assert "result" in await call(http, port, "events/poll", changed_on("b2"))
|
|
467
473
|
await stop()
|
|
468
474
|
|
|
469
475
|
|
|
470
476
|
@asynchronous
|
|
471
|
-
async def
|
|
477
|
+
async def test_a_subscription_can_be_retried_after_setup_times_out(
|
|
472
478
|
monkeypatch,
|
|
473
479
|
):
|
|
474
480
|
monkeypatch.setattr(_server, "_SUBSCRIBE_TIMEOUT", 0.1)
|
|
475
|
-
|
|
481
|
+
ready = asyncio.Event()
|
|
476
482
|
|
|
477
483
|
async def on_subscribe(context, arguments, id):
|
|
478
|
-
|
|
479
|
-
if len(calls) == 1:
|
|
480
|
-
await asyncio.Event().wait()
|
|
484
|
+
await ready.wait()
|
|
481
485
|
|
|
482
486
|
events, _ = declare(on_subscribe=on_subscribe)
|
|
483
487
|
async with served(events) as port, httpx2.AsyncClient(timeout=10) as http:
|
|
484
488
|
refused = await call(http, port, "events/poll", changed_on("b1"))
|
|
485
489
|
assert refused["error"]["code"] == INTERNAL_ERROR
|
|
490
|
+
ready.set()
|
|
486
491
|
assert "result" in await call(http, port, "events/poll", changed_on("b1"))
|
|
487
|
-
assert calls[0] == calls[1]
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
@asynchronous
|
|
491
|
-
async def test_where_push_cannot_be_served_a_subscription_polls(monkeypatch):
|
|
492
|
-
events, changed = declare()
|
|
493
|
-
bare = MCPServer("boards", extensions=[events])
|
|
494
|
-
# An SDK without the private stream path `Events.asgi` uses on a JSON endpoint.
|
|
495
|
-
monkeypatch.setitem(sys.modules, "mcp.server._streamable_http_modern", None)
|
|
496
|
-
wrapped = MCPServer("boards", extensions=[events])
|
|
497
|
-
wrapped.streamable_http_app(stateless_http=True, json_response=True)
|
|
498
|
-
manager = wrapped.session_manager
|
|
499
|
-
for app, path in [
|
|
500
|
-
(bare.streamable_http_app(stateless_http=True, json_response=True), "/mcp"),
|
|
501
|
-
(
|
|
502
|
-
Starlette(
|
|
503
|
-
routes=[Mount("/mcp", app=events.asgi(manager))],
|
|
504
|
-
lifespan=lambda app: manager.run(),
|
|
505
|
-
),
|
|
506
|
-
"/mcp/",
|
|
507
|
-
),
|
|
508
|
-
]:
|
|
509
|
-
port, stop = await serve(app)
|
|
510
|
-
boards = client(port, path=path)
|
|
511
|
-
async with boards.subscribe("board.changed", {"board": "b1"}) as changes:
|
|
512
|
-
assert changes.delivery == "poll"
|
|
513
|
-
say(changed, "b1", "polled")
|
|
514
|
-
assert await take(changes, 1) == ["polled"]
|
|
515
|
-
await changes.cancel()
|
|
516
|
-
assert await anext(changes, None) is None
|
|
517
|
-
with pytest.raises(NoCompatibleDeliveryMode):
|
|
518
|
-
async with boards.subscribe(
|
|
519
|
-
"board.changed", {"board": "b1"}, delivery="push"
|
|
520
|
-
):
|
|
521
|
-
pass
|
|
522
|
-
await stop()
|
|
523
492
|
|
|
524
493
|
|
|
525
494
|
@asynchronous
|
|
526
|
-
async def
|
|
495
|
+
async def test_a_subscription_from_the_cursor_read_with_a_snapshot_hears_every_change_after_it():
|
|
527
496
|
events, said = Events(), []
|
|
528
497
|
changed: EventType[Board, Change] = events.event(
|
|
529
498
|
"board.changed", input_schema=Board, payload_schema=Change.model_json_schema()
|
|
@@ -539,10 +508,10 @@ async def test_a_subscription_from_the_cursor_read_with_a_snapshot_hears_every_c
|
|
|
539
508
|
|
|
540
509
|
server = Server("boards", on_call_tool=snapshot)
|
|
541
510
|
events.serve(server)
|
|
542
|
-
manager = StreamableHTTPSessionManager(server, stateless=True
|
|
511
|
+
manager = StreamableHTTPSessionManager(server, stateless=True)
|
|
543
512
|
port, stop = await serve(
|
|
544
513
|
Starlette(
|
|
545
|
-
routes=[Mount("/mcp", app=
|
|
514
|
+
routes=[Mount("/mcp", app=manager.handle_request)],
|
|
546
515
|
lifespan=lambda app: manager.run(),
|
|
547
516
|
)
|
|
548
517
|
)
|
|
@@ -556,5 +525,6 @@ async def test_a_subscription_from_the_cursor_read_with_a_snapshot_hears_every_c
|
|
|
556
525
|
) as changes:
|
|
557
526
|
assert changes.delivery == "push"
|
|
558
527
|
tell("once subscribed")
|
|
559
|
-
assert state["said"]
|
|
528
|
+
assert state["said"] == ["in the snapshot"]
|
|
529
|
+
assert await take(changes, 2) == ["after the snapshot", "once subscribed"]
|
|
560
530
|
await stop()
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|