holon-sh 0.0.1.dev21__tar.gz → 0.0.1.dev22__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.dev21 → holon_sh-0.0.1.dev22}/PKG-INFO +1 -1
  2. {holon_sh-0.0.1.dev21 → holon_sh-0.0.1.dev22}/holon/ext/events/_server.py +20 -3
  3. {holon_sh-0.0.1.dev21 → holon_sh-0.0.1.dev22}/holon/serve.py +17 -1
  4. {holon_sh-0.0.1.dev21 → holon_sh-0.0.1.dev22}/pyproject.toml +1 -1
  5. {holon_sh-0.0.1.dev21 → holon_sh-0.0.1.dev22}/tests/test_serve.py +72 -79
  6. holon_sh-0.0.1.dev21/tests/test_context.py +0 -71
  7. {holon_sh-0.0.1.dev21 → holon_sh-0.0.1.dev22}/.gitignore +0 -0
  8. {holon_sh-0.0.1.dev21 → holon_sh-0.0.1.dev22}/LICENSE +0 -0
  9. {holon_sh-0.0.1.dev21 → holon_sh-0.0.1.dev22}/README.md +0 -0
  10. {holon_sh-0.0.1.dev21 → holon_sh-0.0.1.dev22}/holon/client.py +0 -0
  11. {holon_sh-0.0.1.dev21 → holon_sh-0.0.1.dev22}/holon/context.py +0 -0
  12. {holon_sh-0.0.1.dev21 → holon_sh-0.0.1.dev22}/holon/ext/__init__.py +0 -0
  13. {holon_sh-0.0.1.dev21 → holon_sh-0.0.1.dev22}/holon/ext/events/__init__.py +0 -0
  14. {holon_sh-0.0.1.dev21 → holon_sh-0.0.1.dev22}/holon/ext/events/_client.py +0 -0
  15. {holon_sh-0.0.1.dev21 → holon_sh-0.0.1.dev22}/holon/ext/events/_wire.py +0 -0
  16. {holon_sh-0.0.1.dev21 → holon_sh-0.0.1.dev22}/holon/ext/files/__init__.py +0 -0
  17. {holon_sh-0.0.1.dev21 → holon_sh-0.0.1.dev22}/holon/ext/files/_client.py +0 -0
  18. {holon_sh-0.0.1.dev21 → holon_sh-0.0.1.dev22}/holon/ext/files/_server.py +0 -0
  19. {holon_sh-0.0.1.dev21 → holon_sh-0.0.1.dev22}/holon/ext/files/_wire.py +0 -0
  20. {holon_sh-0.0.1.dev21 → holon_sh-0.0.1.dev22}/holon/py.typed +0 -0
  21. {holon_sh-0.0.1.dev21 → holon_sh-0.0.1.dev22}/scripts/verify_distribution.py +0 -0
  22. {holon_sh-0.0.1.dev21 → holon_sh-0.0.1.dev22}/tests/fixtures/caller/holon/apps/__init__.py +0 -0
  23. {holon_sh-0.0.1.dev21 → holon_sh-0.0.1.dev22}/tests/test_elicit.py +0 -0
  24. {holon_sh-0.0.1.dev21 → holon_sh-0.0.1.dev22}/tests/test_events.py +0 -0
  25. {holon_sh-0.0.1.dev21 → holon_sh-0.0.1.dev22}/tests/test_files.py +0 -0
  26. {holon_sh-0.0.1.dev21 → holon_sh-0.0.1.dev22}/tests/test_package.py +0 -0
  27. {holon_sh-0.0.1.dev21 → holon_sh-0.0.1.dev22}/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.dev21
3
+ Version: 0.0.1.dev22
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
@@ -374,6 +374,21 @@ class Events(Extension):
374
374
  self._sent = asyncio.Event()
375
375
  self._leases: dict[str, _Hold] = {}
376
376
  self._loop: asyncio.AbstractEventLoop | None = None
377
+ self._closed = False
378
+
379
+ def close(self) -> None:
380
+ """Initiate graceful closure of every open stream, and of each one opened from now on.
381
+
382
+ Each stream then sends its ``StreamEventsResult`` as its final frame, which tells its client that the
383
+ server closed the stream and not the subscription: the client opens it again from its cursor. Call it
384
+ when the server is about to stop, on the event loop that serves the events. It does not wait for the
385
+ streams to finish.
386
+ """
387
+ self._on_loop()
388
+ self._closed = True
389
+ for declared in self._types.values():
390
+ for hold in declared._holds(None):
391
+ hold.wake.set()
377
392
 
