holon-sh 0.0.1.dev5__tar.gz → 0.0.1.dev6__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 (24) hide show
  1. {holon_sh-0.0.1.dev5 → holon_sh-0.0.1.dev6}/PKG-INFO +16 -15
  2. {holon_sh-0.0.1.dev5 → holon_sh-0.0.1.dev6}/README.md +14 -13
  3. holon_sh-0.0.1.dev6/holon/apps/__init__.py +19 -0
  4. holon_sh-0.0.1.dev6/holon/binding.py +20 -0
  5. {holon_sh-0.0.1.dev5 → holon_sh-0.0.1.dev6}/holon/client.py +48 -45
  6. holon_sh-0.0.1.dev6/holon/context.py +87 -0
  7. {holon_sh-0.0.1.dev5 → holon_sh-0.0.1.dev6}/pyproject.toml +2 -2
  8. holon_sh-0.0.1.dev6/tests/test_context.py +53 -0
  9. {holon_sh-0.0.1.dev5 → holon_sh-0.0.1.dev6}/tests/test_elicit.py +4 -34
  10. {holon_sh-0.0.1.dev5 → holon_sh-0.0.1.dev6}/tests/test_package.py +23 -8
  11. {holon_sh-0.0.1.dev5 → holon_sh-0.0.1.dev6}/tests/test_runtime.py +42 -65
  12. holon_sh-0.0.1.dev5/holon/binding.py +0 -47
  13. holon_sh-0.0.1.dev5/holon/view.py +0 -55
  14. holon_sh-0.0.1.dev5/scripts/fixtures.sh +0 -7
  15. holon_sh-0.0.1.dev5/tests/fixtures/orders/server.json +0 -5
  16. holon_sh-0.0.1.dev5/tests/fixtures/orders/server.py +0 -57
  17. holon_sh-0.0.1.dev5/tests/test_view.py +0 -47
  18. {holon_sh-0.0.1.dev5 → holon_sh-0.0.1.dev6}/.gitignore +0 -0
  19. {holon_sh-0.0.1.dev5 → holon_sh-0.0.1.dev6}/LICENSE +0 -0
  20. {holon_sh-0.0.1.dev5 → holon_sh-0.0.1.dev6}/holon/py.typed +0 -0
  21. {holon_sh-0.0.1.dev5 → holon_sh-0.0.1.dev6}/scripts/verify_distribution.py +0 -0
  22. {holon_sh-0.0.1.dev5 → holon_sh-0.0.1.dev6}/tests/fixtures/caller/holon/apps/__init__.py +0 -0
  23. {holon_sh-0.0.1.dev5 → holon_sh-0.0.1.dev6}/tests/fixtures/caller/requirements.txt +0 -0
  24. {holon_sh-0.0.1.dev5 → holon_sh-0.0.1.dev6}/tests/fixtures/caller/server.json +0 -0
@@ -1,7 +1,7 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: holon-sh
3
- Version: 0.0.1.dev5
4
- Summary: Typed MCP clients, bindings, and app views
3
+ Version: 0.0.1.dev6
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
7
7
  License-File: LICENSE
@@ -45,12 +45,13 @@ uv run holon types check
45
45
  ```python
46
46
  from holon.apps import apps
47
47
 
48
+
48
49
  async def greet(name: str) -> str:
49
50
  greeting = await apps.bar.tools.greet({"timeout": 5.0}, name=name)
50
51
  return greeting["result"]
51
52
  ```
52
53
 
53
- Arguments are keywords, validated before sending; the result is validated against the output schema and returned.
54
+ Arguments are keywords; the result is validated against the output schema and returned.
54
55
 
55
56
  </details>
56
57
 
@@ -76,11 +77,11 @@ except ToolCallError as error:
76
77
  ```python
77
78
  result = await apps.bar.call_tool("greet", name="world")
78
79
  if result.result_type == "input_required":
79
- ... # call again with input_responses and request_state
80
+ ... # call again with input_responses and request_state
80
81
  elif result.is_error:
81
- ... # inspect result.content
82
+ ... # inspect result.content
82
83
  else:
83
- result.structured_content # typed as Outputs.bar.greet
84
+ result.structured_content # typed as Outputs.bar.greet
84
85
  ```
85
86
 
86
87
  The options dict also accepts `input_responses`, `request_state` and `meta`.
