holon-sh 0.0.1.dev16__tar.gz → 0.0.1.dev18__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.
Files changed (27) hide show
  1. {holon_sh-0.0.1.dev16 → holon_sh-0.0.1.dev18}/PKG-INFO +1 -1
  2. {holon_sh-0.0.1.dev16 → holon_sh-0.0.1.dev18}/holon/ext/events/_server.py +57 -118
  3. {holon_sh-0.0.1.dev16 → holon_sh-0.0.1.dev18}/holon/serve.py +1 -8
  4. {holon_sh-0.0.1.dev16 → holon_sh-0.0.1.dev18}/pyproject.toml +1 -1
  5. {holon_sh-0.0.1.dev16 → holon_sh-0.0.1.dev18}/tests/test_events.py +23 -66
  6. {holon_sh-0.0.1.dev16 → holon_sh-0.0.1.dev18}/.gitignore +0 -0
  7. {holon_sh-0.0.1.dev16 → holon_sh-0.0.1.dev18}/LICENSE +0 -0
  8. {holon_sh-0.0.1.dev16 → holon_sh-0.0.1.dev18}/README.md +0 -0
  9. {holon_sh-0.0.1.dev16 → holon_sh-0.0.1.dev18}/holon/client.py +0 -0
  10. {holon_sh-0.0.1.dev16 → holon_sh-0.0.1.dev18}/holon/context.py +0 -0
  11. {holon_sh-0.0.1.dev16 → holon_sh-0.0.1.dev18}/holon/ext/__init__.py +0 -0
  12. {holon_sh-0.0.1.dev16 → holon_sh-0.0.1.dev18}/holon/ext/events/__init__.py +0 -0
  13. {holon_sh-0.0.1.dev16 → holon_sh-0.0.1.dev18}/holon/ext/events/_client.py +0 -0
  14. {holon_sh-0.0.1.dev16 → holon_sh-0.0.1.dev18}/holon/ext/events/_wire.py +0 -0
  15. {holon_sh-0.0.1.dev16 → holon_sh-0.0.1.dev18}/holon/ext/files/__init__.py +0 -0
  16. {holon_sh-0.0.1.dev16 → holon_sh-0.0.1.dev18}/holon/ext/files/_client.py +0 -0
  17. {holon_sh-0.0.1.dev16 → holon_sh-0.0.1.dev18}/holon/ext/files/_server.py +0 -0
  18. {holon_sh-0.0.1.dev16 → holon_sh-0.0.1.dev18}/holon/ext/files/_wire.py +0 -0
  19. {holon_sh-0.0.1.dev16 → holon_sh-0.0.1.dev18}/holon/py.typed +0 -0
  20. {holon_sh-0.0.1.dev16 → holon_sh-0.0.1.dev18}/scripts/verify_distribution.py +0 -0
  21. {holon_sh-0.0.1.dev16 → holon_sh-0.0.1.dev18}/tests/fixtures/caller/holon/apps/__init__.py +0 -0
  22. {holon_sh-0.0.1.dev16 → holon_sh-0.0.1.dev18}/tests/test_context.py +0 -0
  23. {holon_sh-0.0.1.dev16 → holon_sh-0.0.1.dev18}/tests/test_elicit.py +0 -0
  24. {holon_sh-0.0.1.dev16 → holon_sh-0.0.1.dev18}/tests/test_files.py +0 -0
  25. {holon_sh-0.0.1.dev16 → holon_sh-0.0.1.dev18}/tests/test_package.py +0 -0
  26. {holon_sh-0.0.1.dev16 → holon_sh-0.0.1.dev18}/tests/test_runtime.py +0 -0
  27. {holon_sh-0.0.1.dev16 → holon_sh-0.0.1.dev18}/tests/test_serve.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: holon-sh
3
- Version: 0.0.1.dev16
3
+ Version: 0.0.1.dev18
4
4
  Summary: Typed MCP clients and the caller of an MCP request
5
5
  Project-URL: Repository, https://github.com/holon-sh/sdk-py
6
6
  License-Expression: Apache-2.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,9 +35,8 @@ 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