378
393
  def event(
379
394
  self,
@@ -516,8 +531,8 @@ class Events(Extension):
516
531
  self._loop = self._loop or running
517
532
  if running is None or running is not self._loop:
518
533
  raise RuntimeError(
519
- "Events are emitted on the event loop that serves them. From another thread, call "
520
- "loop.call_soon_threadsafe(event_type.emit, data)."
534
+ "Events are emitted and closed on the event loop that serves them. From another thread, "
535
+ "use loop.call_soon_threadsafe."
521
536
  )
522
537
 
523
538
  # Checked in the order of https://github.com/modelcontextprotocol/experimental-ext-triggers-events/blob/main/docs/design-sketch-proposal.md#error-codes
@@ -719,7 +734,7 @@ class Events(Extension):
719
734
 
720
735
  await active(*declared._resume(params.cursor, params.max_age_ms, hold.seen))
721
736
  beat = time.monotonic() + _HEARTBEAT
722
- while hold.ended is None:
737
+ while hold.ended is None and not self._closed:
723
738
  hold.wake.clear()
724
739
  if time.monotonic() >= beat:
725
740
  beat = time.monotonic() + _HEARTBEAT
@@ -740,6 +755,8 @@ class Events(Extension):
740
755
  else:
741
756
  with anyio.move_on_after(beat - time.monotonic()):
742
757
  await hold.wake.wait()
758
+ if hold.ended is None:
759
+ return {"_meta": {}}
743
760
  while (kept := declared._next(hold.seen)) and kept.sequence <= hold.until:
744
761
  await send(kept)
745
762
  ended = MCPError.from_error_data(hold.ended)
@@ -8,6 +8,7 @@ import importlib
8
8
  import mimetypes
9
9
  import os
10
10
  import re
11
+ import socket
11
12
  import sys
12
13
  from dataclasses import dataclass
13
14
  from pathlib import Path, PurePath
@@ -18,6 +19,7 @@ from mcp.server import MCPServer
18
19
  from mcp.server.auth.middleware.auth_context import AuthContextMiddleware
19
20
  from mcp.server.auth.middleware.bearer_auth import AuthenticatedUser
20
21
  from mcp.server.auth.provider import AccessToken
22
+ from mcp.server.subscriptions import ListenHandler
21
23
  from mcp.server.transport_security import TransportSecuritySettings
22
24
  from opentelemetry import context as tracing
23
25
  from opentelemetry import propagate
@@ -28,6 +30,7 @@ from starlette.responses import FileResponse, PlainTextResponse, Response
28
30
  from starlette.types import ASGIApp, Receive, Scope, Send
29
31
 
30
32
  from holon.context import _Request, _request
33
+ from holon.ext.events import Events
31
34
 
32
35
  __all__ = ["App", "load", "serve"]
33
36
 
@@ -80,7 +83,20 @@ async def serve(app: App) -> None:
80
83
  ws="none",
81
84
  timeout_graceful_shutdown=1,
82
85
  )
83
- await uvicorn.Server(config).serve()
86
+
87
+ class Server(uvicorn.Server):
88
+ async def shutdown(self, sockets: list[socket.socket] | None = None) -> None:
89
+ listen = app.server.session_manager.app.get_request_handler(
90
+ "subscriptions/listen"
91
+ )
92
+ if listen is not None and isinstance(listen.handler, ListenHandler):
93
+ listen.handler.close()
94
+ for each in app.server.middleware:
95
+ if isinstance(each, Events):
96
+ each.close()
97
+ await super().shutdown(sockets)
98
+
99
+ await Server(config).serve()
84
100
 
85
101
 
86
102
  def _asgi(app: App) -> ASGIApp:
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "holon-sh"
7
- version = "0.0.1.dev21"
7
+ version = "0.0.1.dev22"
8
8
  description = "Typed MCP clients and the caller of an MCP request"
9
9
  readme = "README.md"
10
10
  license = "Apache-2.0"
@@ -12,10 +12,20 @@ from functools import wraps
12
12
  import httpx2
13
13
  import pytest
14
14
  import uvicorn
