holon-sh 0.0.1.dev7__tar.gz → 0.0.1.dev9__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 (25) hide show
  1. {holon_sh-0.0.1.dev7 → holon_sh-0.0.1.dev9}/PKG-INFO +1 -1
  2. {holon_sh-0.0.1.dev7 → holon_sh-0.0.1.dev9}/holon/binding.py +6 -1
  3. {holon_sh-0.0.1.dev7 → holon_sh-0.0.1.dev9}/holon/client.py +116 -57
  4. holon_sh-0.0.1.dev9/holon/ext/__init__.py +1 -0
  5. holon_sh-0.0.1.dev9/holon/ext/events.py +1627 -0
  6. holon_sh-0.0.1.dev9/holon/ext/files/__init__.py +38 -0
  7. holon_sh-0.0.1.dev9/holon/ext/files/_client.py +581 -0
  8. holon_sh-0.0.1.dev9/holon/ext/files/_server.py +630 -0
  9. holon_sh-0.0.1.dev9/holon/ext/files/_wire.py +348 -0
  10. {holon_sh-0.0.1.dev7 → holon_sh-0.0.1.dev9}/pyproject.toml +1 -1
  11. holon_sh-0.0.1.dev9/tests/test_events.py +581 -0
  12. holon_sh-0.0.1.dev9/tests/test_files.py +491 -0
  13. {holon_sh-0.0.1.dev7 → holon_sh-0.0.1.dev9}/.gitignore +0 -0
  14. {holon_sh-0.0.1.dev7 → holon_sh-0.0.1.dev9}/LICENSE +0 -0
  15. {holon_sh-0.0.1.dev7 → holon_sh-0.0.1.dev9}/README.md +0 -0
  16. {holon_sh-0.0.1.dev7 → holon_sh-0.0.1.dev9}/holon/context.py +0 -0
  17. {holon_sh-0.0.1.dev7 → holon_sh-0.0.1.dev9}/holon/py.typed +0 -0
  18. {holon_sh-0.0.1.dev7 → holon_sh-0.0.1.dev9}/scripts/verify_distribution.py +0 -0
  19. {holon_sh-0.0.1.dev7 → holon_sh-0.0.1.dev9}/tests/fixtures/caller/holon/apps/__init__.py +0 -0
  20. {holon_sh-0.0.1.dev7 → holon_sh-0.0.1.dev9}/tests/fixtures/caller/requirements.txt +0 -0
  21. {holon_sh-0.0.1.dev7 → holon_sh-0.0.1.dev9}/tests/fixtures/caller/server.json +0 -0
  22. {holon_sh-0.0.1.dev7 → holon_sh-0.0.1.dev9}/tests/test_context.py +0 -0
  23. {holon_sh-0.0.1.dev7 → holon_sh-0.0.1.dev9}/tests/test_elicit.py +0 -0
  24. {holon_sh-0.0.1.dev7 → holon_sh-0.0.1.dev9}/tests/test_package.py +0 -0
  25. {holon_sh-0.0.1.dev7 → holon_sh-0.0.1.dev9}/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.dev7
3
+ Version: 0.0.1.dev9
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,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,8 @@ class _App:
168
191
  if not name.startswith("_")
169
192
  }
170
193
  )
194
+ # Draft extensions, whose interfaces may change with the drafts.
195
+ self.ext = SimpleNamespace(events=AppEvents(self, contract))
171
196
 
