holon-sh 0.0.1.dev24__tar.gz → 0.0.1.dev26__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.dev24 → holon_sh-0.0.1.dev26}/PKG-INFO +1 -1
  2. {holon_sh-0.0.1.dev24 → holon_sh-0.0.1.dev26}/holon/client.py +17 -7
  3. {holon_sh-0.0.1.dev24 → holon_sh-0.0.1.dev26}/holon/ext/events/_server.py +11 -12
  4. {holon_sh-0.0.1.dev24 → holon_sh-0.0.1.dev26}/pyproject.toml +1 -1
  5. {holon_sh-0.0.1.dev24 → holon_sh-0.0.1.dev26}/tests/test_events.py +26 -23
  6. {holon_sh-0.0.1.dev24 → holon_sh-0.0.1.dev26}/tests/test_runtime.py +13 -2
  7. {holon_sh-0.0.1.dev24 → holon_sh-0.0.1.dev26}/.gitignore +0 -0
  8. {holon_sh-0.0.1.dev24 → holon_sh-0.0.1.dev26}/LICENSE +0 -0
  9. {holon_sh-0.0.1.dev24 → holon_sh-0.0.1.dev26}/README.md +0 -0
  10. {holon_sh-0.0.1.dev24 → holon_sh-0.0.1.dev26}/holon/context.py +0 -0
  11. {holon_sh-0.0.1.dev24 → holon_sh-0.0.1.dev26}/holon/ext/__init__.py +0 -0
  12. {holon_sh-0.0.1.dev24 → holon_sh-0.0.1.dev26}/holon/ext/events/__init__.py +0 -0
  13. {holon_sh-0.0.1.dev24 → holon_sh-0.0.1.dev26}/holon/ext/events/_client.py +0 -0
  14. {holon_sh-0.0.1.dev24 → holon_sh-0.0.1.dev26}/holon/ext/events/_wire.py +0 -0
  15. {holon_sh-0.0.1.dev24 → holon_sh-0.0.1.dev26}/holon/ext/files/__init__.py +0 -0
  16. {holon_sh-0.0.1.dev24 → holon_sh-0.0.1.dev26}/holon/ext/files/_client.py +0 -0
  17. {holon_sh-0.0.1.dev24 → holon_sh-0.0.1.dev26}/holon/ext/files/_server.py +0 -0
  18. {holon_sh-0.0.1.dev24 → holon_sh-0.0.1.dev26}/holon/ext/files/_wire.py +0 -0
  19. {holon_sh-0.0.1.dev24 → holon_sh-0.0.1.dev26}/holon/py.typed +0 -0
  20. {holon_sh-0.0.1.dev24 → holon_sh-0.0.1.dev26}/holon/serve.py +0 -0
  21. {holon_sh-0.0.1.dev24 → holon_sh-0.0.1.dev26}/scripts/verify_distribution.py +0 -0
  22. {holon_sh-0.0.1.dev24 → holon_sh-0.0.1.dev26}/tests/fixtures/caller/holon/apps/__init__.py +0 -0
  23. {holon_sh-0.0.1.dev24 → holon_sh-0.0.1.dev26}/tests/test_elicit.py +0 -0
  24. {holon_sh-0.0.1.dev24 → holon_sh-0.0.1.dev26}/tests/test_files.py +0 -0
  25. {holon_sh-0.0.1.dev24 → holon_sh-0.0.1.dev26}/tests/test_package.py +0 -0
  26. {holon_sh-0.0.1.dev24 → holon_sh-0.0.1.dev26}/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.dev24
3
+ Version: 0.0.1.dev26
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
@@ -1,5 +1,6 @@
1
1
  from __future__ import annotations
2
2
 
3
+ import json
3
4
  import os
4
5
  from collections.abc import AsyncIterator, Awaitable, Callable, Mapping, Sequence
5
6
  from contextlib import asynccontextmanager
@@ -110,6 +111,12 @@ class CallOptions(TypedDict, total=False):
110
111
  elicit: Callable[[ElicitRequestParams], Awaitable[ElicitResult]]
111
112
 
112
113
 
114
+ def _text(result: CallToolResult) -> str | None:
115
+ return next(
116
+ (part.text for part in result.content if isinstance(part, TextContent)), None
117
+ )
118
+
119
+
113
120
  class ToolCallError(RuntimeError):
