holon-sh 0.0.1.dev18__tar.gz → 0.0.1.dev19__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.dev18 → holon_sh-0.0.1.dev19}/PKG-INFO +1 -1
  2. {holon_sh-0.0.1.dev18 → holon_sh-0.0.1.dev19}/holon/ext/events/_server.py +26 -33
  3. {holon_sh-0.0.1.dev18 → holon_sh-0.0.1.dev19}/pyproject.toml +1 -1
  4. {holon_sh-0.0.1.dev18 → holon_sh-0.0.1.dev19}/tests/test_events.py +38 -43
  5. {holon_sh-0.0.1.dev18 → holon_sh-0.0.1.dev19}/tests/test_package.py +1 -1
  6. {holon_sh-0.0.1.dev18 → holon_sh-0.0.1.dev19}/.gitignore +0 -0
  7. {holon_sh-0.0.1.dev18 → holon_sh-0.0.1.dev19}/LICENSE +0 -0
  8. {holon_sh-0.0.1.dev18 → holon_sh-0.0.1.dev19}/README.md +0 -0
  9. {holon_sh-0.0.1.dev18 → holon_sh-0.0.1.dev19}/holon/client.py +0 -0
  10. {holon_sh-0.0.1.dev18 → holon_sh-0.0.1.dev19}/holon/context.py +0 -0
  11. {holon_sh-0.0.1.dev18 → holon_sh-0.0.1.dev19}/holon/ext/__init__.py +0 -0
  12. {holon_sh-0.0.1.dev18 → holon_sh-0.0.1.dev19}/holon/ext/events/__init__.py +0 -0
  13. {holon_sh-0.0.1.dev18 → holon_sh-0.0.1.dev19}/holon/ext/events/_client.py +0 -0
  14. {holon_sh-0.0.1.dev18 → holon_sh-0.0.1.dev19}/holon/ext/events/_wire.py +0 -0
  15. {holon_sh-0.0.1.dev18 → holon_sh-0.0.1.dev19}/holon/ext/files/__init__.py +0 -0
  16. {holon_sh-0.0.1.dev18 → holon_sh-0.0.1.dev19}/holon/ext/files/_client.py +0 -0
  17. {holon_sh-0.0.1.dev18 → holon_sh-0.0.1.dev19}/holon/ext/files/_server.py +0 -0
  18. {holon_sh-0.0.1.dev18 → holon_sh-0.0.1.dev19}/holon/ext/files/_wire.py +0 -0
  19. {holon_sh-0.0.1.dev18 → holon_sh-0.0.1.dev19}/holon/py.typed +0 -0
  20. {holon_sh-0.0.1.dev18 → holon_sh-0.0.1.dev19}/holon/serve.py +0 -0
  21. {holon_sh-0.0.1.dev18 → holon_sh-0.0.1.dev19}/scripts/verify_distribution.py +0 -0
  22. {holon_sh-0.0.1.dev18 → holon_sh-0.0.1.dev19}/tests/fixtures/caller/holon/apps/__init__.py +0 -0
  23. {holon_sh-0.0.1.dev18 → holon_sh-0.0.1.dev19}/tests/test_context.py +0 -0
  24. {holon_sh-0.0.1.dev18 → holon_sh-0.0.1.dev19}/tests/test_elicit.py +0 -0
  25. {holon_sh-0.0.1.dev18 → holon_sh-0.0.1.dev19}/tests/test_files.py +0 -0
  26. {holon_sh-0.0.1.dev18 → holon_sh-0.0.1.dev19}/tests/test_runtime.py +0 -0
  27. {holon_sh-0.0.1.dev18 → holon_sh-0.0.1.dev19}/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.dev18
3
+ Version: 0.0.1.dev19
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
@@ -12,13 +12,15 @@ import secrets
12
12
  import time
13
13
  import uuid
14
14
  from collections import Counter
15
- from collections.abc import AsyncIterator, Awaitable, Callable, Sequence
15
+ from collections.abc import AsyncIterator, Awaitable, Callable, Mapping, Sequence
16
16
  from contextlib import asynccontextmanager
17
17
  from dataclasses import dataclass, field
18
18
  from datetime import UTC, datetime
19
19
  from typing import Any, Generic, TypeAlias, TypeVar, cast
20
20
 
21
21
  import anyio
22
+ import jsonschema
23
+ from jsonschema.protocols import Validator
22
24
  from mcp.server.context import CallNext, HandlerResult, ServerRequestContext
