holon-sh 0.0.1.dev6__tar.gz → 0.0.1.dev8__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 (28) hide show
  1. holon_sh-0.0.1.dev8/PKG-INFO +84 -0
  2. holon_sh-0.0.1.dev8/README.md +71 -0
  3. {holon_sh-0.0.1.dev6 → holon_sh-0.0.1.dev8}/holon/binding.py +6 -1
  4. {holon_sh-0.0.1.dev6 → holon_sh-0.0.1.dev8}/holon/client.py +115 -57
  5. holon_sh-0.0.1.dev8/holon/ext/__init__.py +1 -0
  6. holon_sh-0.0.1.dev8/holon/ext/events.py +1631 -0
  7. holon_sh-0.0.1.dev8/holon/ext/files/__init__.py +38 -0
  8. holon_sh-0.0.1.dev8/holon/ext/files/_client.py +581 -0
  9. holon_sh-0.0.1.dev8/holon/ext/files/_server.py +630 -0
  10. holon_sh-0.0.1.dev8/holon/ext/files/_wire.py +348 -0
  11. {holon_sh-0.0.1.dev6 → holon_sh-0.0.1.dev8}/pyproject.toml +1 -1
  12. holon_sh-0.0.1.dev8/tests/test_events.py +550 -0
  13. holon_sh-0.0.1.dev8/tests/test_files.py +491 -0
  14. {holon_sh-0.0.1.dev6 → holon_sh-0.0.1.dev8}/tests/test_package.py +8 -23
  15. holon_sh-0.0.1.dev6/PKG-INFO +0 -122
  16. holon_sh-0.0.1.dev6/README.md +0 -109
  17. holon_sh-0.0.1.dev6/holon/apps/__init__.py +0 -19
  18. {holon_sh-0.0.1.dev6 → holon_sh-0.0.1.dev8}/.gitignore +0 -0
  19. {holon_sh-0.0.1.dev6 → holon_sh-0.0.1.dev8}/LICENSE +0 -0
  20. {holon_sh-0.0.1.dev6 → holon_sh-0.0.1.dev8}/holon/context.py +0 -0
  21. {holon_sh-0.0.1.dev6 → holon_sh-0.0.1.dev8}/holon/py.typed +0 -0
  22. {holon_sh-0.0.1.dev6 → holon_sh-0.0.1.dev8}/scripts/verify_distribution.py +0 -0
  23. {holon_sh-0.0.1.dev6 → holon_sh-0.0.1.dev8}/tests/fixtures/caller/holon/apps/__init__.py +0 -0
  24. {holon_sh-0.0.1.dev6 → holon_sh-0.0.1.dev8}/tests/fixtures/caller/requirements.txt +0 -0
  25. {holon_sh-0.0.1.dev6 → holon_sh-0.0.1.dev8}/tests/fixtures/caller/server.json +0 -0
  26. {holon_sh-0.0.1.dev6 → holon_sh-0.0.1.dev8}/tests/test_context.py +0 -0
  27. {holon_sh-0.0.1.dev6 → holon_sh-0.0.1.dev8}/tests/test_elicit.py +0 -0
  28. {holon_sh-0.0.1.dev6 → holon_sh-0.0.1.dev8}/tests/test_runtime.py +0 -0