114
121
  """Raised by ``tools.<name>`` when a tool fails or needs input.
115
122
 
@@ -130,10 +137,7 @@ class ToolCallError(RuntimeError):
130
137
  )
131
138
  else:
132
139
  message = "tool failed"
133
- detail = next(
134
- (part.text for part in result.content if isinstance(part, TextContent)),
135
- "",
136
- )
140
+ detail = _text(result) or ""
137
141
  if detail:
138
142
  message = f"{message}: {detail}"
139
143
  super().__init__(f"{app}.{tool}: {message}")
@@ -207,9 +211,10 @@ class _App:
207
211
  if contract is None
208
212
  else {tool["name"]: tool for tool in contract["tools"]}
209
213
  )
214
+ parsed = set((contract or {}).get("responses", ()))
210
215
  self.tools = SimpleNamespace(
211
216
  **{
212
- name: partial(self._call_tool, tool)
217
+ name: partial(self._call_tool, tool, name in parsed)
213
218
  for name, tool in self._definitions.items()
214
219
  if not name.startswith("_")
215
220
  }
@@ -346,6 +351,7 @@ class _App:
346
351
  async def _call_tool(
347
352
  self,
348
353
  tool: dict[str, Any],
354
+ parsed: bool,
349
355
  options: CallOptions | None = None,
350
356
  /,
351
357
  **arguments: object,
@@ -353,6 +359,9 @@ class _App:
353
359
  result = await self.call_tool(tool["name"], options, **arguments)
354
360
  if isinstance(result, InputRequiredResult) or result.is_error:
355
361
  raise ToolCallError(self._name, tool["name"], result)
362
+ if parsed:
363
+ text = _text(result)
364
+ return None if text is None else json.loads(text)
356
365
  return result.structured_content if "outputSchema" in tool else result
357
366
 
358
367
 
@@ -360,8 +369,9 @@ class Apps:
360
369
  """An application's dependencies, as generated clients use them.
361
370
 
362
371
  Applications use ``apps`` or ``create_apps`` from ``holon.apps``. Each dependency is ``apps.<name>``
363
- or ``apps[name]``: its ``tools.<name>`` return structured output or raise :class:`ToolCallError`,
364
- and its ``call_tool`` returns the full result.
372
+ or ``apps[name]``: its ``tools.<name>`` return structured output, or the parsed JSON text of a tool
373
+ the contract lists under ``responses``, or raise :class:`ToolCallError`, and its ``call_tool``
374
+ returns the full result.
365
375
 
366
376
  Args:
367
377
  identity: Application name, version, and ``requires``.
@@ -370,7 +370,7 @@ class Events(Extension):
370
370
  self._epoch = secrets.token_hex(6)
371
371
  self._types: dict[str, EventType[Any, Any]] = {}
372
372
  self._held: Counter[str] = Counter()
373
- self._sending: Counter[str] = Counter()
373
+ self._sending = 0
374
374
  self._sent = asyncio.Event()
375
375
  self._leases: dict[str, _Hold] = {}
376
376
  self._loop: asyncio.AbstractEventLoop | None = None
@@ -595,7 +595,10 @@ class Events(Extension):
595
595
  "ResourceExhausted",
596
596
  {"limit": "subscriptions", "max": _MAX_SUBSCRIPTIONS},
597
597
  )
598
- if self._held[request.caller] >= _MAX_SUBSCRIPTIONS_PER_CALLER:
598
+ if (
599
+ request.caller
600
+ and self._held[request.caller] >= _MAX_SUBSCRIPTIONS_PER_CALLER
601
+ ):
599
602
  raise MCPError(
600
603
  RESOURCE_EXHAUSTED,
601
604
  "ResourceExhausted",
@@ -676,20 +679,16 @@ class Events(Extension):
676
679
  hold.lease.cancel()
677
680
  self._close(hold)
678
681
 
679
- # Waits for room to send `size` bytes. One caller may use a quarter of the budget.
682
+ # Waits for room to send `size` bytes.
680
683
  @asynccontextmanager
681
- async def _send_budget(self, size: int, caller: str) -> AsyncIterator[None]:
682
- while (
683
- (sending := self._sending.total()) and sending + size > _MAX_SENDING_BYTES
684
- ) or (
685
- (mine := self._sending[caller]) and mine + size > _MAX_SENDING_BYTES // 4
686
- ):
684
+ async def _send_budget(self, size: int) -> AsyncIterator[None]:
685
+ while self._sending and self._sending + size > _MAX_SENDING_BYTES:
687
686
  await self._sent.wait()
688
- self._sending[caller] += size
687
+ self._sending += size
689
688
  try:
690
689
  yield
691
690
  finally:
692
- _release(self._sending, caller, size)
691
+ self._sending -= size
693
692
  self._sent.set()
694
693
  self._sent = asyncio.Event()
695
694
 
@@ -708,7 +707,7 @@ class Events(Extension):
708
707
  method=f"notifications/events/{method}", params=body
709
708
  )
710
709
  with anyio.move_on_after(2 * _HEARTBEAT) as waited:
711
- async with self._send_budget(size, request.caller):
710
+ async with self._send_budget(size):
712
711
  await ctx.session.send_notification(
713
712
  cast(ServerNotification, notification),
714
713
  related_request_id=ctx.request_id,
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "holon-sh"
7
- version = "0.0.1.dev24"
7
+ version = "0.0.1.dev26"
8
8
  description = "Typed MCP clients and the caller of an MCP request"
9
9
  readme = "README.md"
10
10
  license = "Apache-2.0"
@@ -21,7 +21,6 @@ from mcp.types import (
21
21
  JSONRPC_VERSION,
22
22
  LATEST_PROTOCOL_VERSION,
23
23
  PROTOCOL_VERSION_META_KEY,
24
- CallToolResult,
25
24
  ErrorData,
26
25
  )
27
26
  from pydantic import BaseModel
@@ -452,6 +451,25 @@ async def test_a_poll_that_gives_up_while_it_is_set_up_stops_its_setup_and_holds
452
451
  assert "result" in await call(http, port, "events/poll", changed_on("b2"))
453
452
 
454
453
 
454
+ @asynchronous
455
+ async def test_a_signed_in_caller_is_held_to_its_limit_and_callers_without_an_identity_only_to_the_limit_in_all(
456
+ monkeypatch,
457
+ ):
458
+ monkeypatch.setattr(_server, "_MAX_SUBSCRIPTIONS_PER_CALLER", 1)
459
+ async with (
460
+ served(declare()[0]) as port,
461
+ httpx2.AsyncClient(headers={"x-holon-context": signed_in("ann")}) as ann,
462
+ httpx2.AsyncClient() as anonymous,
463
+ ):
464
+ assert "result" in await call(ann, port, "events/poll", changed_on("b1"))
465
+ refused = await call(ann, port, "events/poll", changed_on("b2"))
466
+ assert refused["error"]["data"] == {"limit": "subscriptionsPerCaller", "max": 1}
467
+ for board in ("b1", "b2"):
468
+ assert "result" in await call(
469
+ anonymous, port, "events/poll", changed_on(board)
470
+ )
471
+
472
+
455
473
  @asynchronous
456
474
  async def test_a_subscription_can_be_retried_after_setup_times_out(
457
475
  monkeypatch,
@@ -471,18 +489,9 @@ async def test_a_subscription_can_be_retried_after_setup_times_out(
471
489
 
472
490
 
473
491
  @asynchronous
474
- async def test_a_subscription_from_the_cursor_read_with_a_snapshot_hears_every_change_after_it():
475
- (events, changed), said = declare(), []
476
-
477
- def tell(text):
478
- said.append(text)
479
- say(changed, "b1", text)
480
-
481
- async def snapshot(context, params):
482
- state = {"said": list(said), "cursor": changed.cursor()}
483
- return CallToolResult(content=[], structured_content=state)
484
-
485
- server = Server("boards", on_call_tool=snapshot)
492
+ async def test_a_low_level_server_serves_the_events():
493
+ events, changed = declare()
494
+ server = Server("boards")
486
495
  events.serve(server)
487
496
  manager = StreamableHTTPSessionManager(server, stateless=True)
488
497
  port, stop = await serve(
@@ -491,15 +500,9 @@ async def test_a_subscription_from_the_cursor_read_with_a_snapshot_hears_every_c
491
500
  lifespan=lambda app: manager.run(),
492
501
  )
493
502
  )
494
- tell("in the snapshot")
495
- binding = {"endpoint": f"http://127.0.0.1:{port}/mcp/"}
496
- boards = Apps(IDENTITY, {}, {"boards": binding}).boards
497
- state = (await boards.call_tool("snapshot")).structured_content
498
- tell("after the snapshot")
499
- async with client(port).subscribe(
500
- "board.changed", {"board": "b1"}, cursor=state["cursor"]
503
+ async with client(port, path="/mcp/").subscribe(
504
+ "board.changed", {"board": "b1"}
501
505
  ) as changes:
502
- assert changes.delivery == "push"
503
- tell("once subscribed")
504
- assert await take(changes, 2) == ["after the snapshot", "once subscribed"]
506
+ say(changed, "b1", "hello")
507
+ assert await take(changes, 1) == ["hello"]
505
508
  await stop()
@@ -58,8 +58,10 @@ def test_clients_preserve_mcp_results_and_validate(monkeypatch):
58
58
  return InputRequiredResult(
59
59
  request_state="opaque", _meta={"preserved": True}
60
60
  )
61
+ if id == "empty":
62
+ return CallToolResult(content=[])
61
63
  return CallToolResult(
62
- content=[TextContent(type="text", text="Order")],
64
+ content=[TextContent(type="text", text='{"order": "unchecked"}')],
63
65
  structured_content={"total": "bad" if id == "bad" else limit},
64
66
  )
65
67
 
@@ -147,7 +149,16 @@ def test_clients_preserve_mcp_results_and_validate(monkeypatch):
147
149
  k: v for k, v in CONTRACT["tools"][0].items() if k != "outputSchema"
148
150
  }
149
151
  plain = Apps(identity, {"orders": {"tools": [tool]}}, bindings)
150
- assert (await plain.orders.tools.read(id="good")).content[0].text == "Order"
152
+ assert (await plain.orders.tools.read(id="good")).content[0].text == (
153
+ '{"order": "unchecked"}'
154
+ )
155
+ parsed = Apps(
156
+ identity, {"orders": {"tools": [tool], "responses": ["read"]}}, bindings
157
+ )
158
+ assert await parsed.orders.tools.read(id="good") == {"order": "unchecked"}
159
+ assert await parsed.orders.tools.read(id="empty") is None
160
+ with pytest.raises(ToolCallError):
161
+ await parsed.orders.tools.read(id="error")
151
162
  with pytest.raises(RuntimeError):
152
163
  await Apps(undeclared, {}).missing.call_tool("read")
153
164
  script = {**identity, "requires": {}}
File without changes
File without changes