15
+ from mcp import Client
15
16
  from mcp.server import MCPServer
16
17
  from mcp.server.auth.middleware.auth_context import get_access_token
17
18
  from mcp.server.mcpserver import Context
19
+ from mcp.server.streamable_http import CONTENT_TYPE_JSON, CONTENT_TYPE_SSE
18
20
  from mcp.shared.exceptions import MCPError
21
+ from mcp.shared.inbound import MCP_METHOD_HEADER, MCP_PROTOCOL_VERSION_HEADER
22
+ from mcp.types import (
23
+ CLIENT_CAPABILITIES_META_KEY,
24
+ CLIENT_INFO_META_KEY,
25
+ JSONRPC_VERSION,
26
+ LATEST_PROTOCOL_VERSION,
27
+ PROTOCOL_VERSION_META_KEY,
28
+ )
19
29
  from opentelemetry import propagate
20
30
  from starlette.datastructures import Headers
21
31
  from starlette.responses import RedirectResponse, Response
@@ -116,8 +126,14 @@ async def test_inside_holon_a_tool_sees_whom_the_waypoint_admitted_and_not_the_h
116
126
  ("/mcp", {"x-holon-context": signed_in}, RequestContext(ann, None)),
117
127
  (
118
128
  "/mcp/inspector",
119
- {"x-holon-context": signed_in, "x-holon-caller": REPORTER},
120
- RequestContext(ann, Caller("reporter", "session")),
129
+ {
130
+ "x-holon-context": context(principal=PERSON),
131
+ "x-holon-caller": REPORTER,
132
+ },
133
+ RequestContext(
134
+ Principal("https://id.example", "ann", "web", [], {}),
135
+ Caller("reporter", "session"),
136
+ ),
121
137
  ),