23
25
  from mcp.server.extension import Extension, MethodBinding
24
26
  from mcp.server.lowlevel.server import Server
@@ -33,8 +35,9 @@ from mcp.types import (
33
35
  RequestParams,
34
36
  ServerNotification,
35
37
  )
36
- from pydantic import Field, StrictInt, StrictStr, TypeAdapter, ValidationError
38
+ from pydantic import Field, StrictInt, StrictStr
37
39
  from pydantic_core import to_json, to_jsonable_python
40
+ from referencing import Registry
38
41
 
39
42
  from holon.context import get_context
40
43
  from holon.ext.events._wire import (
@@ -64,7 +67,7 @@ _MAX_SUBSCRIPTIONS_PER_CALLER = 100
64
67
  _LIST_PAGE_SIZE = 100
65
68
  _SUBSCRIBE_TIMEOUT = 30.0
66
69
 
67
- A = TypeVar("A")
70
+ A = TypeVar("A", bound=Mapping[str, Any])
68
71
  T = TypeVar("T")
69
72
 
70
73
 
@@ -159,7 +162,7 @@ class EventType(Generic[A, D]):
159
162
 
160
163
  name: str
161
164
  _events: Events
162
- _input: TypeAdapter[A]
165
+ _input: Validator
163
166
  _descriptor: dict[str, Any]
164
167
  _match: Match[D, A] | None
165
168
  _transform: Transform[D, A] | None
@@ -376,7 +379,7 @@ class Events(Extension):
376
379
  self,
377
380
  name: str,
378
381
  *,
379
- input_schema: type[A] | TypeAdapter[A],
382
+ input_schema: dict[str, Any],
380
383
  payload_schema: dict[str, Any],
381
384
  description: str | None = None,
382
385
  match: Match[D, A] | None = None,
@@ -387,12 +390,14 @@ class Events(Extension):
387
390
  ) -> EventType[A, D]:
388
391
  """Declare an event type.
389
392
 
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``.
393
+ Annotate the result as ``EventType[Arguments, Data]`` to type the hooks and ``emit``. Hooks receive the
394
+ arguments as the subscription sent them, so ``Arguments`` is a ``TypedDict`` or ``dict[str, Any]``. Each
395
+ hook's ``context`` is the server's context of the request it runs in. A subscription outlives the first
396
+ request to name it, where ``on_subscribe`` runs, and other requests may share it: keep what the hook reads
397
+ from ``context``, not ``context``.
393
398
 
394
399
  Args:
395
- input_schema: Type of a subscription's arguments.
400
+ input_schema: JSON Schema of a subscription's arguments. Arguments that do not match are refused.
396
401
  payload_schema: JSON Schema of each occurrence's data.
397
402
  match: ``(context, event, arguments)``: whether a subscription receives an event. Defaults to all.
398
403
  transform: ``(context, event, arguments)``: the data a subscription receives.
@@ -405,21 +410,18 @@ class Events(Extension):
405
410
  raise ValueError(f"Event {name} is already declared.")
406
411
  if not delivery:
407
412
  raise ValueError(f"Event {name} must be delivered by poll, push or both.")
408
- arguments = (
409
- input_schema
410
- if isinstance(input_schema, TypeAdapter)
411
- else TypeAdapter(input_schema)
412
- )
413
+ checker = jsonschema.validators.validator_for(input_schema)
414
+ checker.check_schema(input_schema)
413
415
  descriptor = {
414
416
  "name": name,
415
417
  **({"description": description} if description else {}),
416
- "inputSchema": arguments.json_schema(),
418
+ "inputSchema": input_schema,
417
419
  "payloadSchema": payload_schema,
418
420
  }
419
421
  declared = EventType(
420
422
  name,
421
423
  self,
422
- arguments,
424
+ checker(input_schema, registry=Registry()),
423
425
  descriptor,
424
426
  match,
425
427
  transform,
@@ -532,16 +534,14 @@ class Events(Extension):
532
534
  "Unsupported",
533
535
  {"feature": "deliveryMode", "value": delivery},
534
536
  )
535
- try:
536
- arguments = declared._input.validate_python(params.arguments or {})
537
- except ValidationError as error:
538
- problems = "; ".join(
539
- f"{'.'.join(map(str, each['loc'])) or 'arguments'}: {each['msg']}"
540
- for each in error.errors()
541
- )
537
+ arguments = params.arguments or {}
538
+ if error := jsonschema.exceptions.best_match(
539
+ declared._input.iter_errors(arguments)
540
+ ):
542
541
  raise MCPError(
543
- INVALID_PARAMS, f"Invalid arguments for {params.name}: {problems}"
544
- ) from None
542
+ INVALID_PARAMS,
543
+ f"Invalid arguments for {params.name}: {error.json_path}: {error.message}",
544
+ )
545
545
  principal = get_context().principal
546
546
  caller = ""
547
547
  if principal is not None:
@@ -556,14 +556,7 @@ class Events(Extension):
556
556
  if principal is None and delivery == "push":
557
557
  id = f"sub_{uuid.uuid4().hex}"
558
558
  else:
559
- canonical = json.dumps(
560
- [
561
- caller,
562
- declared.name,
563
- declared._input.dump_python(arguments, mode="json"),
564
- ],
565
- sort_keys=True,
566
- )
559
+ canonical = json.dumps([caller, declared.name, arguments], sort_keys=True)
567
560
  id = f"sub_{hashlib.sha256(canonical.encode()).hexdigest()[:32]}"
568
561
  request = _Request(
569
562
  declared,
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "holon-sh"
7
- version = "0.0.1.dev18"
7
+ version = "0.0.1.dev19"
8
8
  description = "Typed MCP clients and the caller of an MCP request"
9
9
  readme = "README.md"
10
10
  license = "Apache-2.0"
@@ -52,11 +52,11 @@ def asynchronous(test):
52
52
  return run
53
53
 
54
54
 
55
- def declare(events=None, **hooks) -> tuple[Events, EventType[Board, Change]]:
55
+ def declare(events=None, **hooks) -> tuple[Events, EventType[dict[str, str], Change]]:
56
56
  events = events or Events()
57
57
  return events, events.event(
58
58
  "board.changed",
59
- input_schema=Board,
59
+ input_schema=Board.model_json_schema(),
60
60
  payload_schema=Change.model_json_schema(),
61
61
  **hooks,
62
62
  )
@@ -166,7 +166,7 @@ async def test_a_subscription_hears_what_its_arguments_match_as_shaped_across_a_
166
166
  delivery,
167
167
  ):
168
168
  events, changed = declare(
169
- match=lambda context, event, arguments: event.data.board == arguments.board,
169
+ match=lambda context, event, arguments: event.data.board == arguments["board"],
170
170
  transform=lambda context, event, arguments: {
171
171
  "board": event.data.board,
172
172
  "text": event.data.text.upper(),
@@ -207,6 +207,22 @@ async def test_targeted_events_follow_shared_identity_but_isolate_anonymous_read
207
207
  assert (await anext(second)).event_id == expected
208
208
 
209
209
 
210
+ @asynchronous
211
+ async def test_a_subscription_is_named_by_its_arguments_as_sent():
212
+ subscribed = []
213
+ events, _ = declare(on_subscribe=lambda context, args, id: subscribed.append(args))
214
+ ann = {"x-holon-context": signed_in("ann")}
215
+ async with served(events) as port, httpx2.AsyncClient(headers=ann) as http:
216
+ for arguments in [
217
+ {"board": "b"},
218
+ {"n": 1, "board": "b"},
219
+ {"board": "b", "n": 1},
220
+ ]:
221
+ params = {"name": "board.changed", "arguments": arguments}
222
+ assert "result" in await call(http, port, "events/poll", params)
223
+ assert subscribed == [{"board": "b"}, {"n": 1, "board": "b"}]
224
+
225
+
210
226
  @pytest.mark.parametrize("targeted", [False, True])
211
227
  @pytest.mark.parametrize("delivery", ["push", "poll"])
212
228
  @asynchronous
@@ -236,28 +252,21 @@ async def test_a_subscription_behind_what_is_kept_is_told_of_the_gap_and_carries
236
252
 
237
253
 
238
254
  @asynchronous
239
- async def test_what_a_subscribe_hook_emits_reaches_its_subscription_first_and_a_cursor_from_before_a_restart_is_a_gap():
240
- events, changed = declare(
241
- on_subscribe=lambda context, arguments, id: say(
242
- changed, arguments.board, "welcome", to=id
243
- )
244
- )
245
- restarted = declare()[1].cursor()
246
- gaps = []
255
+ async def test_a_cursor_from_before_a_restart_is_a_gap():
256
+ events, changed = declare()
257
+ restarted, gaps = declare()[1].cursor(), []
247
258
  async with served(events) as port:
248
- for cursor in [None, restarted]:
249
- for delivery in ["push", "poll"]:
250
- board = f"{delivery} {'resumed' if cursor else 'fresh'}"
251
- async with client(port, user="ann").subscribe(
252
- "board.changed",
253
- {"board": board},
254
- delivery=delivery,
255
- cursor=cursor,
256
- on_gap=partial(gaps.append, board),
257
- ) as changes:
258
- say(changed, board, "hello")
259
- assert await take(changes, 2) == ["welcome", "hello"]
260
- assert gaps == ["push resumed", "poll resumed"]
259
+ for delivery in ["push", "poll"]:
260
+ async with client(port, user="ann").subscribe(
261
+ "board.changed",
262
+ {"board": delivery},
263
+ delivery=delivery,
264
+ cursor=restarted,
265
+ on_gap=partial(gaps.append, delivery),
266
+ ) as changes:
267
+ say(changed, delivery, "hello")
268
+ assert await take(changes, 1) == ["hello"]
269
+ assert gaps == ["push", "poll"]
261
270
 
262
271
 
263
272
  @asynchronous
@@ -265,7 +274,7 @@ async def test_a_subscription_the_app_ends_is_sent_what_was_emitted_to_it_unless
265
274
  ids = {}
266
275
 
267
276
  def on_subscribe(context, arguments, id):
268
- ids[arguments.board] = id
277
+ ids[arguments["board"]] = id
269
278
 
270
279
  events, changed = declare(on_subscribe=on_subscribe)
271
280
  async with served(events) as port:
@@ -297,16 +306,6 @@ async def test_a_subscription_the_app_ends_is_sent_what_was_emitted_to_it_unless
297
306
 
298
307
  @asynchronous
299
308
  async def test_the_messages_on_the_wire_are_the_sketchs():
300
- recursive = {
301
- "$ref": "#/$defs/Node",
302
- "$defs": {
303
- "Node": {
304
- "type": "object",
305
- "properties": {"child": {"$ref": "#/$defs/Node"}},
306
- }
307
- },
308
- }
309
-
310
309
  def shaped(context, event, arguments):
311
310
  if event.data.text == "bad":
312
311
  raise ValueError("cannot be shaped")
@@ -319,10 +318,10 @@ async def test_the_messages_on_the_wire_are_the_sketchs():
319
318
  )
320
319
  events.event(
321
320
  "board.locked",
322
- input_schema=Board,
323
- payload_schema=recursive,
321
+ input_schema=Board.model_json_schema(),
322
+ payload_schema=Change.model_json_schema(),
324
323
  delivery=["poll"],
325
- authorize=lambda context, arguments: arguments.board != "secret",
324
+ authorize=lambda context, arguments: arguments["board"] != "secret",
326
325
  )
327
326
  async with served(events) as port, httpx2.AsyncClient(timeout=10) as http:
328
327
  discovered = await call(http, port, "server/discover", {})
@@ -331,7 +330,6 @@ async def test_the_messages_on_the_wire_are_the_sketchs():
331
330
  event["name"]: event
332
331
  for event in (await call(http, port, "events/list", {}))["result"]["events"]
333
332
  }
334
- assert listed["board.locked"]["payloadSchema"] == recursive
335
333
  assert set(listed["board.changed"]["delivery"]) == {"poll", "push"}
336
334
  expected = {
337
335
  "description": "A board changed",
@@ -486,10 +484,7 @@ async def test_a_subscription_can_be_retried_after_setup_times_out(
486
484
 
487
485
  @asynchronous
488
486
  async def test_a_subscription_from_the_cursor_read_with_a_snapshot_hears_every_change_after_it():
489
- events, said = Events(), []
490
- changed: EventType[Board, Change] = events.event(
491
- "board.changed", input_schema=Board, payload_schema=Change.model_json_schema()
492
- )
487
+ (events, changed), said = declare(), []
493
488
 
494
489
  def tell(text):
495
490
  said.append(text)
@@ -20,7 +20,7 @@ from holon.ext.events import Events, EventType
20
20
 
21
21
  def emit() -> None:
22
22
  changed: EventType[dict[str, str], dict[str, str]] = Events().event(
23
- "board.changed", input_schema=dict[str, str],
23
+ "board.changed", input_schema={"type": "object"},
24
24
  payload_schema={"type": "object", "additionalProperties": {"type": "string"}},
25
25
  )
26
26
  changed.emit({"text": "hello"})
File without changes
File without changes