holon-sh 0.0.1.dev11__tar.gz → 0.0.1.dev13__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 (26) hide show
  1. {holon_sh-0.0.1.dev11 → holon_sh-0.0.1.dev13}/PKG-INFO +1 -1
  2. {holon_sh-0.0.1.dev11 → holon_sh-0.0.1.dev13}/holon/context.py +19 -4
  3. {holon_sh-0.0.1.dev11 → holon_sh-0.0.1.dev13}/holon/ext/events/_server.py +26 -31
  4. {holon_sh-0.0.1.dev11 → holon_sh-0.0.1.dev13}/pyproject.toml +1 -1
  5. holon_sh-0.0.1.dev13/tests/test_context.py +71 -0
  6. {holon_sh-0.0.1.dev11 → holon_sh-0.0.1.dev13}/tests/test_events.py +11 -7
  7. holon_sh-0.0.1.dev11/tests/test_context.py +0 -52
  8. {holon_sh-0.0.1.dev11 → holon_sh-0.0.1.dev13}/.gitignore +0 -0
  9. {holon_sh-0.0.1.dev11 → holon_sh-0.0.1.dev13}/LICENSE +0 -0
  10. {holon_sh-0.0.1.dev11 → holon_sh-0.0.1.dev13}/README.md +0 -0
  11. {holon_sh-0.0.1.dev11 → holon_sh-0.0.1.dev13}/holon/client.py +0 -0
  12. {holon_sh-0.0.1.dev11 → holon_sh-0.0.1.dev13}/holon/ext/__init__.py +0 -0
  13. {holon_sh-0.0.1.dev11 → holon_sh-0.0.1.dev13}/holon/ext/events/__init__.py +0 -0
  14. {holon_sh-0.0.1.dev11 → holon_sh-0.0.1.dev13}/holon/ext/events/_client.py +0 -0
  15. {holon_sh-0.0.1.dev11 → holon_sh-0.0.1.dev13}/holon/ext/events/_wire.py +0 -0
  16. {holon_sh-0.0.1.dev11 → holon_sh-0.0.1.dev13}/holon/ext/files/__init__.py +0 -0
  17. {holon_sh-0.0.1.dev11 → holon_sh-0.0.1.dev13}/holon/ext/files/_client.py +0 -0
  18. {holon_sh-0.0.1.dev11 → holon_sh-0.0.1.dev13}/holon/ext/files/_server.py +0 -0
  19. {holon_sh-0.0.1.dev11 → holon_sh-0.0.1.dev13}/holon/ext/files/_wire.py +0 -0
  20. {holon_sh-0.0.1.dev11 → holon_sh-0.0.1.dev13}/holon/py.typed +0 -0
  21. {holon_sh-0.0.1.dev11 → holon_sh-0.0.1.dev13}/scripts/verify_distribution.py +0 -0
  22. {holon_sh-0.0.1.dev11 → holon_sh-0.0.1.dev13}/tests/fixtures/caller/holon/apps/__init__.py +0 -0
  23. {holon_sh-0.0.1.dev11 → holon_sh-0.0.1.dev13}/tests/test_elicit.py +0 -0
  24. {holon_sh-0.0.1.dev11 → holon_sh-0.0.1.dev13}/tests/test_files.py +0 -0
  25. {holon_sh-0.0.1.dev11 → holon_sh-0.0.1.dev13}/tests/test_package.py +0 -0
  26. {holon_sh-0.0.1.dev11 → holon_sh-0.0.1.dev13}/tests/test_runtime.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: holon-sh
3
- Version: 0.0.1.dev11
3
+ Version: 0.0.1.dev13
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
@@ -54,17 +54,31 @@ class Principal:
54
54
  actor: dict[str, Any] | None = None
55
55
 
56
56
 
57
+ @dataclass(frozen=True)
58
+ class Caller:
59
+ """The app a request comes from. A lifecycle hook's job calls as its app."""
60
+
61
+ app: str # as named in holon.yaml
62
+ session: str # the namespace of the session both apps run in
63
+
64
+
57
65
  @dataclass(frozen=True)
58
66
  class RequestContext:
59
- principal: Principal | None
67
+ principal: Principal | None # None when anonymous
68
+ caller: Caller | None # None when a person calls the app directly
60
69
 