122
138
  (
123
139
  "/mcp",
@@ -131,39 +147,21 @@ async def test_inside_holon_a_tool_sees_whom_the_waypoint_admitted_and_not_the_h
131
147
  await call(origin + path, "inspect", headers)
132
148
  admitted, token, names, traceparent = seen.pop()
133
149
  assert admitted == expected
150
+ assert (token is None) == (expected == RequestContext(None, None))
134
151
  assert not {name for name in names if name.startswith("x-holon-")}
135
152
  assert "authorization" not in names
136
153
  assert traceparent == TRACEPARENT
137
- if expected == RequestContext(None, None):
138
- assert token is None
139
- continue
140
- assert token.token == headers.get("x-holon-context", "")
141
-
142
-
143
- def token(payload):
144
- encoded = base64.urlsafe_b64encode(payload.encode()).rstrip(b"=")
145
- return f"e30.{encoded.decode()}.signature"
146
154
 
147
155
 
148
156
  @asynchronous
149
157
  async def test_a_malformed_context_is_a_bad_request(monkeypatch):
150
158
  monkeypatch.setenv("HOLON_PLATFORM", "1")
151
- person = {**PERSON, "act": {"sub": "agent"}}
152
- seen = []
153
- async with served(_asgi(App(inspector(seen)))) as origin:
159
+ async with served(_asgi(App(MCPServer("strict")))) as origin:
154
160
  for headers in [
155
161
  [("x-holon-context", context()), ("x-holon-context", context())],
156
162
  [("x-holon-caller", REPORTER), ("x-holon-caller", REPORTER)],
157
163
  [("x-holon-caller", "reporter")],
158
- [("x-holon-context", "header.claims")],
159
- [("x-holon-context", "e30.e30=.signature")],
160
- [("x-holon-context", token("person"))],
161
- [("x-holon-context", token("[]"))],
162
- [("x-holon-context", token("null"))],
163
164
  [("x-holon-context", context(principal="user"))],
164
- [("x-holon-context", context(principal={"iss": 1}))],
165
- [("x-holon-context", context(principal={"claims": []}))],
166
- [("x-holon-context", context(principal={**person, "act": ["agent"]}))],
167
165
  ]:
168
166
  async with httpx2.AsyncClient() as client:
169
167
  response = await client.post(
@@ -173,7 +171,6 @@ async def test_a_malformed_context_is_a_bad_request(monkeypatch):
173
171
  400,
174
172
  "Malformed Holon context\n",
175
173
  ), headers
176
- assert seen == []
177
174
 
178
175
 
179
176
  @asynchronous
@@ -187,9 +184,8 @@ async def test_outside_holon_the_same_headers_make_an_anonymous_request(monkeypa
187
184
  "authorization": "Bearer forged",
188
185
  }
189
186
  await call(origin + "/mcp", "inspect", headers)
190
- [(admitted, token, names, _)] = seen
191
- assert (admitted, token) == (RequestContext(None, None), None)
192
- assert not names & {"x-holon-context", "x-holon-caller", "authorization"}
187
+ [(admitted, _, _, _)] = seen
188
+ assert admitted == RequestContext(None, None)
193
189
 
194
190
 
195
191
  @asynchronous
@@ -270,53 +266,31 @@ async def test_the_frontend_serves_its_files_and_nothing_hidden_or_outside_it(
270
266
  tmp_path,
271
267
  ):
272
268
  web = tmp_path / "web"
273
- (web / "nested").mkdir(parents=True)
269
+ web.mkdir()
274
270
  (web / "index.html").write_text("<p>Home</p>")
275
- (web / "nested/index.html").write_text("<p>Nested</p>")
276
271
  (web / "style.css").write_text("p {}")
277
- (web / "data.json").write_text("{}")
278
272
  (web / ".private").write_text("Hidden")
279
273
  (tmp_path / "secret").write_text("Outside")
280
274
  (web / "escape").symlink_to(tmp_path / "secret")
281
- (web / "linked.css").symlink_to(web / "style.css")
282
- os.mkfifo(web / "pipe")
283
275
  app = _asgi(App(MCPServer("site"), web))
284
276
  async with httpx2.AsyncClient(
285
277
  transport=httpx2.ASGITransport(app=app), base_url="http://app"
286
278
  ) as http:
287
279
  for path, body, kind in [
288
- ("/", "<p>Home</p>", "text/html; charset=utf-8"),
289
- ("/index.html", "<p>Home</p>", "text/html; charset=utf-8"),
290
- ("/nested", "<p>Nested</p>", "text/html; charset=utf-8"),
291
- ("/nested/", "<p>Nested</p>", "text/html; charset=utf-8"),
292
- ("/style.css", "p {}", "text/css; charset=utf-8"),
293
- ("/linked.css", "p {}", "text/css; charset=utf-8"),
294
- ("/data.json", "{}", "application/json"),
280
+ ("/", "<p>Home</p>", "text/html"),
281
+ ("/style.css", "p {}", "text/css"),
295
282
  ]:
296
283
  response = await http.get(path)
297
284
  assert (response.status_code, response.text) == (200, body), path
298
- assert response.headers["content-type"] == kind
285
+ assert response.headers["content-type"].startswith(kind)
299
286
  assert response.headers["x-content-type-options"] == "nosniff"
300
- head = await http.head("/style.css")
301
- assert (head.status_code, head.content) == (200, b"")
302
- for path in [
303
- "/.private",
304
- "/%2eprivate",
305
- "/%2E%2E/secret",
306
- "/escape",
307
- "/pipe",
308
- "/missing",
309
- ]:
287
+ assert (await http.head("/style.css")).status_code == 200
288
+ for path in ["/.private", "/escape", "/missing"]:
310
289
  assert (await http.get(path)).status_code == 404, path
311
290
  assert (await http.post("/")).status_code == 404
312
- async with httpx2.AsyncClient(
313
- transport=httpx2.ASGITransport(app=_asgi(App(MCPServer("bare")))),
314
- base_url="http://app",
315
- ) as http:
316
- assert (await http.get("/")).status_code == 404
317
291
 
318
292
 
319
- def test_python_m_holon_serve_runs_an_entry_with_a_16_kib_context_and_stops_on_sigterm(
293
+ def test_python_m_holon_serve_runs_an_entry_with_a_16_kib_context_and_on_sigterm_closes_its_streams_and_stops(
320
294
  tmp_path,
321
295
  ):
322
296
  (tmp_path / "src").mkdir()
@@ -324,30 +298,21 @@ def test_python_m_holon_serve_runs_an_entry_with_a_16_kib_context_and_stops_on_s
324
298
  (tmp_path / "web/index.html").write_text("<p>Home</p>")
325
299
  (tmp_path / "src/server.py").write_text(
326
300
  """from mcp.server import MCPServer
327
- from holon.context import get_context
301
+ from holon.ext.events import Events
328
302
 
329
- server = MCPServer("large")
303
+ events = Events()
304
+ events.event("ticked", input_schema={"type": "object"}, payload_schema={"type": "object"})
305
+ server = MCPServer("large", extensions=[events], middleware=[events])
330
306
  frontend = "web"
331
-
332
-
333
- @server.tool()
334
- def subject() -> str:
335
- return get_context().principal.subject
336
307
  """
337
308
  )
338
- subject = "a" * 12200
339
- token = context(principal={**PERSON, "sub": subject})
340
- assert len(token) >= 16 * 1024
341
309
  with socket.socket() as reserved:
342
310
  reserved.bind(("127.0.0.1", 0))
343
311
  port = reserved.getsockname()[1]
344
- environment = {**os.environ, "HOLON_PLATFORM": "1", "PORT": str(port)}
345
312
  process = subprocess.Popen(
346
313
  [sys.executable, "-m", "holon.serve", "src/server.py"],
347
314
  cwd=tmp_path,
348
- env=environment,
349
- stderr=subprocess.PIPE,
350
- text=True,
315
+ env={**os.environ, "PORT": str(port)},
351
316
  )
352
317
 
353
318
  async def exercise():
@@ -361,19 +326,47 @@ def subject() -> str:
361
326
  await asyncio.sleep(0.05)
362
327
  assert home.text == "<p>Home</p>"
363
328
  reader, writer = await asyncio.open_connection("127.0.0.1", port)
364
- head = f"GET / HTTP/1.1\r\nhost: app\r\nx-holon-context: {token}\r\n\r\n"
365
- for piece in [head[:-2], head[-2:]]:
366
- writer.write(piece.encode())
367
- await writer.drain()
368
- await asyncio.sleep(0.1)
329
+ head = f"GET / HTTP/1.1\r\nhost: app\r\nx-holon-context: {'a' * 16384}\r\n"
330
+ writer.write(head.encode())
331
+ await writer.drain()
332
+ await asyncio.sleep(0.1)
333
+ writer.write(b"\r\n")
369
334
  assert (await reader.readline()).startswith(b"HTTP/1.1 200")
370
335
  writer.close()
371
- result = await call(origin + "/mcp", "subject", {"x-holon-context": token})
372
- assert result.structured_content == {"result": subject}
336
+ meta = {
337
+ PROTOCOL_VERSION_META_KEY: LATEST_PROTOCOL_VERSION,
338
+ CLIENT_INFO_META_KEY: {"name": "test", "version": "1"},
339
+ CLIENT_CAPABILITIES_META_KEY: {},
340
+ }
341
+ stream = {
342
+ "jsonrpc": JSONRPC_VERSION,
343
+ "id": 7,
344
+ "method": "events/stream",
345
+ "params": {"name": "ticked", "arguments": {}, "_meta": meta},
346
+ }
347
+ headers = {
348
+ "accept": f"{CONTENT_TYPE_JSON}, {CONTENT_TYPE_SSE}",
349
+ MCP_PROTOCOL_VERSION_HEADER: LATEST_PROTOCOL_VERSION,
350
+ MCP_METHOD_HEADER: "events/stream",
351
+ }
352
+ async with (
353
+ Client(origin + "/mcp", mode=LATEST_PROTOCOL_VERSION) as client,
354
+ client.listen(tools_list_changed=True) as subscription,
355
+ httpx2.AsyncClient() as http,
356
+ http.stream("POST", origin + "/mcp", json=stream, headers=headers) as sent,
357
+ ):
358
+ frames = sent.aiter_lines()
359
+ while not (await anext(frames)).startswith("data: "):
360
+ pass
361
+ process.send_signal(signal.SIGTERM)
362
+ last = [frame async for frame in frames if frame.startswith("data: ")][-1]
363
+ async for _ in subscription:
364
+ pass
365
+ closed = json.loads(last.removeprefix("data: "))
366
+ assert closed["id"] == 7 and "result" in closed
373
367
 
374
368
  try:
375
369
  asyncio.run(asyncio.wait_for(exercise(), timeout=20))
370
+ process.wait(timeout=10)
376
371
  finally:
377
- process.send_signal(signal.SIGTERM)
378
- _, errors = process.communicate(timeout=10)
379
- assert "Application shutdown complete" in errors
372
+ process.kill()
@@ -1,71 +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 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)
File without changes
File without changes