172
197
  async def call_tool(
173
198
  self,
@@ -183,7 +208,8 @@ class _App:
183
208
  options: Request timeout in seconds, input responses, continuation
184
209
  state, metadata, and ``elicit`` to answer the server's questions in
185
210
  place. Passed positionally, separate from tool input.
186
- **arguments: Tool input, which the server validates.
211
+ **arguments: Tool input, which the server validates. Pass a
212
+ ``holon.ext.files.File`` where the tool takes a file.
187
213
 
188
214
  Returns:
189
215
  A complete result, or an input-required result for a question left
@@ -193,6 +219,10 @@ class _App:
193
219
  Raises:
194
220
  ValueError: Unknown tool, invalid output, or undeclared dependency.
195
221
  RuntimeError: Endpoint resolution failed.
222
+ holon.ext.files.FileTransferError: A file was not sent; the tool did
223
+ not run.
224
+ holon.ext.files.OutcomeUnknownError: The call failed after its files
225
+ were sent; the tool may have run.
196
226
 
197
227
  Transport and protocol exceptions propagate. Each call closes its HTTP
198
228
  client and MCP session, including when an exception occurs.
@@ -203,47 +233,23 @@ class _App:
203
233
  definition = self._definitions.get(name)
204
234
  if definition is None:
205
235
  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
236
  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
237
+ transfers = Transfers(
238
+ f"{self._name}.{name}",
239
+ self._binding.get("file_origins") if self._binding else None,
240
+ )
241
+ async with self._session(options.get("timeout"), transfers=transfers) as client:
242
+ try:
243
+ if holds_file(arguments):
244
+ schema = definition.get("inputSchema") if definition else None
245
+ arguments = await transfers.prepare(client, name, schema, arguments)
246
+ result = await _send(client, name, arguments, options, transfers)
247
+ except Exception as error: # noqa: BLE001
248
+ failure = error
245
249
  if failure is not None:
246
250
  raise failure
251
+ if isinstance(result, CallToolResult):
252
+ remember(result, transfers)
247
253
  if (
248
254
  definition is not None
249
255
  and isinstance(result, CallToolResult)
@@ -258,6 +264,59 @@ class _App:
258
264
  )
259
265
  return result
260
266
 
267
+ def _connection(
268
+ self, timeout: float | None
269
+ ) -> tuple[str, Callable[[], httpx2.AsyncClient]]:
270
+ http_client = partial(
271
+ httpx2.AsyncClient,
272
+ trust_env=False,
273
+ timeout=httpx2.Timeout(timeout, read=None),
274
+ )
275
+ if self._binding is not None:
276
+ return self._binding["endpoint"], self._binding.get(
277
+ "http_client", http_client
278
+ )
279
+ if self._name not in self._identity["requires"]:
280
+ raise ValueError(
281
+ f"Dependency {self._name} is not declared by this application."
282
+ )
283
+ prefix = self._name.upper().replace("-", "_") + "_MCP_"
284
+ endpoint = os.environ.get(prefix + "URL")
285
+ if not endpoint:
286
+ raise RuntimeError(
287
+ f"Dependency {self._name} is unavailable ({prefix}URL). Set the endpoint or supply a binding."
288
+ )
289
+ token = os.environ.get(prefix + "TOKEN")
290
+ headers = {"Authorization": f"Bearer {token}"} if token else None
291
+ return endpoint, partial(http_client, headers=headers)
292
+
293
+ @asynccontextmanager
294
+ async def _session(
295
+ self,
296
+ timeout: float | None,
297
+ wrap: Callable[[Transport], Transport] | None = None,
298
+ transfers: Transfers | None = None,
299
+ ) -> AsyncIterator[Client]:
300
+ endpoint, http_client = self._connection(timeout)
301
+ async with http_client() as http:
302
+ if transfers is not None:
303
+ transfers.bind(endpoint, http_client, http)
304
+ transport: Transport = streamable_http_client(
305
+ endpoint, http_client=http, max_sse_event_size=None
306
+ )
307
+ if wrap is not None:
308
+ transport = wrap(transport)
309
+ async with Client(
310
+ transport,
311
+ client_info=Implementation(
312
+ name=self._identity["name"], version=self._identity["version"]
313
+ ),
314
+ mode=_VERSION,
315
+ elicitation_callback=_declare_elicitation,
316
+ extensions=[FILES],
317
+ ) as client:
318
+ yield client
319
+
261
320
  def _validate(
262
321
  self, name: str, schema: dict[str, Any], value: Any, label: str
263
322
  ) -> None:
@@ -0,0 +1 @@
1
+ """Draft extensions of MCP. Their interfaces follow the drafts, so they may change in any release."""