61
70
 
62
71
  def get_context() -> RequestContext:
63
- """The caller of the current MCP request; ``principal`` is ``None`` when anonymous."""
72
+ """Who the current MCP request comes from: the person and the calling app."""
64
73
  admitted = get_access_token()
65
74
  extra = (admitted.claims or {}) if admitted else {}
75
+ # None for a person's direct call, and for an older runtime's raw mesh identity.
76
+ caller: Caller | None = None
77
+ match extra.get("caller"):
78
+ case {"app": str(app), "session": str(session)}:
79
+ caller = Caller(app, session)
66
80
  if admitted is None or admitted.subject is None or "iss" not in extra:
67
- return RequestContext(principal=None)
81
+ return RequestContext(principal=None, caller=caller)
68
82
  return RequestContext(
69
83
  Principal(
70
84
  issuer=extra["iss"],
@@ -73,5 +87,6 @@ def get_context() -> RequestContext:
73
87
  scopes=admitted.scopes,
74
88
  claims=extra.get("claims", {}),
75
89
  actor=extra.get("act"),
76
- )
90
+ ),
91
+ caller,
77
92
  )
@@ -155,6 +155,7 @@ class _Hold:
155
155
  ended: ErrorData | None = None
156
156
  until: int = 0
157
157
  lease: asyncio.TimerHandle | None = None
158
+ seen: int = 0
158
159
 
159
160
 
160
161
  @dataclass(eq=False, repr=False)
@@ -191,7 +192,7 @@ class EventType(Generic[A, D]):
191
192
  Args:
192
193
  event_id: The source's own id, so a client drops duplicates.
193
194
  timestamp: When it happened. Defaults to now.
194
- subscription_id: Send it to this subscription alone.
195
+ subscription_id: Send it to this subscription alone, and keep it until the subscription's open streams have sent it.
195
196
 
196
197
  Call it on the event loop that serves the events; from another thread, use ``loop.call_soon_threadsafe``.