@@ -0,0 +1,84 @@
1
+ Metadata-Version: 2.5
2
+ Name: holon-sh
3
+ Version: 0.0.1.dev8
4
+ Summary: Typed MCP clients and the caller of an MCP request
5
+ Project-URL: Repository, https://github.com/holon-sh/sdk-py
6
+ License-Expression: Apache-2.0
7
+ License-File: LICENSE
8
+ Requires-Python: >=3.11
9
+ Requires-Dist: httpx2<3,>=2.10
10
+ Requires-Dist: jsonschema<5,>=4.26
11
+ Requires-Dist: mcp<3,>=2.3
12
+ Description-Content-Type: text/markdown
13
+
14
+ # Holon Python SDK
15
+
16
+ [![CI](https://github.com/holon-sh/sdk-py/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/holon-sh/sdk-py/actions/workflows/ci.yml)
17
+ [![Docs](https://img.shields.io/badge/docs-holon--labs.dev-blue)](https://holon-labs.dev/docs/)
18
+ [![PyPI](https://img.shields.io/pypi/v/holon-sh)](https://pypi.org/project/holon-sh/)
19
+ [![Python](https://img.shields.io/badge/Python-3.11%2B-3776AB?logo=python&logoColor=white)](https://www.python.org/downloads/)
20
+ [![Apache 2.0 License](https://img.shields.io/badge/license-Apache--2.0-green)](LICENSE)
21
+ [![Discord](https://img.shields.io/badge/Discord-join-5865F2?logo=discord&logoColor=white)](https://discord.gg/jXExyBdy)
22
+
23
+ This repository contains the Python runtime for [`holon`](https://github.com/holon-sh/cli).
24
+
25
+ ## Install
26
+
27
+ ```sh
28
+ uv add --prerelease allow holon-sh
29
+ uv add --dev holon-types
30
+ ```
31
+
32
+ ## Create an app
33
+
34
+ ```sh
35
+ uvx create-holon-app foo
36
+ ```
37
+
38
+ ## Invoking MCP Servers
39
+
40
+ Declare dependencies under `sh.holon.requires` in a [`server.json`](https://modelcontextprotocol.io/registry/quickstart#step-4-create-server-json) beside the server, here the public [Hugging Face](https://huggingface.co/docs/hub/en/hf-mcp-server) MCP server:
41
+
42
+ ```json
43
+ {
44
+ "name": "com.example/foo",
45
+ "version": "0.1.0",
46
+ "description": "Example Foo",
47
+ "_meta": {
48
+ "io.modelcontextprotocol.registry/publisher-provided": {
49
+ "sh.holon": {
50
+ "requires": {
51
+ "huggingface": { "url": "https://huggingface.co/mcp" }
52
+ }
53
+ }
54
+ }
55
+ }
56
+ }
57
+ ```
58
+
59
+ ### Type-checking MCP invocations
60
+
61
+ ```sh
62
+ uv run holon types check
63
+ ```
64
+
65
+ A wrong tool name or argument is a type error:
66
+
67
+ ```python
68
+ from holon.apps import apps
69
+
70
+ await apps.huggingface.tools.hub_repo_search(query="llama")
71
+
72
+ await apps.huggingface.tools.hub_repo_search(limit="3")
73
+ # error: Argument "limit" to "hub_repo_search" of "HuggingfaceTools" has incompatible type "str"; expected "float" [arg-type]
74
+
75
+ await apps.huggingface.tools.hub_repo_details()
76
+ # error: Missing named argument "repo_ids" for "hub_repo_details" of "HuggingfaceTools" [call-arg]
77
+
78
+ await apps.huggingface.tools.hub_search(query="llama")
79
+ # error: "HuggingfaceTools" has no attribute "hub_search"; maybe "hub_repo_search"? [attr-defined]
80
+ ```
81
+
82
+ ## Community
83
+
84
+ Ask questions and share what you're building on the [Holon Discord](https://discord.gg/jXExyBdy).
@@ -0,0 +1,71 @@
1
+ # Holon Python SDK
2
+
3
+ [![CI](https://github.com/holon-sh/sdk-py/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/holon-sh/sdk-py/actions/workflows/ci.yml)
4
+ [![Docs](https://img.shields.io/badge/docs-holon--labs.dev-blue)](https://holon-labs.dev/docs/)
5
+ [![PyPI](https://img.shields.io/pypi/v/holon-sh)](https://pypi.org/project/holon-sh/)
6
+ [![Python](https://img.shields.io/badge/Python-3.11%2B-3776AB?logo=python&logoColor=white)](https://www.python.org/downloads/)
7
+ [![Apache 2.0 License](https://img.shields.io/badge/license-Apache--2.0-green)](LICENSE)
8
+ [![Discord](https://img.shields.io/badge/Discord-join-5865F2?logo=discord&logoColor=white)](https://discord.gg/jXExyBdy)
9
+
10
+ This repository contains the Python runtime for [`holon`](https://github.com/holon-sh/cli).
11
+
12
+ ## Install
13
+
14
+ ```sh
15
+ uv add --prerelease allow holon-sh
16
+ uv add --dev holon-types
17
+ ```
18
+
19
+ ## Create an app
20
+
21
+ ```sh
22
+ uvx create-holon-app foo
23
+ ```
24
+
25
+ ## Invoking MCP Servers
26
+
27
+ Declare dependencies under `sh.holon.requires` in a [`server.json`](https://modelcontextprotocol.io/registry/quickstart#step-4-create-server-json) beside the server, here the public [Hugging Face](https://huggingface.co/docs/hub/en/hf-mcp-server) MCP server:
28
+
29
+ ```json
30
+ {
31
+ "name": "com.example/foo",
32
+ "version": "0.1.0",
33
+ "description": "Example Foo",
34
+ "_meta": {
35
+ "io.modelcontextprotocol.registry/publisher-provided": {
36
+ "sh.holon": {
37
+ "requires": {
38
+ "huggingface": { "url": "https://huggingface.co/mcp" }
39
+ }
40
+ }
41
+ }
42
+ }
43
+ }
44
+ ```
45
+
46
+ ### Type-checking MCP invocations
47
+
48
+ ```sh
49
+ uv run holon types check
50
+ ```
51
+
52
+ A wrong tool name or argument is a type error:
53
+
54
+ ```python
55
+ from holon.apps import apps
56
+
57
+ await apps.huggingface.tools.hub_repo_search(query="llama")
58
+
59
+ await apps.huggingface.tools.hub_repo_search(limit="3")
60
+ # error: Argument "limit" to "hub_repo_search" of "HuggingfaceTools" has incompatible type "str"; expected "float" [arg-type]
61
+
62
+ await apps.huggingface.tools.hub_repo_details()
63
+ # error: Missing named argument "repo_ids" for "hub_repo_details" of "HuggingfaceTools" [call-arg]
64
+
65
+ await apps.huggingface.tools.hub_search(query="llama")
66
+ # error: "HuggingfaceTools" has no attribute "hub_search"; maybe "hub_repo_search"? [attr-defined]
67
+ ```
68
+
69
+ ## Community
70
+
71
+ Ask questions and share what you're building on the [Holon Discord](https://discord.gg/jXExyBdy).
@@ -1,6 +1,6 @@
1
1
  from __future__ import annotations
2
2
 
3
- from collections.abc import Callable
3
+ from collections.abc import Callable, Sequence
4
4
  from typing import NotRequired, TypedDict
5
5
 
6
6
  import httpx2
@@ -14,7 +14,12 @@ class Binding(TypedDict):
14
14
  http_client: Factory returning a fresh ``httpx2.AsyncClient`` for each
15
15
  call. Configure authentication headers or a custom transport here.
16
16
  The SDK closes the returned client when the call finishes.
17
+ file_origins: Origins (``https://host[:port]``) the server may send
18
+ file transfers to. When set, no other origin is used, and a listed
19
+ origin may also be plain-http loopback or a private address. When
20
+ unset, any https origin on a public address.
17
21
  """
18
22
 
19
23
  endpoint: str
20
24
  http_client: NotRequired[Callable[[], httpx2.AsyncClient]]
25
+ file_origins: NotRequired[Sequence[str]]
@@ -1,7 +1,8 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  import os
4
- from collections.abc import Awaitable, Callable, Mapping
4
+ from collections.abc import AsyncIterator, Awaitable, Callable, Mapping
5
+ from contextlib import asynccontextmanager
5
6
  from functools import partial
6
7
  from types import SimpleNamespace
7
8
  from typing import Any, Generic, Literal, Protocol, TypeAlias, TypedDict, TypeVar
@@ -9,6 +10,7 @@ from typing import Any, Generic, Literal, Protocol, TypeAlias, TypedDict, TypeVa
9
10
  import httpx2
10
11
  import jsonschema
11
12
  from mcp import Client
13
+ from mcp.client import Transport
12
14
  from mcp.client.session import ClientRequestContext
13
15
  from mcp.client.streamable_http import streamable_http_client
14
16
  from mcp.types import (
@@ -25,10 +27,18 @@ from mcp.types import (
25
27
  RequestParamsMeta,
26
28
  TextContent,
27
29
  )
28
- from pydantic import TypeAdapter
29
30
  from referencing import Registry
30
31
 
31
32
  from holon.binding import Binding
33
+ from holon.ext.events import AppEvents
34
+ from holon.ext.files._client import (
35
+ FILES,
36
+ OutcomeUnknownError,
37
+ Transfers,
38
+ holds_file,
39
+ remember,
40
+ )
41
+ from holon.ext.files._wire import CALL_RESULT, UploadRequiredResult
32
42
 
33
43
  __all__ = [
34
44
  "Apps",
@@ -40,6 +50,7 @@ __all__ = [
40
50
  ]
41
51
 
42
52
  Output = TypeVar("Output")
53
+ _VERSION = "2026-07-28"
43
54
 
44
55
 
45
56
  class CompleteResult(Protocol, Generic[Output]):
@@ -64,8 +75,6 @@ class ErrorResult(Protocol):
64
75
 
65
76
  ToolResult: TypeAlias = CompleteResult[Output] | ErrorResult | InputRequiredResult
66
77
 
67
- _result = TypeAdapter(CallToolResult | InputRequiredResult)
68
-
69
78
 
70
79
  class CallOptions(TypedDict, total=False):
71
80
  """Request controls, passed positionally to keep tool keywords available."""
@@ -114,25 +123,39 @@ async def _declare_elicitation(
114
123
 
115
124
 
116
125
  async def _send(
117
- client: Client, name: str, arguments: dict[str, Any], options: CallOptions
126
+ client: Client,
127
+ name: str,
128
+ arguments: dict[str, Any],
129
+ options: CallOptions,
130
+ transfers: Transfers,
118
131
  ) -> CallToolResult | InputRequiredResult:
119
132
  elicit = options.get("elicit")
120
133
  responses, state = options.get("input_responses"), options.get("request_state")
121
134
  answered = 0
122
135
  while True:
123
- result = await client.session.send_request(
124
- CallToolRequest(
125
- params=CallToolRequestParams(
126
- name=name,
127
- arguments=arguments,
128
- input_responses=responses,
129
- request_state=state,
130
- _meta=options.get("meta"),
131
- )
132
- ),
133
- _result,
134
- request_read_timeout_seconds=options.get("timeout"),
135
- )
136
+ try:
137
+ result = await client.session.send_request(
138
+ CallToolRequest(
139
+ params=CallToolRequestParams(
140
+ name=name,
141
+ arguments=arguments,
142
+ input_responses=responses,
143
+ request_state=state,
144
+ _meta=options.get("meta"),
145
+ )
146
+ ),
147
+ CALL_RESULT,
148
+ request_read_timeout_seconds=options.get("timeout"),
149
+ )
150
+ except Exception as error:
151
+ if transfers.uploaded:
152
+ raise OutcomeUnknownError(
153
+ f"{transfers.label}: the outcome is unknown; the call failed after its files were sent"
154
+ ) from error
155
+ raise
156
+ if isinstance(result, UploadRequiredResult):
157
+ responses, state = None, await transfers.send(result)
158
+ continue
136
159
  if not (elicit and answered < 10 and isinstance(result, InputRequiredResult)):
137
160
  return result
138
161
  answered += 1
@@ -168,6 +191,7 @@ class _App:
168
191
  if not name.startswith("_")
169
192
  }
170
193
  )
194
+ self.events = AppEvents(self, contract)
171
195
 
172
196
  async def call_tool(
173
197
  self,
@@ -183,7 +207,8 @@ class _App:
183
207
  options: Request timeout in seconds, input responses, continuation
184
208
  state, metadata, and ``elicit`` to answer the server's questions in
185
209
  place. Passed positionally, separate from tool input.
186
- **arguments: Tool input, which the server validates.
210
+ **arguments: Tool input, which the server validates. Pass a
211
+ ``holon.ext.files.File`` where the tool takes a file.
187
212
 
188
213
  Returns:
189
214
  A complete result, or an input-required result for a question left
@@ -193,6 +218,10 @@ class _App:
193
218
  Raises:
194
219
  ValueError: Unknown tool, invalid output, or undeclared dependency.
195
220
  RuntimeError: Endpoint resolution failed.
221
+ holon.ext.files.FileTransferError: A file was not sent; the tool did
222
+ not run.
223
+ holon.ext.files.OutcomeUnknownError: The call failed after its files
224
+ were sent; the tool may have run.
196
225
 
197
226
  Transport and protocol exceptions propagate. Each call closes its HTTP
198
227
  client and MCP session, including when an exception occurs.
@@ -203,47 +232,23 @@ class _App:
203
232
  definition = self._definitions.get(name)
204
233
  if definition is None:
205
234
  raise ValueError(f"Unknown tool {self._name}.{name}.")
206
- timeout = options.get("timeout")
207
- http_client = partial(
208
- httpx2.AsyncClient,
209
- trust_env=False,
210
- timeout=httpx2.Timeout(timeout, read=None),
211
- )
212
- binding = self._binding
213
- if binding is None:
214
- if self._name not in self._identity["requires"]:
215
- raise ValueError(
216
- f"Dependency {self._name} is not declared by this application."
217
- )
218
- prefix = self._name.upper().replace("-", "_") + "_MCP_"
219
- endpoint = os.environ.get(prefix + "URL")
220
- if not endpoint:
221
- raise RuntimeError(
222
- f"Dependency {self._name} is unavailable ({prefix}URL). Set the endpoint or supply a binding."
223
- )
224
- token = os.environ.get(prefix + "TOKEN")
225
- headers = {"Authorization": f"Bearer {token}"} if token else None
226
- binding = {
227
- "endpoint": endpoint,
228
- "http_client": partial(http_client, headers=headers),
229
- }
230
235
  failure: Exception | None = None
231
- async with binding.get("http_client", http_client)() as http:
232
- transport = streamable_http_client(binding["endpoint"], http_client=http)
233
- async with Client(
234
- transport,
235
- client_info=Implementation(
236
- name=self._identity["name"], version=self._identity["version"]
237
- ),
238
- mode="2026-07-28",
239
- elicitation_callback=_declare_elicitation,
240
- ) as client:
241
- try:
242
- result = await _send(client, name, arguments, options)
243
- except Exception as error: # noqa: BLE001
244
- failure = error
236
+ transfers = Transfers(
237
+ f"{self._name}.{name}",
238
+ self._binding.get("file_origins") if self._binding else None,
239
+ )
240
+ async with self._session(options.get("timeout"), transfers=transfers) as client:
241
+ try:
242
+ if holds_file(arguments):
243
+ schema = definition.get("inputSchema") if definition else None
244
+ arguments = await transfers.prepare(client, name, schema, arguments)
245
+ result = await _send(client, name, arguments, options, transfers)
246
+ except Exception as error: # noqa: BLE001
247
+ failure = error
245
248
  if failure is not None:
246
249
  raise failure
250
+ if isinstance(result, CallToolResult):
251
+ remember(result, transfers)
247
252
  if (
248
253
  definition is not None
249
254
  and isinstance(result, CallToolResult)
@@ -258,6 +263,59 @@ class _App:
258
263
  )
259
264
  return result
260
265
 
266
+ def _connection(
267
+ self, timeout: float | None
268
+ ) -> tuple[str, Callable[[], httpx2.AsyncClient]]:
269
+ http_client = partial(
270
+ httpx2.AsyncClient,
271
+ trust_env=False,
272
+ timeout=httpx2.Timeout(timeout, read=None),
273
+ )
274
+ if self._binding is not None:
275
+ return self._binding["endpoint"], self._binding.get(
276
+ "http_client", http_client
277
+ )
278
+ if self._name not in self._identity["requires"]:
279
+ raise ValueError(
280
+ f"Dependency {self._name} is not declared by this application."
281
+ )
282
+ prefix = self._name.upper().replace("-", "_") + "_MCP_"
283
+ endpoint = os.environ.get(prefix + "URL")
284
+ if not endpoint:
285
+ raise RuntimeError(
286
+ f"Dependency {self._name} is unavailable ({prefix}URL). Set the endpoint or supply a binding."
287
+ )
288
+ token = os.environ.get(prefix + "TOKEN")
289
+ headers = {"Authorization": f"Bearer {token}"} if token else None
290
+ return endpoint, partial(http_client, headers=headers)
291
+
292
+ @asynccontextmanager
293
+ async def _session(
294
+ self,
295
+ timeout: float | None,
296
+ wrap: Callable[[Transport], Transport] | None = None,
297
+ transfers: Transfers | None = None,
298
+ ) -> AsyncIterator[Client]:
299
+ endpoint, http_client = self._connection(timeout)
300
+ async with http_client() as http:
301
+ if transfers is not None:
302
+ transfers.bind(endpoint, http_client, http)
303
+ transport: Transport = streamable_http_client(
304
+ endpoint, http_client=http, max_sse_event_size=None
305
+ )
306
+ if wrap is not None:
307
+ transport = wrap(transport)
308
+ async with Client(
309
+ transport,
310
+ client_info=Implementation(
311
+ name=self._identity["name"], version=self._identity["version"]
312
+ ),
313
+ mode=_VERSION,
314
+ elicitation_callback=_declare_elicitation,
315
+ extensions=[FILES],
316
+ ) as client:
317
+ yield client
318
+
261
319
  def _validate(
262
320
  self, name: str, schema: dict[str, Any], value: Any, label: str
263
321
  ) -> None:
@@ -0,0 +1 @@
1
+ """Draft extensions of MCP. Their interfaces follow the drafts, so they may change in any release."""