- from holon.context import RequestContext, get_context
39
+ from holon.context import get_context
44
40
  from holon.ext.events._wire import (
45
41
  EVENTS_EXTENSION,
46
42
  FORBIDDEN,
@@ -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
@@ -74,12 +68,13 @@ A = TypeVar("A")
74
68
  T = TypeVar("T")
75
69
 
76
70
 
77
- Match: TypeAlias = Callable[[RequestContext, Event[D], A], bool]
78
- Transform: TypeAlias = Callable[[RequestContext, Event[D], A], object]
79
- Authorize: TypeAlias = Callable[[RequestContext, A], bool | Awaitable[bool]]
71
+ Context: TypeAlias = ServerRequestContext[Any, Any]
72
+ Match: TypeAlias = Callable[[Context, Event[D], A], bool]
73
+ Transform: TypeAlias = Callable[[Context, Event[D], A], object]
74
+ Authorize: TypeAlias = Callable[[Context, A], bool | Awaitable[bool]]
80
75
  Cleanup: TypeAlias = Callable[[], None | Awaitable[None]]
81
76
  SubscriptionHook: TypeAlias = Callable[
82
- [RequestContext, A, str], Cleanup | None | Awaitable[Cleanup | None]
77
+ [Context, A, str], Cleanup | None | Awaitable[Cleanup | None]
83
78
  ]
84
79
 
85
80
 
@@ -122,7 +117,6 @@ class _Request:
122
117
 
123
118
  type: EventType[Any, Any]
124
119
  id: str
125
- context: RequestContext
126
120
  caller: str
127
121
  arguments: Any
128
122
  targetable: bool
@@ -141,8 +135,8 @@ class _Kept:
141
135
  class _Entry:
142
136
  """A subscription, held by one or more streams or poll leases."""
143
137
 
144
- setup: asyncio.Future[Cleanup | None]
145
138
  holds: set[_Hold] = field(default_factory=set)
139
+ setup: asyncio.Future[Cleanup | None] | None = None
146
140
  teardown: asyncio.Future[None] | None = None
147
141
 
148
142
 
@@ -301,16 +295,18 @@ class EventType(Generic[A, D]):
301
295
  return sequence, truncated
302
296
 
303
297
  # The occurrence as `request` receives it, or None when it is not for it.
304
- def _shape(self, kept: _Kept, request: _Request) -> dict[str, Any] | None:
298
+ def _shape(
299
+ self, kept: _Kept, request: _Request, ctx: Context
300
+ ) -> dict[str, Any] | None:
305
301
  if kept.target is not None:
306
302
  if not request.targetable or kept.target != request.id:
307
303
  return None
308
304
  elif self._match is not None and not self._match(
309
- request.context, kept.event, request.arguments
305
+ ctx, kept.event, request.arguments
310
306
  ):
311
307
  return None
312
308
  data = (
313
- self._transform(request.context, kept.event, request.arguments)
309
+ self._transform(ctx, kept.event, request.arguments)
314
310
  if self._transform
315
311
  else kept.event.data
316
312
  )
@@ -325,6 +321,7 @@ class EventType(Generic[A, D]):
325
321
  def _since(
326
322
  self,
327
323
  request: _Request,
324
+ ctx: Context,
328
325
  cursor: str,
329
326
  max_age_ms: int | None,
330
327
  limit: int,
@@ -335,7 +332,7 @@ class EventType(Generic[A, D]):
335
332
  while len(events) < limit and (kept := self._next(reached)) is not None:
336
333
  reached = kept.sequence
337
334
  try:
338
- occurrence = self._shape(kept, request)
335
+ occurrence = self._shape(kept, request, ctx)
339
336
  except Exception as error: # noqa: BLE001
340
337
  _described(error)
341
338
  continue
@@ -348,52 +345,19 @@ class EventType(Generic[A, D]):
348
345
  "hasMore": self._next(reached) is not None,
349
346
  }
350
347
 
351
- async def _allows(self, context: RequestContext, arguments: Any) -> bool:
352
- return self._authorize is None or await _settle(
353
- self._authorize(context, arguments)
354
- )
348
+ async def _allows(self, ctx: Context, arguments: Any) -> bool:
349
+ return self._authorize is None or await _settle(self._authorize(ctx, arguments))
355
350
 
356
351
  async def _settled(self, id: str) -> None:
357
352
  while (entry := self._subscriptions.get(id)) and entry.teardown is not None:
358
353
  await asyncio.shield(entry.teardown)
359
354
 
360
355
 
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
356
  class Events(Extension):
393
357
  """The event types an app serves as MCP Events.
394
358
 
395
359
  Pass it to ``MCPServer(extensions=[events], middleware=[events])``, or call :meth:`serve` on a low-level
396
- ``Server``. Over Streamable HTTP, push is offered only on an endpoint mounted through :meth:`asgi`.
360
+ ``Server``. Push needs an endpoint whose answers can stream: over Streamable HTTP, not ``json_response=True``.
397
361
  """
398
362
 
399
363
  identifier = EVENTS_EXTENSION
@@ -423,7 +387,9 @@ class Events(Extension):
423
387
  ) -> EventType[A, D]:
424
388
  """Declare an event type.
425
389
 
426
- Annotate the result as ``EventType[Arguments, Data]`` to type ``emit``.
390
+ Annotate the result as ``EventType[Arguments, Data]`` to type ``emit``. Each hook's ``context`` is the server's
391
+ context of the request it runs in. A subscription outlives the first request to name it, where ``on_subscribe``
392
+ runs, and other requests may share it: keep what the hook reads from ``context``, not ``context``.
427
393
 
428
394
  Args:
429
395
  input_schema: Type of a subscription's arguments.
@@ -498,25 +464,6 @@ class Events(Extension):
498
464
  }
499
465
  return result
500
466
 
501
- def asgi(self, manager: StreamableHTTPSessionManager) -> ASGIApp:
502
- """The endpoint of ``manager``, with push.
503
-
504
- Mount it where ``manager.handle_request`` would be, inside any authentication.
505
- """
506
- streaming = _streaming(manager)
507
-
508
- async def app(scope: Scope, receive: Receive, send: Send) -> None:
509
- method = dict(scope.get("headers", [])).get(MCP_METHOD_HEADER.encode())
510
- if scope["type"] == "http" and not manager.json_response:
511
- scope = {**scope, _STREAMS: True}
512
- elif scope["type"] == "http" and streaming and method is not None:
513
- scope = {**scope, _STREAMS: True}
514
- if method == b"events/stream":
515
- return await streaming(scope, receive, send)
516
- await manager.handle_request(scope, receive, send)
517
-
518
- return app
519
-
520
467
  async def _list(
521
468
  self, ctx: ServerRequestContext[Any, Any], params: PaginatedRequestParams
522
469
  ) -> HandlerResult:
@@ -525,25 +472,21 @@ class Events(Extension):
525
472
  if not cursor.isdigit():
526
473
  raise MCPError(INVALID_PARAMS, "Invalid cursor for events/list")
527
474
  start = int(cursor)
528
- streams = _streams(ctx)
529
- listed = []
530
- for each in list(self._types.values())[start : start + _LIST_PAGE_SIZE]:
531
- if delivery := [
532
- mode for mode in each._delivery if streams or mode != "push"
533
- ]:
534
- listed.append({**each._descriptor, "delivery": delivery})
535
- result: dict[str, Any] = {"events": listed}
475
+ listed = list(self._types.values())[start : start + _LIST_PAGE_SIZE]
476
+ result: dict[str, Any] = {
477
+ "events": [
478
+ {**each._descriptor, "delivery": each._delivery} for each in listed
479
+ ]
480
+ }
536
481
  if start + _LIST_PAGE_SIZE < len(self._types):
537
482
  result["nextCursor"] = str(start + _LIST_PAGE_SIZE)
538
483
  return result
539
484
 
540
- async def _poll(
541
- self, ctx: ServerRequestContext[Any, Any], params: _SubscribeParams
542
- ) -> HandlerResult:
543
- request = await self._subscription(params, "poll", _streams(ctx))
485
+ async def _poll(self, ctx: Context, params: _SubscribeParams) -> HandlerResult:
486
+ request = await self._subscription(ctx, params, "poll")
544
487
  declared = request.type
545
488
  opened = declared._sequence
546
- await self._lease(request)
489
+ await self._lease(request, ctx)
547
490
  if params.cursor is None:
548
491
  answer = {
549
492
  "events": [],
@@ -554,6 +497,7 @@ class Events(Extension):
554
497
  else:
555
498
  answer = declared._since(
556
499
  request,
500
+ ctx,
557
501
  params.cursor,
558
502
  params.max_age_ms,
559
503
  params.max_events or _MAX_POLL_EVENTS,
@@ -576,13 +520,13 @@ class Events(Extension):
576
520
 
577
521
  # Checked in the order of https://github.com/modelcontextprotocol/experimental-ext-triggers-events/blob/main/docs/design-sketch-proposal.md#error-codes
578
522
  async def _subscription(
579
- self, params: _SubscribeParams, delivery: Delivery, streams: bool
523
+ self, ctx: Context, params: _SubscribeParams, delivery: Delivery
580
524
  ) -> _Request:
581
525
  self._loop = self._loop or asyncio.get_running_loop()
582
526
  declared = self._types.get(params.name)
583
527
  if declared is None:
584
528
  raise MCPError.from_error_data(_NOT_FOUND)
585
- if delivery not in declared._delivery or (delivery == "push" and not streams):
529
+ if delivery not in declared._delivery:
586
530
  raise MCPError(
587
531
  UNSUPPORTED,
588
532
  "Unsupported",
@@ -598,8 +542,7 @@ class Events(Extension):
598
542
  raise MCPError(
599
543
  INVALID_PARAMS, f"Invalid arguments for {params.name}: {problems}"
600
544
  ) from None
601
- context = get_context()
602
- principal = context.principal
545
+ principal = get_context().principal
603
546
  caller = ""
604
547
  if principal is not None:
605
548
  who = [
@@ -625,12 +568,11 @@ class Events(Extension):
625
568
  request = _Request(
626
569
  declared,
627
570
  id,
628
- context,
629
571
  caller,
630
572
  arguments,
631
573
  targetable=principal is not None or delivery == "push",
632
574
  )
633
- if not await declared._allows(context, arguments):
575
+ if not await declared._allows(ctx, arguments):
634
576
  declared.terminate(id, _FORBIDDEN)
635
577
  if lease := self._leases.get(id):
636
578
  self._stop(lease)
@@ -655,27 +597,26 @@ class Events(Extension):
655
597
  },
656
598
  )
657
599
  self._held[request.caller] += 1
658
- subscriptions = request.type._subscriptions
659
- entry = subscriptions.get(request.id)
660
- if entry is None:
661
- setup = asyncio.ensure_future(self._set_up(request))
662
- entry = subscriptions[request.id] = _Entry(setup)
600
+ entry = request.type._subscriptions.setdefault(request.id, _Entry())
663
601
  hold = _Hold(request, entry)
664
602
  entry.holds.add(hold)
665
603
  return hold
666
604
 
667
- async def _set_up(self, request: _Request) -> Cleanup | None:
605
+ async def _set_up(self, request: _Request, ctx: Context) -> Cleanup | None:
668
606
  if request.type._on_subscribe is None:
669
607
  return None
670
608
  async with asyncio.timeout(_SUBSCRIBE_TIMEOUT):
671
609
  return await _settle(
672
- request.type._on_subscribe(
673
- request.context, request.arguments, request.id
674
- )
610
+ request.type._on_subscribe(ctx, request.arguments, request.id)
675
611
  )
676
612
 
677
- async def _ready(self, hold: _Hold) -> None:
678
- await asyncio.shield(hold.entry.setup)
613
+ async def _ready(self, hold: _Hold, ctx: Context) -> None:
614
+ entry = hold.entry
615
+ while entry.setup is not None and not entry.setup.done():
616
+ await asyncio.wait([entry.setup])
617
+ if entry.setup is None or entry.setup.cancelled():
618
+ entry.setup = asyncio.ensure_future(self._set_up(hold.request, ctx))
619
+ await entry.setup
679
620
  if hold.ended is not None:
680
621
  raise MCPError.from_error_data(hold.ended)
681
622
 
@@ -690,18 +631,20 @@ class Events(Extension):
690
631
 
691
632
  # Cleanup follows only a setup that succeeded; a failing hook is logged.
692
633
  async def _tear_down(self, hold: _Hold) -> None:
693
- request = hold.request
634
+ request, setup = hold.request, hold.entry.setup
694
635
  try:
695
- cleanup = await hold.entry.setup
696
- if cleanup is not None:
697
- await _settle(cleanup())
636
+ if setup is not None:
637
+ await asyncio.wait([setup])
638
+ cleanup = None if setup.cancelled() else setup.result()
639
+ if cleanup is not None:
640
+ await _settle(cleanup())
698
641
  except Exception:
699
642
  logger.exception("An event subscription's setup or cleanup failed")
700
643
  finally:
701
644
  del request.type._subscriptions[request.id]
702
645
 
703
646
  # A poll lease begins with the first poll, is renewed by each, and lapses when polls stop.
704
- async def _lease(self, request: _Request) -> None:
647
+ async def _lease(self, request: _Request, ctx: Context) -> None:
705
648
  await request.type._settled(request.id)
706
649
  hold = self._leases.get(request.id)
707
650
  if hold is None:
@@ -713,7 +656,7 @@ class Events(Extension):
713
656
  _POLL_SUBSCRIPTION_TTL, self._stop, hold
714
657
  )
715
658
  try:
716
- await self._ready(hold)
659
+ await self._ready(hold, ctx)
717
660
  except Exception:
718
661
  self._stop(hold)
719
662
  raise
@@ -742,16 +685,14 @@ class Events(Extension):
742
685
  self._sent.set()
743
686
  self._sent = asyncio.Event()
744
687
 
745
- async def _stream(
746
- self, ctx: ServerRequestContext[Any, Any], params: _SubscribeParams
747
- ) -> HandlerResult:
748
- request = await self._subscription(params, "push", _streams(ctx))
688
+ async def _stream(self, ctx: Context, params: _SubscribeParams) -> HandlerResult:
689
+ request = await self._subscription(ctx, params, "push")
749
690
  declared = request.type
750
691
  await declared._settled(request.id)
751
692
  hold = self._open(request)
752
693
  hold.seen = declared._sequence
753
694
  try:
754
- await self._ready(hold)
695
+ await self._ready(hold, ctx)
755
696
 
756
697
  async def say(method: str, body: dict[str, Any], size: int = 0) -> None:
757
698
  body["_meta"] = {SUBSCRIPTION_ID_META_KEY: ctx.request_id}
@@ -775,7 +716,7 @@ class Events(Extension):
775
716
  async def send(kept: _Kept) -> None:
776
717
  hold.seen = kept.sequence
777
718
  try:
778
- shaped = declared._shape(kept, request)
719
+ shaped = declared._shape(kept, request, ctx)
779
720
  except Exception as error: # noqa: BLE001
780
721
  await say("error", {"error": _described(error)})
781
722
  return
@@ -790,9 +731,7 @@ class Events(Extension):
790
731
  if time.monotonic() >= beat:
791
732
  beat = time.monotonic() + _HEARTBEAT
792
733
  try:
793
- allowed = await declared._allows(
794
- request.context, request.arguments
795
- )
734
+ allowed = await declared._allows(ctx, request.arguments)
796
735
  except Exception as error: # noqa: BLE001
797
736
  await say("error", {"error": _described(error)})
798
737
  continue
@@ -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
- manager = server.session_manager
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:
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "holon-sh"
7
- version = "0.0.1.dev16"
7
+ version = "0.0.1.dev18"
8
8
  description = "Typed MCP clients and the caller of an MCP request"
9
9
  readme = "README.md"
10
10
  license = "Apache-2.0"
@@ -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, NoCompatibleDeliveryMode, _server
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": {}}}
@@ -425,53 +424,46 @@ async def test_the_messages_on_the_wire_are_the_sketchs():
425
424
 
426
425
 
427
426
  @asynchronous
428
- async def test_a_poll_that_gives_up_while_it_is_set_up_holds_its_place_until_its_lease_lapses(
427
+ async def test_a_poll_that_gives_up_while_it_is_set_up_stops_its_setup_and_holds_its_place_until_its_lease_lapses(
429
428
  monkeypatch,
430
429
  ):
431
- monkeypatch.setattr(_server, "_POLL_SUBSCRIPTION_TTL", 0.1)
430
+ monkeypatch.setattr(_server, "_POLL_SUBSCRIPTION_TTL", 0.5)
432
431
  monkeypatch.setattr(_server, "_MAX_SUBSCRIPTIONS", 1)
433
- setting_up, release, ended = asyncio.Event(), asyncio.Event(), asyncio.Event()
432
+ ended, seen = asyncio.Event(), []
434
433
 
435
434
  async def on_subscribe(context, arguments, id):
436
- setting_up.set()
437
- await release.wait()
435
+ seen.append(context.request.headers.get("x-leaving"))
436
+ try:
437
+ if seen[-1]:
438
+ await asyncio.Event().wait()
439
+ except asyncio.CancelledError:
440
+ seen.append("stopped")
441
+ raise
438
442
 
439
443
  async def cleanup():
440
444
  ended.set()
441
445
 
442
446
  return cleanup
443
447
 
444
- events, _ = declare(on_subscribe=on_subscribe)
445
- app, left = mounted(events), asyncio.Event()
446
-
447
- # Tells when the server sees the poll that gives up disconnect.
448
- async def noticing(scope, receive, send):
449
- async def receiving():
450
- message = await receive()
451
- if message["type"] == "http.disconnect":
452
- left.set()
453
- return message
454
-
455
- leaving = (b"x-leaving", b"1") in scope.get("headers", [])
456
- await app(scope, receiving if leaving else receive, send)
457
-
458
448
  async def give_up():
459
449
  async with httpx2.AsyncClient(headers={"x-leaving": "1"}) as http:
460
450
  await call(http, port, "events/poll", changed_on("b1"))
461
451
 
462
- port, stop = await serve(noticing)
463
- giving_up = asyncio.ensure_future(give_up())
464
- await setting_up.wait()
465
- async with httpx2.AsyncClient(timeout=10) as http:
452
+ async with (
453
+ served(declare(on_subscribe=on_subscribe)[0]) as port,
454
+ httpx2.AsyncClient(timeout=10) as http,
455
+ ):
456
+ giving_up = asyncio.ensure_future(give_up())
457
+ await until(lambda: seen)
466
458
  exhausted = await call(http, port, "events/poll", changed_on("b2"))
467
459
  limit = exhausted["error"]["data"]
468
460
  assert (limit["limit"], limit["max"]) == ("subscriptions", 1)
469
461
  giving_up.cancel()
470
- await left.wait()
471
- release.set()
462
+ await until(lambda: "stopped" in seen)
463
+ assert "result" in await call(http, port, "events/poll", changed_on("b1"))
464
+ assert seen == ["1", "stopped", None]
472
465
  await ended.wait()
473
466
  assert "result" in await call(http, port, "events/poll", changed_on("b2"))
474
- await stop()
475
467
 
476
468
 
477
469
  @asynchronous
@@ -493,42 +485,7 @@ async def test_a_subscription_can_be_retried_after_setup_times_out(
493
485
 
494
486
 
495
487
  @asynchronous
496
- async def test_where_push_cannot_be_served_a_subscription_polls(monkeypatch):
497
- events, changed = declare()
498
- bare = MCPServer("boards", extensions=[events])
499
- # An SDK without the private stream path `Events.asgi` uses on a JSON endpoint.
500
- monkeypatch.setitem(sys.modules, "mcp.server._streamable_http_modern", None)
501
- wrapped = MCPServer("boards", extensions=[events])
502
- wrapped.streamable_http_app(stateless_http=True, json_response=True)
503
- manager = wrapped.session_manager
504
- for app, path in [
505
- (bare.streamable_http_app(stateless_http=True, json_response=True), "/mcp"),
506
- (
507
- Starlette(
508
- routes=[Mount("/mcp", app=events.asgi(manager))],
509
- lifespan=lambda app: manager.run(),
510
- ),
511
- "/mcp/",
512
- ),
513
- ]:
514
- port, stop = await serve(app)
515
- boards = client(port, path=path)
516
- async with boards.subscribe("board.changed", {"board": "b1"}) as changes:
517
- assert changes.delivery == "poll"
518
- say(changed, "b1", "polled")
519
- assert await take(changes, 1) == ["polled"]
520
- await changes.cancel()
521
- assert await anext(changes, None) is None
522
- with pytest.raises(NoCompatibleDeliveryMode):
523
- async with boards.subscribe(
524
- "board.changed", {"board": "b1"}, delivery="push"
525
- ):
526
- pass
527
- await stop()
528
-
529
-
530
- @asynchronous
531
- async def test_a_subscription_from_the_cursor_read_with_a_snapshot_hears_every_change_after_it_on_a_json_endpoint():
488
+ async def test_a_subscription_from_the_cursor_read_with_a_snapshot_hears_every_change_after_it():
532
489
  events, said = Events(), []
533
490
  changed: EventType[Board, Change] = events.event(
534
491
  "board.changed", input_schema=Board, payload_schema=Change.model_json_schema()
@@ -544,10 +501,10 @@ async def test_a_subscription_from_the_cursor_read_with_a_snapshot_hears_every_c
544
501
 
545
502
  server = Server("boards", on_call_tool=snapshot)
546
503
  events.serve(server)
547
- manager = StreamableHTTPSessionManager(server, stateless=True, json_response=True)
504
+ manager = StreamableHTTPSessionManager(server, stateless=True)
548
505
  port, stop = await serve(
549
506
  Starlette(
550
- routes=[Mount("/mcp", app=events.asgi(manager))],
507
+ routes=[Mount("/mcp", app=manager.handle_request)],
551
508
  lifespan=lambda app: manager.run(),
552
509
  )
553
510
  )
File without changes
File without changes