@@ -95,9 +96,11 @@ A tool can stop and ask for input through an [MCP elicitation](https://modelcont
95
96
  ```python
96
97
  from mcp.types import ElicitResult
97
98
 
99
+
98
100
  async def elicit(params):
99
101
  return ElicitResult(action="accept", content=await ask(params.message))
100
102
 
103
+
101
104
  greeting = await apps.bar.tools.greet({"elicit": elicit}, name="world")
102
105
  ```
103
106
 
@@ -105,17 +108,15 @@ Without `elicit`, the question arrives on `ToolCallError.result`, or as an `inpu
105
108
 
106
109
  </details>
107
110
 
108
- ## Serve an [MCP App](https://modelcontextprotocol.io/extensions/apps/overview) view
111
+ ## Identify the caller
109
112
 
110
- `holon.view.app_view` registers a built HTML file as an MCP App resource:
113
+ Inside a tool handler, `get_context().principal` is the user Holon admitted for the request, or `None` for anonymous requests:
111
114
 
112
115
  ```python
113
- from holon.view import app_view
116
+ from holon.context import get_context
114
117
 
115
- server.add_resource(app_view(
116
- "ui://foo/index.html", "Foo", "dist/index.html",
117
- connect_domains=["https://bar.example.com"],
118
- ))
118
+ principal = get_context().principal
119
+ if principal is not None:
120
+ principal.issuer, principal.subject, principal.scopes
121
+ principal.claims.get("email") # standard OpenID claims are typed: str | None
119
122
  ```
120
-
121
- The page itself uses [`holon-ui`](https://github.com/holon-sh/sdk-ui).
@@ -32,12 +32,13 @@ uv run holon types check
32
32
  ```python
33
33
  from holon.apps import apps
34
34
 
35
+
35
36
  async def greet(name: str) -> str:
36
37
  greeting = await apps.bar.tools.greet({"timeout": 5.0}, name=name)
37
38
  return greeting["result"]
38
39
  ```
39
40
 
40
- Arguments are keywords, validated before sending; the result is validated against the output schema and returned.
41
+ Arguments are keywords; the result is validated against the output schema and returned.
41
42
 
42
43
  </details>
43
44
 
@@ -63,11 +64,11 @@ except ToolCallError as error:
63
64
  ```python
64
65
  result = await apps.bar.call_tool("greet", name="world")
65
66
  if result.result_type == "input_required":
66
- ... # call again with input_responses and request_state
67
+ ... # call again with input_responses and request_state
67
68
  elif result.is_error:
68
- ... # inspect result.content
69
+ ... # inspect result.content
69
70
  else:
70
- result.structured_content # typed as Outputs.bar.greet
71
+ result.structured_content # typed as Outputs.bar.greet
71
72
  ```
72
73
 
73
74
  The options dict also accepts `input_responses`, `request_state` and `meta`.
@@ -82,9 +83,11 @@ A tool can stop and ask for input through an [MCP elicitation](https://modelcont
82
83
  ```python
83
84
  from mcp.types import ElicitResult
84
85
 
86
+
85
87
  async def elicit(params):
86
88
  return ElicitResult(action="accept", content=await ask(params.message))
87
89
 
90
+
88
91
  greeting = await apps.bar.tools.greet({"elicit": elicit}, name="world")
89
92
  ```
90
93
 
@@ -92,17 +95,15 @@ Without `elicit`, the question arrives on `ToolCallError.result`, or as an `inpu
92
95
 
93
96
  </details>
94
97
 
95
- ## Serve an [MCP App](https://modelcontextprotocol.io/extensions/apps/overview) view
98
+ ## Identify the caller
96
99
 
97
- `holon.view.app_view` registers a built HTML file as an MCP App resource:
100
+ Inside a tool handler, `get_context().principal` is the user Holon admitted for the request, or `None` for anonymous requests:
98
101
 
99
102
  ```python
100
- from holon.view import app_view
103
+ from holon.context import get_context
101
104
 
102
- server.add_resource(app_view(
103
- "ui://foo/index.html", "Foo", "dist/index.html",
104
- connect_domains=["https://bar.example.com"],
105
- ))
105
+ principal = get_context().principal
106
+ if principal is not None:
107
+ principal.issuer, principal.subject, principal.scopes
108
+ principal.claims.get("email") # standard OpenID claims are typed: str | None
106
109
  ```
107
-
108
- The page itself uses [`holon-ui`](https://github.com/holon-sh/sdk-ui).
@@ -0,0 +1,19 @@
1
+ import sys
2
+ from importlib.util import module_from_spec, spec_from_file_location
3
+ from pathlib import Path
4
+
5
+ import holon
6
+
7
+ _here = Path(__file__).resolve().parent
8
+ for _portion in holon.__path__:
9
+ _generated = Path(_portion, "apps")
10
+ if _generated.resolve() != _here and (_generated / "__init__.py").is_file():
11
+ _spec = spec_from_file_location(__name__, _generated / "__init__.py")
12
+ assert _spec and _spec.loader
13
+ sys.modules[__name__] = _module = module_from_spec(_spec)
14
+ _spec.loader.exec_module(_module)
15
+ break
16
+ else:
17
+ raise ImportError(
18
+ "no generated holon.apps on sys.path: run `holon types generate` in the project"
19
+ )
@@ -0,0 +1,20 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Callable
4
+ from typing import NotRequired, TypedDict
5
+
6
+ import httpx2
7
+
8
+
9
+ class Binding(TypedDict):
10
+ """Connection settings for an MCP dependency.
11
+
12
+ Attributes:
13
+ endpoint: Streamable HTTP MCP URL.
14
+ http_client: Factory returning a fresh ``httpx2.AsyncClient`` for each
15
+ call. Configure authentication headers or a custom transport here.
16
+ The SDK closes the returned client when the call finishes.
17
+ """
18
+
19
+ endpoint: str
20
+ http_client: NotRequired[Callable[[], httpx2.AsyncClient]]
@@ -7,7 +7,7 @@ from types import SimpleNamespace
7
7
  from typing import Any, Generic, Literal, Protocol, TypeAlias, TypedDict, TypeVar
8
8
 
9
9
  import httpx2
10
- import jsonschema # type: ignore[import-untyped,unused-ignore]
10
+ import jsonschema
11
11
  from mcp import Client
12
12
  from mcp.client.session import ClientRequestContext
13
13
  from mcp.client.streamable_http import streamable_http_client
@@ -28,9 +28,8 @@ from mcp.types import (
28
28
  from pydantic import TypeAdapter
29
29
  from referencing import Registry
30
30
 
31
- from holon.binding import Binding, resolve_default_binding
31
+ from holon.binding import Binding
32
32
 
33
- # Binding is re-exported for the generated holon.apps module.
34
33
  __all__ = [
35
34
  "Apps",
36
35
  "Binding",
@@ -111,7 +110,6 @@ class ToolCallError(RuntimeError):
111
110
  async def _declare_elicitation(
112
111
  context: ClientRequestContext, params: ElicitRequestParams
113
112
  ) -> ElicitResult:
114
- """Declare that every client can be asked; the MCP client infers it from this."""
115
113
  return ElicitResult(action="decline")
116
114
 
117
115
 
@@ -135,8 +133,6 @@ async def _send(
135
133
  _result,
136
134
  request_read_timeout_seconds=options.get("timeout"),
137
135
  )
138
- # A server may keep asking, so answering stops after ten rounds, the MCP
139
- # clients' own limit, and the last question reaches the caller.
140
136
  if not (elicit and answered < 10 and isinstance(result, InputRequiredResult)):
141
137
  return result
142
138
  answered += 1
@@ -148,18 +144,6 @@ async def _send(
148
144
  state = result.request_state
149
145
 
150
146
 
151
- def validate(schema: dict[str, Any], value: object, label: str) -> None:
152
- try:
153
- jsonschema.validate(
154
- value,
155
- schema,
156
- registry=Registry(),
157
- format_checker=jsonschema.FormatChecker(),
158
- )
159
- except jsonschema.ValidationError as error:
160
- raise ValueError(f"Invalid {label}: {error.message}") from error
161
-
162
-
163
147
  class _App:
164
148
  def __init__(
165
149
  self,
@@ -171,7 +155,7 @@ class _App:
171
155
  self._name = name
172
156
  self._identity = identity
173
157
  self._binding = binding
174
- # None for a dependency without a contract: any tool, unvalidated.
158
+ self._validators: dict[str, Any] = {}
175
159
  self._definitions = (
176
160
  None
177
161
  if contract is None
@@ -199,7 +183,7 @@ class _App:
199
183
  options: Request timeout in seconds, input responses, continuation
200
184
  state, metadata, and ``elicit`` to answer the server's questions in
201
185
  place. Passed positionally, separate from tool input.
202
- **arguments: Tool input, validated against the contract if present.
186
+ **arguments: Tool input, which the server validates.
203
187
 
204
188
  Returns:
205
189
  A complete result, or an input-required result for a question left
@@ -207,7 +191,7 @@ class _App:
207
191
  structured output is contract-validated.
208
192
 
209
193
  Raises:
210
- ValueError: Unknown tool, invalid input/output, or undeclared dependency.
194
+ ValueError: Unknown tool, invalid output, or undeclared dependency.
211
195
  RuntimeError: Endpoint resolution failed.
212
196
 
213
197
  Transport and protocol exceptions propagate. Each call closes its HTTP
@@ -219,28 +203,33 @@ class _App:
219
203
  definition = self._definitions.get(name)
220
204
  if definition is None:
221
205
  raise ValueError(f"Unknown tool {self._name}.{name}.")
222
- validate(
223
- definition["inputSchema"],
224
- arguments,
225
- f"arguments for {self._name}.{name}",
226
- )
227
- binding = self._binding or resolve_default_binding(self._name)
228
- if binding is None and self._name not in self._identity["requires"]:
229
- raise ValueError(
230
- f"Dependency {self._name} is not declared by this application."
231
- )
232
- variable = self._name.upper().replace("-", "_") + "_MCP_URL"
233
- endpoint = binding["endpoint"] if binding else os.environ.get(variable)
234
- if not endpoint:
235
- raise RuntimeError(
236
- f"Dependency {self._name} is unavailable ({variable}). Set the endpoint or supply a binding."
237
- )
238
- http_client = partial(httpx2.AsyncClient, trust_env=False)
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
+ }
239
230
  failure: Exception | None = None
240
- async with (
241
- binding.get("http_client", http_client) if binding else http_client
242
- )() as http:
243
- transport = streamable_http_client(endpoint, http_client=http)
231
+ async with binding.get("http_client", http_client)() as http:
232
+ transport = streamable_http_client(binding["endpoint"], http_client=http)
244
233
  async with Client(
245
234
  transport,
246
235
  client_info=Implementation(
@@ -252,7 +241,6 @@ class _App:
252
241
  try:
253
242
  result = await _send(client, name, arguments, options)
254
243
  except Exception as error: # noqa: BLE001
255
- # Raised below: the client's task group would wrap it in an ExceptionGroup.
256
244
  failure = error
257
245
  if failure is not None:
258
246
  raise failure
@@ -262,13 +250,29 @@ class _App:
262
250
  and not result.is_error
263
251
  and "outputSchema" in definition
264
252
  ):
265
- validate(
253
+ self._validate(
254
+ name,
266
255
  definition["outputSchema"],
267
256
  result.structured_content,
268
257
  f"structured output from {self._name}.{name}",
269
258
  )
270
259
  return result
271
260
 
261
+ def _validate(
262
+ self, name: str, schema: dict[str, Any], value: Any, label: str
263
+ ) -> None:
264
+ validator = self._validators.get(name)
265
+ if validator is None or validator.schema is not schema:
266
+ cls = jsonschema.validators.validator_for(schema)
267
+ cls.check_schema(schema)
268
+ validator = self._validators[name] = cls(
269
+ schema, registry=Registry(), format_checker=jsonschema.FormatChecker()
270
+ )
271
+ if (
272
+ error := jsonschema.exceptions.best_match(validator.iter_errors(value))
273
+ ) is not None:
274
+ raise ValueError(f"Invalid {label}: {error.message}") from error
275
+
272
276
  async def _call_tool(
273
277
  self,
274
278
  tool: dict[str, Any],
@@ -311,7 +315,6 @@ class Apps:
311
315
  contracts: dict[str, Any],
312
316
  bindings: Mapping[str, Binding] | None = None,
313
317
  ) -> None:
314
- # Every declared dependency gets a client; those without a contract are untyped.
315
318
  available = dict.fromkeys(identity["requires"]) | contracts
316
319
  self._apps = {}
317
320
  for name in available if bindings is None else bindings:
@@ -0,0 +1,87 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Any, TypedDict
5
+
6
+ from mcp.server.auth.middleware.auth_context import get_access_token
7
+
8
+
9
+ class AddressClaims(TypedDict, total=False):
10
+ formatted: str
11
+ street_address: str
12
+ locality: str
13
+ region: str
14
+ postal_code: str
15
+ country: str
16
+
17
+
18
+ class IdentityClaims(TypedDict, total=False):
19
+ """Standard OpenID Connect claims.
20
+
21
+ Holon drops one whose value has the wrong type; other claims pass through.
22
+ """
23
+
24
+ name: str
25
+ given_name: str
26
+ family_name: str
27
+ middle_name: str
28
+ nickname: str
29
+ preferred_username: str
30
+ profile: str
31
+ picture: str
32
+ website: str
33
+ email: str
34
+ email_verified: bool
35
+ gender: str
36
+ birthdate: str
37
+ zoneinfo: str
38
+ locale: str
39
+ phone_number: str
40
+ phone_number_verified: bool
41
+ address: AddressClaims
42
+ updated_at: float
43
+
44
+
45
+ @dataclass(frozen=True)
46
+ class Principal:
47
+ """The user a request acts for, as Holon admitted it."""
48
+
49
+ issuer: str
50
+ subject: str
51
+ client_id: str
52
+ scopes: list[str]
53
+ claims: IdentityClaims
54
+ actor: dict[str, Any] | None = None
55
+
56
+
57
+ @dataclass(frozen=True)
58
+ class RequestContext:
59
+ principal: Principal | None
60
+
61
+
62
+ def get_context() -> RequestContext:
63
+ """Read the caller of the current MCP request.
64
+
65
+ Holon validates the request before it reaches the application and hands the
66
+ caller over as MCP's access token, so this reads ``get_access_token()``.
67
+
68
+ Returns:
69
+ A ``RequestContext`` whose ``principal`` is ``None`` for anonymous requests.
70
+
71
+ Example:
72
+ ``principal = get_context().principal``
73
+ """
74
+ admitted = get_access_token()
75
+ extra = (admitted.claims or {}) if admitted else {}
76
+ if admitted is None or admitted.subject is None or "iss" not in extra:
77
+ return RequestContext(principal=None)
78
+ return RequestContext(
79
+ Principal(
80
+ issuer=extra["iss"],
81
+ subject=admitted.subject,
82
+ client_id=admitted.client_id,
83
+ scopes=admitted.scopes,
84
+ claims=extra.get("claims", {}),
85
+ actor=extra.get("act"),
86
+ )
87
+ )
@@ -4,8 +4,8 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "holon-sh"
7
- version = "0.0.1.dev5"
8
- description = "Typed MCP clients, bindings, and app views"
7
+ version = "0.0.1.dev6"
8
+ description = "Typed MCP clients and the caller of an MCP request"
9
9
  readme = "README.md"
10
10
  license = "Apache-2.0"
11
11
  license-files = ["LICENSE"]
@@ -0,0 +1,53 @@
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 Principal, get_context
6
+
7
+ PROFILE = {"email": "user@example.com", "email_verified": True}
8
+
9
+
10
+ def test_get_context_reads_the_caller_holon_admitted():
11
+ assert get_context().principal is None
12
+ for client_id, scopes, extra, expected in [
13
+ (
14
+ "web",
15
+ ["read", "write"],
16
+ {
17
+ "iss": "https://id.example",
18
+ "sub": "user",
19
+ "claims": PROFILE,
20
+ "act": {"sub": "agent"},
21
+ },
22
+ Principal(
23
+ issuer="https://id.example",
24
+ subject="user",
25
+ client_id="web",
26
+ scopes=["read", "write"],
27
+ claims=PROFILE,
28
+ actor={"sub": "agent"},
29
+ ),
30
+ ),
31
+ (
32
+ "web",
33
+ [],
34
+ {"iss": "https://id.example", "sub": "user"},
35
+ Principal("https://id.example", "user", "web", [], {}),
36
+ ),
37
+ # A hook call carries no user, and a caller needs an issuer.
38
+ ("", [], {"hook": {"event": "installed"}}, None),
39
+ ("web", [], {"sub": "user"}, None),
40
+ ]:
41
+ # The Holon host builds the access token this way from what it admitted.
42
+ token = AccessToken(
43
+ token="t",
44
+ client_id=client_id,
45
+ scopes=scopes,
46
+ subject=extra.get("sub"),
47
+ claims=extra,
48
+ )
49
+ admitted = auth_context_var.set(AuthenticatedUser(token))
50
+ try:
51
+ assert get_context().principal == expected
52
+ finally:
53
+ auth_context_var.reset(admitted)
@@ -51,9 +51,7 @@ def ask_size() -> Elicit[Choice]:
51
51
  return Elicit(QUESTION, Choice)
52
52
 
53
53
 
54
- def exercise(body, contract=CONTRACT):
55
- """Run body against a real server."""
56
-
54
+ def exercise(body):
57
55
  async def run():
58
56
  server = MCPServer("orders")
59
57
 
@@ -80,7 +78,7 @@ def exercise(body, contract=CONTRACT):
80
78
 
81
79
  apps = Apps(
82
80
  {"name": "checkout", "version": "1", "requires": {}},
83
- {"orders": contract},
81
+ {"orders": CONTRACT},
84
82
  {
85
83
  "orders": {
86
84
  "endpoint": "http://127.0.0.1:8000/mcp",
@@ -94,16 +92,12 @@ def exercise(body, contract=CONTRACT):
94
92
  asyncio.run(asyncio.wait_for(run(), timeout=15))
95
93
 
96
94
 
97
- async def large(params):
98
- return ElicitResult(action="accept", content={"size": "large"})
99
-
100
-
101
95
  def test_elicit_answers_in_place_and_the_call_returns_typed_output():
102
96
  asked = []
103
97
 
104
98
  async def elicit(params):
105
99
  asked.append(params.message)
106
- return await large(params)
100
+ return ElicitResult(action="accept", content={"size": "large"})
107
101
 
108
102
  async def body(orders):
109
103
  assert await orders.tools.ship({"elicit": elicit}, id="A-1") == {
@@ -114,28 +108,6 @@ def test_elicit_answers_in_place_and_the_call_returns_typed_output():
114
108
  assert asked == [QUESTION]
115
109
 
116
110
 
117
- def test_accepted_output_is_still_validated():
118
- tool = CONTRACT["tools"][0]
119
- wrong = {"type": "object", "required": ["total"]}
120
-
121
- async def body(orders):
122
- with pytest.raises(ValueError, match="structured output"):
123
- await orders.tools.ship({"elicit": large}, id="A-1")
124
-
125
- exercise(body, {"tools": [{**tool, "outputSchema": wrong}]})
126
-
127
-
128
- def test_a_declined_question_reaches_the_tool():
129
- async def decline(params):
130
- return ElicitResult(action="decline")
131
-
132
- async def body(orders):
133
- with pytest.raises(ToolCallError, match="elicitation was decline"):
134
- await orders.tools.ship({"elicit": decline}, id="A-1")
135
-
136
- exercise(body)
137
-
138
-
139
111
  def test_a_server_that_keeps_asking_stops_after_ten_answers():
140
112
  answers = []
141
113
 
@@ -157,9 +129,7 @@ def test_without_elicit_the_question_reaches_the_caller_who_continues():
157
129
  await orders.tools.ship(id="A-1")
158
130
  assert str(error.value) == f"orders.ship: additional input required: {QUESTION}"
159
131
  result = error.value.result
160
- assert isinstance(result, InputRequiredResult)
161
- [(key, request)] = result.input_requests.items()
162
- assert request.params.message == QUESTION
132
+ [key] = result.input_requests
163
133
  answer = ElicitResult(action="accept", content={"size": "small"})
164
134
  continued = await orders.call_tool(
165
135
  "ship",
@@ -1,5 +1,3 @@
1
- """Consumer contracts at the generated namespace boundary."""
2
-
3
1
  import os
4
2
  import shutil
5
3
  import subprocess
@@ -8,7 +6,18 @@ from pathlib import Path
8
6
 
9
7
 
10
8
  def test_generated_namespace_combines_app_types_with_installed_runtime(tmp_path):
11
- # Refresh with scripts/fixtures.sh; generation is tested in holon-sh/cli.
9
+ env = os.environ.copy()
10
+ env.pop("MYPYPATH", None)
11
+ env.pop("PYTHONPATH", None)
12
+ placeholder = subprocess.run(
13
+ [sys.executable, "-c", "import holon.apps"],
14
+ cwd=tmp_path,
15
+ env=env,
16
+ capture_output=True,
17
+ text=True,
18
+ check=False,
19
+ )
20
+ assert "run `holon types generate`" in placeholder.stderr
12
21
  shutil.copytree(
13
22
  Path(__file__).parent / "fixtures/caller", tmp_path, dirs_exist_ok=True
14
23
  )
@@ -48,11 +57,6 @@ async def invalid() -> None:
48
57
  assert holon.__file__ is None
49
58
  assert Path(holon.client.__file__).parent != Path(__file__).parent / "holon"
50
59
  """)
51
- # Runtime and typing must agree across the two namespace portions. No
52
- # MYPYPATH/PYTHONPATH override is allowed to hide packaging problems.
53
- env = os.environ.copy()
54
- env.pop("MYPYPATH", None)
55
- env.pop("PYTHONPATH", None)
56
60
  result = subprocess.run(
57
61
  [sys.executable, "-m", "mypy", "--strict", "--no-error-summary", "check.py"],
58
62
  cwd=tmp_path,
@@ -65,3 +69,14 @@ assert Path(holon.client.__file__).parent != Path(__file__).parent / "holon"
65
69
  assert len(result.stdout.splitlines()) == 1, result.stdout
66
70
  assert '"OrdersApp" has no attribute "missing"' in result.stdout
67
71
  subprocess.run([sys.executable, "check.py"], cwd=tmp_path, env=env, check=True)
72
+ (tmp_path / "later").mkdir()
73
+ subprocess.run(
74
+ [
75
+ sys.executable,
76
+ "-c",
77
+ "import sys; sys.path.append('..'); from holon.apps import apps",
78
+ ],
79
+ cwd=tmp_path / "later",
80
+ env=env,
81
+ check=True,
82
+ )
@@ -1,13 +1,13 @@
1
1
  import asyncio
2
2
  import json
3
+ import socket
3
4
 
4
5
  import httpx2
5
6
  import pytest
7
+ import uvicorn
6
8
  from mcp.server import MCPServer
7
9
  from mcp.types import CallToolResult, InputRequiredResult, TextContent
8
10
 
9
- import holon.binding
10
- from holon.binding import set_default_binding
11
11
  from holon.client import Apps, ToolCallError
12
12
 
13
13
  CONTRACT = {
@@ -35,10 +35,8 @@ CONTRACT = {
35
35
  }
36
36
 
37
37
 
38
- def test_clients_preserve_mcp_results_validate_and_cancel(monkeypatch):
38
+ def test_clients_preserve_mcp_results_and_validate(monkeypatch):
39
39
  async def exercise():
40
- started = asyncio.Event()
41
- cancelled = asyncio.Event()
42
40
  server = MCPServer("orders")
43
41
 
44
42
  @server.tool()
@@ -55,16 +53,9 @@ def test_clients_preserve_mcp_results_validate_and_cancel(monkeypatch):
55
53
  return InputRequiredResult(
56
54
  request_state="opaque", _meta={"preserved": True}
57
55
  )
58
- if id == "slow":
59
- started.set()
60
- try:
61
- await asyncio.Event().wait()
62
- finally:
63
- cancelled.set()
64
56
  return CallToolResult(
65
57
  content=[TextContent(type="text", text="Order")],
66
58
  structured_content={"total": "bad" if id == "bad" else limit},
67
- _meta={"preserved": True},
68
59
  )
69
60
 
70
61
  app = server.streamable_http_app(stateless_http=True)
@@ -73,34 +64,32 @@ def test_clients_preserve_mcp_results_validate_and_cancel(monkeypatch):
73
64
  headers = []
74
65
 
75
66
  async def record(request):
76
- headers.append(request.headers.get("authorization"))
77
67
  if request.method == "POST":
78
68
  requests.append(json.loads(await request.aread()))
79
69
 
70
+ async def listen(scope, receive, send):
71
+ if scope["type"] == "http":
72
+ headers.append(dict(scope["headers"]).get(b"authorization"))
73
+ await app(scope, receive, send)
74
+
80
75
  def http_client():
81
76
  client = httpx2.AsyncClient(
82
- transport=httpx2.ASGITransport(app=app),
77
+ transport=httpx2.ASGITransport(app=listen),
83
78
  headers={"Authorization": "Bearer external"},
84
79
  event_hooks={"request": [record]},
85
80
  )
86
81
  clients.append(client)
87
82
  return client
88
83
 
89
- monkeypatch.setattr(holon.binding, "_resolver", None)
90
84
  monkeypatch.delenv("MISSING_MCP_URL", raising=False)
91
- set_default_binding(
92
- lambda app: (
93
- {"endpoint": "http://127.0.0.1:8000/mcp", "http_client": http_client}
94
- if app == "orders"
95
- else None
96
- )
97
- )
85
+ monkeypatch.setenv("ORDERS_MCP_TOKEN", "secret")
86
+ binding = {"endpoint": "http://127.0.0.1:8000/mcp", "http_client": http_client}
87
+ bindings = {"orders": binding}
98
88
  identity = {"name": "checkout", "version": "1", "requires": {"orders": {}}}
99
- apps = Apps(identity, {"orders": CONTRACT})
100
- other = Apps({**identity, "name": "other"}, {"orders": CONTRACT})
101
- assert not requests
89
+ apps = Apps(identity, {"orders": CONTRACT}, bindings)
90
+ other = Apps({**identity, "name": "other"}, {"orders": CONTRACT}, bindings)
102
91
  async with app.router.lifespan_context(app):
103
- output, raw = await asyncio.gather(
92
+ await asyncio.gather(
104
93
  apps.orders.tools.read(id="good"),
105
94
  other.orders.call_tool(
106
95
  "read",
@@ -114,10 +103,6 @@ def test_clients_preserve_mcp_results_validate_and_cancel(monkeypatch):
114
103
  timeout=7,
115
104
  ),
116
105
  )
117
- assert output == {"total": 5}
118
- assert raw.structured_content == {"total": 2}
119
- assert raw.content[0].text == "Order"
120
- assert raw.meta["preserved"] is True
121
106
  request = next(
122
107
  request["params"]
123
108
  for request in requests
@@ -144,58 +129,50 @@ def test_clients_preserve_mcp_results_validate_and_cancel(monkeypatch):
144
129
  await apps.orders.tools.read(id=value)
145
130
  assert type(error.value.result) is type(raw)
146
131
  assert error.value.result.meta["preserved"] is True
147
- if isinstance(raw, InputRequiredResult):
148
- assert error.value.result.request_state
149
- await apps.orders.call_tool(
150
- "read",
151
- {"request_state": raw.request_state, "input_responses": {}},
152
- id=value,
153
- )
154
- assert requests[-1]["params"]["requestState"] == raw.request_state
155
- assert requests[-1]["params"]["inputResponses"] == {}
156
- else:
132
+ if value == "error":
157
133
  assert error.value.result == raw
158
134
  assert "Unavailable" in str(error.value)
159
- before = len(requests)
160
- with pytest.raises(ValueError, match="arguments"):
161
- await apps.orders.tools.read(id=1)
162
- assert len(requests) == before
163
135
  with pytest.raises(ValueError, match="structured output"):
164
136
  await apps.orders.tools.read(id="bad")
165
- task = asyncio.create_task(apps.orders.tools.read(id="slow"))
166
- await started.wait()
167
- task.cancel()
168
- with pytest.raises(asyncio.CancelledError):
169
- await task
170
- await cancelled.wait()
171
- untyped = Apps({**identity, "requires": {"orders": {}, "missing": {}}}, {})
137
+ undeclared = {**identity, "requires": {"orders": {}, "missing": {}}}
138
+ untyped = Apps(undeclared, {}, bindings)
172
139
  raw = await untyped.orders.call_tool("read", id="good")
173
140
  assert raw.structured_content == {"total": 5}
174
- assert not hasattr(untyped.orders.tools, "read")
175
141
  tool = {
176
142
  k: v for k, v in CONTRACT["tools"][0].items() if k != "outputSchema"
177
143
  }
178
- plain = Apps(identity, {"orders": {"tools": [tool]}})
144
+ plain = Apps(identity, {"orders": {"tools": [tool]}}, bindings)
179
145
  assert (await plain.orders.tools.read(id="good")).content[0].text == "Order"
180
146
  with pytest.raises(RuntimeError, match=r"unavailable \(MISSING_MCP_URL\)"):
181
- await untyped.missing.call_tool("read")
182
- # Explicit bindings work without a declaration and override the resolver.
183
- set_default_binding(
184
- lambda _: {"endpoint": "http://unavailable.invalid/mcp"}
185
- )
147
+ await Apps(undeclared, {}).missing.call_tool("read")
186
148
  script = {**identity, "requires": {}}
187
- binding = {
188
- "endpoint": "http://127.0.0.1:8000/mcp",
189
- "http_client": http_client,
190
- }
191
149
  with pytest.raises(ValueError, match="Unknown app binding"):
192
150
  Apps(script, {"orders": CONTRACT}, {"missing": binding})
193
- bound = Apps(script, {"orders": CONTRACT}, {"orders": binding})
151
+ bound = Apps(script, {"orders": CONTRACT}, bindings)
194
152
  assert await bound.orders.tools.read(id="good") == {"total": 5}
195
- set_default_binding(lambda _: None)
196
153
  with pytest.raises(ValueError, match="not declared"):
197
154
  await Apps(script, {"orders": CONTRACT}).orders.tools.read(id="good")
198
- assert headers and all(value == "Bearer external" for value in headers)
155
+ assert set(headers) == {b"Bearer external"}
156
+ sock = socket.create_server(("127.0.0.1", 0))
157
+ monkeypatch.setenv(
158
+ "ORDERS_MCP_URL", f"http://127.0.0.1:{sock.getsockname()[1]}/mcp"
159
+ )
160
+ http = uvicorn.Server(
161
+ uvicorn.Config(listen, lifespan="off", log_level="warning")
162
+ )
163
+ serving = asyncio.create_task(http.serve(sockets=[sock]))
164
+ apps = Apps(identity, {"orders": CONTRACT})
165
+ try:
166
+ headers.clear()
167
+ assert await apps.orders.tools.read(id="good") == {"total": 5}
168
+ assert set(headers) == {b"Bearer secret"}
169
+ monkeypatch.delenv("ORDERS_MCP_TOKEN")
170
+ headers.clear()
171
+ await apps.orders.tools.read(id="good")
172
+ assert set(headers) == {None}
173
+ finally:
174
+ http.should_exit = True
175
+ await serving
199
176
  assert all(client.is_closed for client in clients)
200
177
 
201
178
  asyncio.run(asyncio.wait_for(exercise(), timeout=15))
@@ -1,47 +0,0 @@
1
- from __future__ import annotations
2
-
3
- from collections.abc import Callable
4
- from typing import NotRequired, TypedDict
5
-
6
- import httpx2
7
-
8
-
9
- class Binding(TypedDict):
10
- """Connection settings for an MCP dependency.
11
-
12
- Attributes:
13
- endpoint: Streamable HTTP MCP URL.
14
- http_client: Factory returning a fresh ``httpx2.AsyncClient`` for each
15
- call. Configure authentication headers or a custom transport here.
16
- The SDK closes the returned client when the call finishes.
17
- """
18
-
19
- endpoint: str
20
- http_client: NotRequired[Callable[[], httpx2.AsyncClient]]
21
-
22
-
23
- _resolver: Callable[[str], Binding | None] | None = None
24
-
25
-
26
- def set_default_binding(resolve: Callable[[str], Binding | None]) -> None:
27
- """Register the default binding resolver for app clients.
28
-
29
- Args:
30
- resolve: Process-wide callback receiving the dependency name. Return a
31
- binding or ``None`` to use the environment fallback. Explicit
32
- bindings take precedence. Register during application startup.
33
- """
34
- global _resolver
35
- _resolver = resolve
36
-
37
-
38
- def resolve_default_binding(app: str) -> Binding | None:
39
- """Return the registered resolver's binding for an app.
40
-
41
- Args:
42
- app: Dependency name passed unchanged to the resolver.
43
-
44
- Returns:
45
- The resolved binding, or ``None`` if none is available.
46
- """
47
- return _resolver(app) if _resolver is not None else None
@@ -1,55 +0,0 @@
1
- from __future__ import annotations
2
-
3
- from pathlib import Path
4
-
5
- from mcp.server.apps import APP_MIME_TYPE
6
- from mcp.server.mcpserver.resources import FunctionResource
7
-
8
-
9
- def app_view(
10
- uri: str,
11
- name: str,
12
- file: Path | str,
13
- *,
14
- connect_domains: list[str] | None = None,
15
- resource_domains: list[str] | None = None,
16
- ) -> FunctionResource:
17
- """Create a server resource serving a built MCP App HTML file.
18
-
19
- Args:
20
- uri: Resource URI, normally starting with ``ui://``.
21
- name: Human-readable resource name.
22
- file: HTML file to read lazily on the first resource request.
23
- connect_domains: Domains allowed for network connections by the view.
24
- resource_domains: Domains allowed for external view assets.
25
-
26
- Returns:
27
- A ``FunctionResource`` ready for the MCP server's resource manager.
28
- Successful reads are cached for the lifetime of this resource instance.
29
-
30
- Raises:
31
- OSError: Reading the HTML file failed.
32
-
33
- Example:
34
- ``resource = app_view("ui://app/index.html", "App", "dist/index.html")``
35
- """
36
- page = Path(file)
37
- csp = {
38
- "connectDomains": connect_domains or [],
39
- "resourceDomains": resource_domains or [],
40
- }
41
- built: list[str] = []
42
-
43
- def read() -> str:
44
- # Concurrent first reads must all return the first cached build.
45
- if not built:
46
- built.append(page.read_text())
47
- return built[0]
48
-
49
- return FunctionResource.from_function(
50
- read,
51
- uri,
52
- name=name,
53
- mime_type=APP_MIME_TYPE,
54
- meta={"ui": {"csp": csp}},
55
- )
@@ -1,7 +0,0 @@
1
- #!/bin/sh
2
- set -eu
3
-
4
- # Run from any directory with the holon CLI on PATH. The orders server is
5
- # statically extracted; no running server or installed fixture dependencies are needed.
6
- cd "$(dirname "$0")/../tests/fixtures/caller"
7
- exec holon types generate -s ../orders
@@ -1,5 +0,0 @@
1
- {
2
- "name": "fixtures/orders",
3
- "version": "1",
4
- "description": "Orders contract for the Python package fixture."
5
- }
@@ -1,57 +0,0 @@
1
- """Static tool catalog for generated-client typing regressions."""
2
-
3
- from mcp.server import Server
4
- from mcp.types import Tool
5
-
6
- server = Server("orders")
7
-
8
- READ_INPUT = {
9
- "type": "object",
10
- "properties": {
11
- "id": {"type": "string"},
12
- "limit": {"type": "integer"},
13
- "name": {"type": "string"},
14
- "timeout": {"type": "string"},
15
- "options": {"type": "string"},
16
- "self": {"type": "string"},
17
- "arguments": {"type": "string"},
18
- "class": {"type": "string"},
19
- "order-id": {"type": "string"},
20
- },
21
- "required": ["id"],
22
- "additionalProperties": False,
23
- }
24
- READ_OUTPUT = {
25
- "type": "object",
26
- "properties": {"total": {"type": "number"}},
27
- "required": ["total"],
28
- }
29
-
30
-
31
- @server.list_tools()
32
- async def tools() -> list[Tool]:
33
- return [
34
- Tool(name="read", input_schema=READ_INPUT, output_schema=READ_OUTPUT),
35
- Tool(name="get-order", input_schema=READ_INPUT, output_schema=READ_OUTPUT),
36
- Tool(name="ping", input_schema={"type": "object", "additionalProperties": False}),
37
- Tool(
38
- name="counts",
39
- input_schema={"type": "object", "additionalProperties": {"type": "integer"}},
40
- ),
41
- Tool(
42
- name="find",
43
- input_schema={
44
- "type": "object",
45
- "anyOf": [
46
- READ_INPUT,
47
- READ_INPUT,
48
- {
49
- "type": "object",
50
- "properties": {"email": {"type": "string"}},
51
- "required": ["email"],
52
- "additionalProperties": False,
53
- },
54
- ],
55
- },
56
- ),
57
- ]
@@ -1,47 +0,0 @@
1
- import asyncio
2
-
3
- from mcp import Client
4
- from mcp.server import MCPServer
5
- from mcp.server.apps import APP_MIME_TYPE
6
-
7
- from holon.view import app_view
8
-
9
-
10
- def test_app_view_serves_one_build_for_the_life_of_the_process(tmp_path):
11
- page = tmp_path / "index.html"
12
- page.write_text("<html>one</html>")
13
- server = MCPServer("site")
14
- server.add_resource(
15
- app_view(
16
- "ui://site/index.html",
17
- "Site",
18
- page,
19
- connect_domains=["https://api.example"],
20
- )
21
- )
22
-
23
- async def exercise():
24
- async with Client(server, mode="2026-07-28") as client:
25
- listed = await client.list_resources()
26
- resource = listed.resources[0]
27
- assert (str(resource.uri), resource.name, resource.mime_type) == (
28
- "ui://site/index.html",
29
- "Site",
30
- APP_MIME_TYPE,
31
- )
32
- assert resource.meta == {
33
- "ui": {
34
- "csp": {
35
- "connectDomains": ["https://api.example"],
36
- "resourceDomains": [],
37
- }
38
- }
39
- }
40
- first = await client.read_resource("ui://site/index.html")
41
- assert first.contents[0].text == "<html>one</html>"
42
- assert first.contents[0].mime_type == APP_MIME_TYPE
43
- page.write_text("<html>two</html>")
44
- second = await client.read_resource("ui://site/index.html")
45
- assert second.contents[0].text == "<html>one</html>"
46
-
47
- asyncio.run(exercise())
File without changes
File without changes