197
198
  """
@@ -256,8 +257,14 @@ class EventType(Generic[A, D]):
256
257
  or self._bytes > _KEEP_BYTES
257
258
  or self._kept[dropped].at < kept.at - _KEEP_AGE
258
259
  ):
259
- self._dropped = self._kept[dropped].sequence
260
- self._bytes -= self._kept[dropped].size
260
+ oldest = self._kept[dropped]
261
+ if oldest.target is not None and any(
262
+ hold.lease is None and hold.seen < oldest.sequence
263
+ for hold in self._holds(oldest.target)
264
+ ):
265
+ break
266
+ self._dropped = oldest.sequence
267
+ self._bytes -= oldest.size
261
268
  dropped += 1
262
269
  del self._kept[:dropped]
263
270
 
@@ -753,7 +760,7 @@ class Events(Extension):
753
760
  declared = request.type
754
761
  await declared._settled(request.id)
755
762
  hold = self._open(request)
756
- seen = declared._sequence
763
+ hold.seen = declared._sequence
757
764
  try:
758
765
  await self._ready(hold)
759
766
 
@@ -771,20 +778,23 @@ class Events(Extension):
771
778
  if waited.cancelled_caught:
772
779
  raise _Stalled
773
780
 
781
+ async def active(seen: int, truncated: bool) -> None:
782
+ hold.seen = seen
783
+ cursor = declared._position(seen)
784
+ await say("active", {"cursor": cursor, "truncated": truncated})
785
+
774
786
  async def send(kept: _Kept) -> None:
787
+ hold.seen = kept.sequence
775
788
  try:
776
789
  shaped = declared._shape(kept, request)
777
790
  except Exception as error: # noqa: BLE001
778
791
  await say("error", {"error": _described(error)})
779
792
  return
780
793
  if shaped is not None:
781
- cursor = declared._position(seen)
794
+ cursor = declared._position(kept.sequence)
782
795
  await say("event", {**shaped, "cursor": cursor}, kept.size)
783
796
 
784
- seen, truncated = declared._resume(params.cursor, params.max_age_ms, seen)
785
- await say(
786
- "active", {"cursor": declared._position(seen), "truncated": truncated}
787
- )
797
+ await active(*declared._resume(params.cursor, params.max_age_ms, hold.seen))
788
798
  beat = time.monotonic() + _HEARTBEAT
789
799
  while hold.ended is None:
790
800
  hold.wake.clear()
@@ -800,34 +810,19 @@ class Events(Extension):
800
810
  if not allowed:
801
811
  hold.ended = _FORBIDDEN
802
812
  break
803
- await say("heartbeat", {"cursor": declared._position(seen)})
804
- elif seen < declared._dropped:
813
+ await say("heartbeat", {"cursor": declared._position(hold.seen)})
814
+ elif hold.seen < declared._dropped:
805
815
  # Evicted before it was sent: a gap.
806
- seen = declared._dropped
807
- await say(
808
- "active",
809
- {"cursor": declared._position(seen), "truncated": True},
810
- )
811
- elif (kept := declared._next(seen)) is not None:
812
- seen = kept.sequence
816
+ await active(declared._dropped, True)
817
+ elif (kept := declared._next(hold.seen)) is not None:
813
818
  await send(kept)
814
819
  else:
815
820
  with anyio.move_on_after(beat - time.monotonic()):
816
821
  await hold.wake.wait()
817
- while (
818
- kept := declared._next(seen)
819
- ) is not None and kept.sequence <= hold.until:
820
- seen = kept.sequence
822
+ while (kept := declared._next(hold.seen)) and kept.sequence <= hold.until:
821
823
  await send(kept)
822
- if hold.ended is not None:
823
- await say(
824
- "terminated",
825
- {
826
- "error": hold.ended.model_dump(
827
- by_alias=True, exclude_none=True, mode="json"
828
- )
829
- },
830
- )
824
+ ended = MCPError.from_error_data(hold.ended)
825
+ await say("terminated", {"error": _described(ended)})
831
826
  except _Stalled:
832
827
  logger.info(
833
828
  "Closed a stream of %s whose reader took nothing for two heartbeats",
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "holon-sh"
7
- version = "0.0.1.dev11"
7
+ version = "0.0.1.dev13"
8
8
  description = "Typed MCP clients and the caller of an MCP request"
9
9
  readme = "README.md"
10
10
  license = "Apache-2.0"
@@ -0,0 +1,71 @@
1
+ from mcp.server.auth.middleware.auth_context import auth_context_var
2
+ from mcp.server.auth.middleware.bearer_auth import AuthenticatedUser
3
+ from mcp.server.auth.provider import AccessToken
4
+
5
+ from holon.context import Caller, Principal, RequestContext, get_context
6
+
7
+ PROFILE = {"email": "user@example.com", "email_verified": True}
8
+ REPORTER = {"app": "reporter", "session": "session"}
9
+
10
+
11
+ def test_get_context_reads_the_caller_holon_admitted():
12
+ assert get_context() == RequestContext(principal=None, caller=None)
13
+ for client_id, scopes, extra, expected in [
14
+ (
15
+ "web",
16
+ ["read", "write"],
17
+ {
18
+ "iss": "https://id.example",
19
+ "sub": "user",
20
+ "claims": PROFILE,
21
+ "act": {"sub": "agent"},
22
+ },
23
+ RequestContext(
24
+ Principal(
25
+ issuer="https://id.example",
26
+ subject="user",
27
+ client_id="web",
28
+ scopes=["read", "write"],
29
+ claims=PROFILE,
30
+ actor={"sub": "agent"},
31
+ ),
32
+ caller=None,
33
+ ),
34
+ ),
35
+ # An app acting for a person, then an app or its lifecycle hook's job with nobody signed in.
36
+ (
37
+ "web",
38
+ [],
39
+ {"iss": "https://id.example", "sub": "user", "caller": REPORTER},
40
+ RequestContext(
41
+ Principal("https://id.example", "user", "web", [], {}),
42
+ Caller("reporter", "session"),
43
+ ),
44
+ ),
45
+ (
46
+ "",
47
+ [],
48
+ {"caller": REPORTER},
49
+ RequestContext(None, Caller("reporter", "session")),
50
+ ),
51
+ # An older runtime passed the raw mesh identity, and a person needs an issuer.
52
+ (
53
+ "",
54
+ [],
55
+ {"caller": "spiffe://cluster.local/ns/session/sa/reporter"},
56
+ RequestContext(None, None),
57
+ ),
58
+ ("web", [], {"sub": "user"}, RequestContext(None, None)),
59
+ ]:
60
+ token = AccessToken(
61
+ token="t",
62
+ client_id=client_id,
63
+ scopes=scopes,
64
+ subject=extra.get("sub"),
65
+ claims=extra,
66
+ )
67
+ admitted = auth_context_var.set(AuthenticatedUser(token))
68
+ try:
69
+ assert get_context() == expected
70
+ finally:
71
+ auth_context_var.reset(admitted)
@@ -213,17 +213,21 @@ async def test_a_signed_in_caller_has_one_subscription_per_arguments_and_a_calle
213
213
  assert began[3] == began[0]
214
214
 
215
215
 
216
+ @pytest.mark.parametrize("targeted", [False, True])
216
217
  @pytest.mark.parametrize("delivery", ["push", "poll"])
217
218
  @asynchronous
218
- async def test_a_subscription_behind_what_is_kept_is_told_of_the_gap_and_carries_on(
219
- monkeypatch, delivery
219
+ async def test_a_subscription_behind_what_is_kept_is_told_of_the_gap_and_carries_on_but_a_stream_is_sent_all_emitted_to_its_subscription(
220
+ monkeypatch, delivery, targeted
220
221
  ):
221
222
  monkeypatch.setattr(_server, "_KEEP_EVENTS", 2)
222
- events, changed = declare()
223
- heard = []
223
+ ids, heard = [], []
224
+ events, changed = declare(
225
+ on_subscribe=lambda context, arguments, id: ids.append(id)
226
+ )
227
+ owed = delivery == "push" and targeted
224
228
  async with (
225
229
  served(events) as port,
226
- client(port).subscribe(
230
+ client(port, user="ann").subscribe(
227
231
  "board.changed",
228
232
  {"board": "b1"},
229
233
  delivery=delivery,
@@ -231,9 +235,9 @@ async def test_a_subscription_behind_what_is_kept_is_told_of_the_gap_and_carries
231
235
  ) as changes,
232
236
  ):
233
237
  for text in ["a", "b", "c", "d"]:
234
- say(changed, "b1", text)
238
+ say(changed, "b1", text, to=ids[0] if targeted else None)
235
239
  heard.extend(await take(changes, 2))
236
- assert heard == ["gap", "c", "d"]
240
+ assert heard == (["a", "b"] if owed else ["gap", "c", "d"])
237
241
 
238
242
 
239
243
  @asynchronous
@@ -1,52 +0,0 @@
1
- from mcp.server.auth.middleware.auth_context import auth_context_var
2
- from mcp.server.auth.middleware.bearer_auth import AuthenticatedUser
3
- from mcp.server.auth.provider import AccessToken
4
-
5
- from holon.context import Principal, get_context
6
-
7
- PROFILE = {"email": "user@example.com", "email_verified": True}
8
-
9
-
10
- def test_get_context_reads_the_caller_holon_admitted():
11
- assert get_context().principal is None
12
- for client_id, scopes, extra, expected in [
13
- (
14
- "web",
15
- ["read", "write"],
16
- {
17
- "iss": "https://id.example",
18
- "sub": "user",
19
- "claims": PROFILE,
20
- "act": {"sub": "agent"},
21
- },
22
- Principal(
23
- issuer="https://id.example",
24
- subject="user",
25
- client_id="web",
26
- scopes=["read", "write"],
27
- claims=PROFILE,
28
- actor={"sub": "agent"},
29
- ),
30
- ),
31
- (
32
- "web",
33
- [],
34
- {"iss": "https://id.example", "sub": "user"},
35
- Principal("https://id.example", "user", "web", [], {}),
36
- ),
37
- # A hook call carries no user, and a caller needs an issuer.
38
- ("", [], {"hook": {"event": "installed"}}, None),
39
- ("web", [], {"sub": "user"}, None),
40
- ]:
41
- token = AccessToken(
42
- token="t",
43
- client_id=client_id,
44
- scopes=scopes,
45
- subject=extra.get("sub"),
46
- claims=extra,
47
- )
48
- admitted = auth_context_var.set(AuthenticatedUser(token))
49
- try:
50
- assert get_context().principal == expected
51
- finally:
52
- auth_context_var.reset(admitted)
File without changes
File without changes