tesseron 0.1.0__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.
@@ -0,0 +1,8 @@
1
+ .venv/
2
+ dist/
3
+ .mypy_cache/
4
+ .pytest_cache/
5
+ .ruff_cache/
6
+ __pycache__/
7
+ *.egg-info/
8
+ .claude/
tesseron-0.1.0/LICENSE ADDED
@@ -0,0 +1,114 @@
1
+ Business Source License 1.1
2
+
3
+ License text copyright (c) 2020 MariaDB Corporation Ab, All Rights Reserved.
4
+ "Business Source License" is a trademark of MariaDB Corporation Ab.
5
+
6
+ -----------------------------------------------------------------------------
7
+
8
+ Parameters
9
+
10
+ Licensor: Kenny Vaneetvelde
11
+
12
+ Licensed Work: Tesseron
13
+ The Licensed Work is (c) 2026 Kenny Vaneetvelde.
14
+
15
+ Additional Use Grant: You may make production use of the Licensed Work,
16
+ provided your use does not include offering the
17
+ Licensed Work, or a substantial portion of its
18
+ functionality, to third parties as a hosted or
19
+ managed service.
20
+
21
+ For clarity, permitted uses include (but are not
22
+ limited to): embedding the Licensed Work in your
23
+ own applications (commercial or otherwise),
24
+ internal use within your organization, consulting
25
+ engagements that integrate the Licensed Work into
26
+ client applications, redistributing modified or
27
+ unmodified copies of the Licensed Work, and running
28
+ the gateway locally on end-user machines as part
29
+ of the user's own tooling.
30
+
31
+ Change Date: Four years from the date the Licensed Work is
32
+ published. For each release of the Licensed Work,
33
+ the Change Date is four years from the publication
34
+ date of that release.
35
+
36
+ Change License: Apache License, Version 2.0
37
+
38
+ -----------------------------------------------------------------------------
39
+
40
+ Terms
41
+
42
+ The Licensor hereby grants you the right to copy, modify, create derivative
43
+ works, redistribute, and make non-production use of the Licensed Work. The
44
+ Licensor may make an Additional Use Grant, above, permitting limited
45
+ production use.
46
+
47
+ Effective on the Change Date, or the fourth anniversary of the first
48
+ publicly available distribution of a specific version of the Licensed Work
49
+ under this License, whichever comes first, the Licensor hereby grants you
50
+ rights under the terms of the Change License, and the rights granted in the
51
+ paragraph above terminate.
52
+
53
+ If your use of the Licensed Work does not comply with the requirements
54
+ currently in effect as described in this License, you must purchase a
55
+ commercial license from the Licensor, its affiliated entities, or authorized
56
+ resellers, or you must refrain from using the Licensed Work.
57
+
58
+ All copies of the original and modified Licensed Work, and derivative works
59
+ of the Licensed Work, are subject to this License. This License applies
60
+ separately for each version of the Licensed Work and the Change Date may
61
+ vary for each version of the Licensed Work released by Licensor.
62
+
63
+ You must conspicuously display this License on each original or modified
64
+ copy of the Licensed Work. If you receive the Licensed Work in original or
65
+ modified form from a third party, the terms and conditions set forth in
66
+ this License apply to your use of that work.
67
+
68
+ Any use of the Licensed Work in violation of this License will automatically
69
+ terminate your rights under this License for the current and all other
70
+ versions of the Licensed Work.
71
+
72
+ This License does not grant you any right in any trademark or logo of
73
+ Licensor or its affiliates (provided that you may use a trademark or logo of
74
+ Licensor as expressly required by this License).
75
+
76
+ TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON
77
+ AN "AS IS" BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS,
78
+ EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF
79
+ MERCHANTABILITY, NON-INFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
80
+
81
+ MariaDB hereby grants you permission to use this License's text to license
82
+ your works, and to refer to it using the trademark "Business Source License",
83
+ as long as you comply with the Covenants of Licensor below.
84
+
85
+ -----------------------------------------------------------------------------
86
+
87
+ Covenants of Licensor
88
+
89
+ In consideration of the right to use this License's text and the "Business
90
+ Source License" name and trademark, Licensor covenants to MariaDB, and to
91
+ all other recipients of the licensed work to be provided by Licensor:
92
+
93
+ 1. To specify as the Change License the GPL Version 2.0 or any later version,
94
+ or a license that is compatible with GPL Version 2.0 or a later version,
95
+ where "compatible" means that software provided under the Change License
96
+ can be included in a program with software provided under GPL Version 2.0
97
+ or a later version. Licensor may specify additional Change Licenses
98
+ without limitation.
99
+
100
+ 2. To either: (a) specify an additional grant of rights to use that does not
101
+ impose any additional restriction on the right granted in this License,
102
+ as the Additional Use Grant; or (b) insert the text "None".
103
+
104
+ 3. To specify a Change Date.
105
+
106
+ 4. Not to modify this License in any other way.
107
+
108
+ -----------------------------------------------------------------------------
109
+
110
+ Notice
111
+
112
+ The Business Source License (this document, or the "License") is not an
113
+ Open Source license. However, the Licensed Work will eventually be made
114
+ available under an Open Source License, as stated in this License.
@@ -0,0 +1,139 @@
1
+ Metadata-Version: 2.5
2
+ Name: tesseron
3
+ Version: 0.1.0
4
+ Summary: Expose typed application actions to MCP-compatible AI agents over WebSocket.
5
+ Project-URL: Homepage, https://eigenwise.github.io/tesseron/
6
+ Project-URL: Documentation, https://eigenwise.github.io/tesseron/sdk/python/
7
+ Project-URL: Repository, https://github.com/Eigenwise/tesseron-python
8
+ Project-URL: Issues, https://github.com/Eigenwise/tesseron/issues
9
+ Author-email: Kenny Vaneetvelde <kenny@eigenwise.io>
10
+ License-Expression: BUSL-1.1
11
+ License-File: LICENSE
12
+ Keywords: agents,json-rpc,mcp,tesseron,websocket
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Framework :: AsyncIO
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Typing :: Typed
20
+ Requires-Python: >=3.11
21
+ Requires-Dist: pydantic>=2.7
22
+ Requires-Dist: websockets>=14
23
+ Description-Content-Type: text/markdown
24
+
25
+ # tesseron (Python)
26
+
27
+ The Python SDK lives at [Eigenwise/tesseron-python](https://github.com/Eigenwise/tesseron-python).
28
+ The [Tesseron hub](https://github.com/Eigenwise/tesseron) owns the protocol, docs, and issues.
29
+
30
+ The Python implementation of the [Tesseron](https://eigenwise.github.io/tesseron/) host
31
+ protocol. Your application listens on loopback, the MCP gateway dials in, and the agent
32
+ gets typed actions and readable resources instead of a scraper.
33
+
34
+ Speaks protocol **1.2.0**. Compatibility is decided by protocol version, never by matching
35
+ package numbers: see the
36
+ [compatibility contract](https://eigenwise.github.io/tesseron/protocol/compatibility/).
37
+
38
+ Not on PyPI yet.
39
+
40
+ ## Install
41
+
42
+ ```bash
43
+ uv add tesseron
44
+ ```
45
+
46
+ Python 3.11 or newer. The only runtime dependencies are Pydantic v2 and `websockets`.
47
+
48
+ ## A first action
49
+
50
+ ```python
51
+ import asyncio
52
+
53
+ from pydantic import BaseModel, Field
54
+ from tesseron import ActionContext, TesseronApp
55
+
56
+ app = TesseronApp(id="todo", name="Todo", origin="http://127.0.0.1")
57
+
58
+
59
+ class AddTodo(BaseModel):
60
+ text: str = Field(min_length=1)
61
+ tag: str | None = None
62
+
63
+
64
+ @app.action("addTodo", description="Add one todo")
65
+ async def add_todo(input: AddTodo, context: ActionContext) -> dict[str, object]:
66
+ await context.progress(percent=100, message="saved")
67
+ return {"id": "1", "text": input.text, "done": False, "tag": input.tag}
68
+
69
+
70
+ async def main() -> None:
71
+ host = await app.listen()
72
+ print(host.url)
73
+ await asyncio.Event().wait()
74
+
75
+
76
+ asyncio.run(main())
77
+ ```
78
+
79
+ The input type comes from the handler annotation. Its validation-mode JSON Schema is what
80
+ the manifest publishes, and `model_validate` is what rejects bad input with `-32004` before
81
+ the handler body runs.
82
+
83
+ ## What it covers
84
+
85
+ Handshake and claiming, session resume with in-memory token rotation, action invocation
86
+ with validation, cancellation, timeouts, progress, sampling, confirmation, schema-checked
87
+ elicitation, structured logs, and resources with reads, subscriptions, and pushes.
88
+
89
+ Gateway-minted claims only. WebSocket only: no Unix domain sockets and no host-minted bind
90
+ in this release, so the conformance suite skips those fixtures honestly.
91
+
92
+ ## Examples
93
+
94
+ From the repo root, run the headless todo app with:
95
+
96
+ ```bash
97
+ uv run --locked --directory sdks/python python -m examples.todo
98
+ ```
99
+
100
+ Run the prompt library with:
101
+
102
+ ```bash
103
+ uv run --locked --directory sdks/python python -m examples.prompts
104
+ ```
105
+
106
+ Each prints a claim code after the gateway connects. In Claude Code with the Tesseron plugin
107
+ loaded, ask Claude to claim that code, then call the actions. The todo app includes the canonical
108
+ `todos://all` resource and the prompt app includes `library` and `lastTest` resources.
109
+
110
+ Validate both examples against the real gateway with `pnpm example:python:e2e`.
111
+
112
+ ## Development
113
+
114
+ Run everything from this directory:
115
+
116
+ ```bash
117
+ uv sync --locked
118
+ uv run ruff check .
119
+ uv run ruff format --check .
120
+ uv run mypy --strict src tests
121
+ uv run pytest
122
+ uv build
123
+ ```
124
+
125
+ The conformance host lives in `conformance_host/`, beside the package rather than inside
126
+ it, so the published wheel carries the SDK and nothing else. See
127
+ [the conformance page](https://eigenwise.github.io/tesseron/sdk/python/conformance/) for how
128
+ the runner drives it.
129
+
130
+ ## Documentation
131
+
132
+ - [Python SDK](https://eigenwise.github.io/tesseron/sdk/python/)
133
+ - [Protocol specification](https://eigenwise.github.io/tesseron/protocol/)
134
+
135
+ ## License
136
+
137
+ Tesseron is licensed under the [Business Source License 1.1](./LICENSE). Each
138
+ release auto-converts to Apache-2.0, the Change License, four years after
139
+ publication.
@@ -0,0 +1,115 @@
1
+ # tesseron (Python)
2
+
3
+ The Python SDK lives at [Eigenwise/tesseron-python](https://github.com/Eigenwise/tesseron-python).
4
+ The [Tesseron hub](https://github.com/Eigenwise/tesseron) owns the protocol, docs, and issues.
5
+
6
+ The Python implementation of the [Tesseron](https://eigenwise.github.io/tesseron/) host
7
+ protocol. Your application listens on loopback, the MCP gateway dials in, and the agent
8
+ gets typed actions and readable resources instead of a scraper.
9
+
10
+ Speaks protocol **1.2.0**. Compatibility is decided by protocol version, never by matching
11
+ package numbers: see the
12
+ [compatibility contract](https://eigenwise.github.io/tesseron/protocol/compatibility/).
13
+
14
+ Not on PyPI yet.
15
+
16
+ ## Install
17
+
18
+ ```bash
19
+ uv add tesseron
20
+ ```
21
+
22
+ Python 3.11 or newer. The only runtime dependencies are Pydantic v2 and `websockets`.
23
+
24
+ ## A first action
25
+
26
+ ```python
27
+ import asyncio
28
+
29
+ from pydantic import BaseModel, Field
30
+ from tesseron import ActionContext, TesseronApp
31
+
32
+ app = TesseronApp(id="todo", name="Todo", origin="http://127.0.0.1")
33
+
34
+
35
+ class AddTodo(BaseModel):
36
+ text: str = Field(min_length=1)
37
+ tag: str | None = None
38
+
39
+
40
+ @app.action("addTodo", description="Add one todo")
41
+ async def add_todo(input: AddTodo, context: ActionContext) -> dict[str, object]:
42
+ await context.progress(percent=100, message="saved")
43
+ return {"id": "1", "text": input.text, "done": False, "tag": input.tag}
44
+
45
+
46
+ async def main() -> None:
47
+ host = await app.listen()
48
+ print(host.url)
49
+ await asyncio.Event().wait()
50
+
51
+
52
+ asyncio.run(main())
53
+ ```
54
+
55
+ The input type comes from the handler annotation. Its validation-mode JSON Schema is what
56
+ the manifest publishes, and `model_validate` is what rejects bad input with `-32004` before
57
+ the handler body runs.
58
+
59
+ ## What it covers
60
+
61
+ Handshake and claiming, session resume with in-memory token rotation, action invocation
62
+ with validation, cancellation, timeouts, progress, sampling, confirmation, schema-checked
63
+ elicitation, structured logs, and resources with reads, subscriptions, and pushes.
64
+
65
+ Gateway-minted claims only. WebSocket only: no Unix domain sockets and no host-minted bind
66
+ in this release, so the conformance suite skips those fixtures honestly.
67
+
68
+ ## Examples
69
+
70
+ From the repo root, run the headless todo app with:
71
+
72
+ ```bash
73
+ uv run --locked --directory sdks/python python -m examples.todo
74
+ ```
75
+
76
+ Run the prompt library with:
77
+
78
+ ```bash
79
+ uv run --locked --directory sdks/python python -m examples.prompts
80
+ ```
81
+
82
+ Each prints a claim code after the gateway connects. In Claude Code with the Tesseron plugin
83
+ loaded, ask Claude to claim that code, then call the actions. The todo app includes the canonical
84
+ `todos://all` resource and the prompt app includes `library` and `lastTest` resources.
85
+
86
+ Validate both examples against the real gateway with `pnpm example:python:e2e`.
87
+
88
+ ## Development
89
+
90
+ Run everything from this directory:
91
+
92
+ ```bash
93
+ uv sync --locked
94
+ uv run ruff check .
95
+ uv run ruff format --check .
96
+ uv run mypy --strict src tests
97
+ uv run pytest
98
+ uv build
99
+ ```
100
+
101
+ The conformance host lives in `conformance_host/`, beside the package rather than inside
102
+ it, so the published wheel carries the SDK and nothing else. See
103
+ [the conformance page](https://eigenwise.github.io/tesseron/sdk/python/conformance/) for how
104
+ the runner drives it.
105
+
106
+ ## Documentation
107
+
108
+ - [Python SDK](https://eigenwise.github.io/tesseron/sdk/python/)
109
+ - [Protocol specification](https://eigenwise.github.io/tesseron/protocol/)
110
+
111
+ ## License
112
+
113
+ Tesseron is licensed under the [Business Source License 1.1](./LICENSE). Each
114
+ release auto-converts to Apache-2.0, the Change License, four years after
115
+ publication.
@@ -0,0 +1,80 @@
1
+ [project]
2
+ name = "tesseron"
3
+ version = "0.1.0"
4
+ description = "Expose typed application actions to MCP-compatible AI agents over WebSocket."
5
+ readme = "README.md"
6
+ requires-python = ">=3.11"
7
+ license = "BUSL-1.1"
8
+ authors = [{ name = "Kenny Vaneetvelde", email = "kenny@eigenwise.io" }]
9
+ keywords = ["tesseron", "mcp", "agents", "websocket", "json-rpc"]
10
+ classifiers = [
11
+ "Development Status :: 3 - Alpha",
12
+ "Framework :: AsyncIO",
13
+ "Intended Audience :: Developers",
14
+ "Programming Language :: Python :: 3.11",
15
+ "Programming Language :: Python :: 3.12",
16
+ "Programming Language :: Python :: 3.13",
17
+ "Typing :: Typed",
18
+ ]
19
+ dependencies = ["pydantic>=2.7", "websockets>=14"]
20
+
21
+ [project.urls]
22
+ Homepage = "https://eigenwise.github.io/tesseron/"
23
+ Documentation = "https://eigenwise.github.io/tesseron/sdk/python/"
24
+ Repository = "https://github.com/Eigenwise/tesseron-python"
25
+ Issues = "https://github.com/Eigenwise/tesseron/issues"
26
+
27
+ [build-system]
28
+ requires = ["hatchling"]
29
+ build-backend = "hatchling.build"
30
+
31
+ # The conformance host lives beside the package rather than inside it, so the
32
+ # published wheel carries the SDK and nothing else.
33
+ [tool.hatch.build.targets.wheel]
34
+ packages = ["src/tesseron"]
35
+
36
+ [tool.hatch.build.targets.sdist]
37
+ include = ["src", "tests", "README.md", "pyproject.toml"]
38
+
39
+ [dependency-groups]
40
+ dev = ["mypy>=1.11", "pytest>=8.3", "pytest-asyncio>=0.24", "ruff>=0.6"]
41
+
42
+ [tool.ruff]
43
+ line-length = 100
44
+ target-version = "py311"
45
+ src = ["src", "tests", "conformance_host"]
46
+
47
+ [tool.ruff.lint]
48
+ select = [
49
+ "A",
50
+ "ANN",
51
+ "ASYNC",
52
+ "B",
53
+ "BLE",
54
+ "C4",
55
+ "E",
56
+ "F",
57
+ "I",
58
+ "N",
59
+ "PTH",
60
+ "RUF",
61
+ "SIM",
62
+ "UP",
63
+ "W",
64
+ ]
65
+
66
+ [tool.ruff.lint.per-file-ignores]
67
+ "tests/*" = ["ANN401"]
68
+
69
+ [tool.pytest.ini_options]
70
+ asyncio_mode = "auto"
71
+ asyncio_default_fixture_loop_scope = "function"
72
+ testpaths = ["tests"]
73
+ # The conformance host sits outside the package, so the tests that cover it need this
74
+ # directory on the path.
75
+ pythonpath = ["."]
76
+
77
+ [tool.mypy]
78
+ python_version = "3.11"
79
+ strict = true
80
+ mypy_path = ["src", "."]
@@ -0,0 +1,98 @@
1
+ """Tesseron: expose typed application actions to MCP-compatible AI agents over WebSocket.
2
+
3
+ The application listens and the gateway dials in. Build a :class:`TesseronApp`, register
4
+ actions and resources on it, ``await app.listen()``, and hand the gateway the manifest the
5
+ host writes.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from .action import ActionHandler, InputValidator, TypedActionHandler, ValidationIssue
11
+ from .context import ActionContext, Cancellation
12
+ from .errors import (
13
+ ActionError,
14
+ DuplicateNameError,
15
+ HostError,
16
+ InvalidApplicationIdError,
17
+ ManifestError,
18
+ MissingApplicationError,
19
+ ProtocolError,
20
+ TesseronErrorCode,
21
+ )
22
+ from .host import (
23
+ ClaimedEvent,
24
+ DisconnectedEvent,
25
+ HandshakeFailedEvent,
26
+ HostEvent,
27
+ HostEventListener,
28
+ TesseronApp,
29
+ TesseronHost,
30
+ WelcomeEvent,
31
+ )
32
+ from .json_types import JsonObject, JsonValue
33
+ from .manifest import InstanceManifest, ManifestPublication
34
+ from .protocol import (
35
+ GATEWAY_SUBPROTOCOL,
36
+ PROTOCOL_VERSION,
37
+ ActionDescriptor,
38
+ AgentIdentity,
39
+ ApplicationDescriptor,
40
+ Capabilities,
41
+ ClaimedParams,
42
+ LogLevel,
43
+ ResourceDescriptor,
44
+ WelcomeResult,
45
+ )
46
+ from .resource import (
47
+ Emit,
48
+ Resource,
49
+ ResourceReader,
50
+ SubscribeCallback,
51
+ Subscription,
52
+ Unsubscribe,
53
+ )
54
+
55
+ __all__ = [
56
+ "GATEWAY_SUBPROTOCOL",
57
+ "PROTOCOL_VERSION",
58
+ "ActionContext",
59
+ "ActionDescriptor",
60
+ "ActionError",
61
+ "ActionHandler",
62
+ "AgentIdentity",
63
+ "ApplicationDescriptor",
64
+ "Cancellation",
65
+ "Capabilities",
66
+ "ClaimedEvent",
67
+ "ClaimedParams",
68
+ "DisconnectedEvent",
69
+ "DuplicateNameError",
70
+ "Emit",
71
+ "HandshakeFailedEvent",
72
+ "HostError",
73
+ "HostEvent",
74
+ "HostEventListener",
75
+ "InputValidator",
76
+ "InstanceManifest",
77
+ "InvalidApplicationIdError",
78
+ "JsonObject",
79
+ "JsonValue",
80
+ "LogLevel",
81
+ "ManifestError",
82
+ "ManifestPublication",
83
+ "MissingApplicationError",
84
+ "ProtocolError",
85
+ "Resource",
86
+ "ResourceDescriptor",
87
+ "ResourceReader",
88
+ "SubscribeCallback",
89
+ "Subscription",
90
+ "TesseronApp",
91
+ "TesseronErrorCode",
92
+ "TesseronHost",
93
+ "TypedActionHandler",
94
+ "Unsubscribe",
95
+ "ValidationIssue",
96
+ "WelcomeEvent",
97
+ "WelcomeResult",
98
+ ]
@@ -0,0 +1,142 @@
1
+ """One action the agent can invoke, and the input contract it publishes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Awaitable, Callable, Coroutine, Mapping, Sequence
6
+ from dataclasses import dataclass
7
+ from enum import Enum
8
+ from typing import TypeAlias, TypeVar
9
+
10
+ from pydantic import BaseModel, ValidationError
11
+
12
+ from .context import ActionContext
13
+ from .errors import ActionError, TesseronErrorCode
14
+ from .json_types import JsonObject, JsonValue
15
+ from .protocol import ActionDescriptor
16
+
17
+ __all__ = [
18
+ "ActionHandler",
19
+ "InputValidator",
20
+ "LooseHandler",
21
+ "RegisteredAction",
22
+ "TypedActionHandler",
23
+ "ValidationIssue",
24
+ "to_json_value",
25
+ ]
26
+
27
+ InputModel = TypeVar("InputModel", bound=BaseModel)
28
+
29
+ TypedActionHandler: TypeAlias = "Callable[[InputModel, ActionContext], Awaitable[object]]"
30
+ """A handler whose first parameter is annotated with a Pydantic model."""
31
+
32
+ ActionHandler: TypeAlias = "Callable[[JsonValue, ActionContext], Awaitable[object]]"
33
+ """A handler that takes the invocation input as raw JSON."""
34
+
35
+ LooseHandler: TypeAlias = "Callable[..., Awaitable[object]]"
36
+ """Either handler shape.
37
+
38
+ Registration reads the handler's annotations at runtime, so the decorator cannot know
39
+ statically which of the two shapes it was handed.
40
+ """
41
+
42
+ DispatchHandler: TypeAlias = (
43
+ "Callable[[JsonValue, ActionContext], Coroutine[object, object, JsonValue]]"
44
+ )
45
+ """What the session runs: input validation folded in, output already JSON.
46
+
47
+ Concretely a coroutine rather than any awaitable, because the session runs each invocation
48
+ as its own task so it can race the handler against cancellation and the timeout.
49
+ """
50
+
51
+ InputValidator: TypeAlias = "Callable[[JsonValue], list[ValidationIssue]]"
52
+ """Checks raw invocation input and answers every problem it finds."""
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class ValidationIssue:
57
+ """One reason invocation input was refused, reported inside a ``-32004`` failure."""
58
+
59
+ message: str
60
+ path: list[str]
61
+
62
+ def to_wire(self) -> JsonObject:
63
+ """The issue as it appears in the error ``data`` member."""
64
+ return {"message": self.message, "path": list(self.path)}
65
+
66
+
67
+ @dataclass(frozen=True)
68
+ class RegisteredAction:
69
+ """An action the host has accepted, ready for the session to dispatch."""
70
+
71
+ descriptor: ActionDescriptor
72
+ dispatch: DispatchHandler
73
+
74
+
75
+ def to_json_value(value: object) -> JsonValue:
76
+ """Converts handler output into the JSON the invocation result carries.
77
+
78
+ Pydantic models, primitives, sequences, mappings, and enums are understood. Anything
79
+ else has no defined wire shape, so it fails as an internal error rather than reaching
80
+ the agent as a string of a repr.
81
+ """
82
+ if value is None or isinstance(value, bool | int | float | str):
83
+ return value
84
+ if isinstance(value, BaseModel):
85
+ converted: JsonValue = value.model_dump(mode="json")
86
+ return converted
87
+ if isinstance(value, Enum):
88
+ return to_json_value(value.value)
89
+ if isinstance(value, Mapping):
90
+ return {str(key): to_json_value(item) for key, item in value.items()}
91
+ if isinstance(value, Sequence):
92
+ return [to_json_value(item) for item in value]
93
+ raise ActionError.internal(
94
+ TypeError(f"an action returned {type(value).__name__}, which has no JSON form")
95
+ )
96
+
97
+
98
+ def issues_from_validation_error(error: ValidationError) -> list[ValidationIssue]:
99
+ """Normalises a Pydantic failure into the issue list a ``-32004`` failure carries."""
100
+ return [
101
+ ValidationIssue(message=detail["msg"], path=[str(segment) for segment in detail["loc"]])
102
+ for detail in error.errors()
103
+ ]
104
+
105
+
106
+ def input_validation_error(issues: list[ValidationIssue]) -> ActionError:
107
+ """The ``-32004`` failure for input that did not satisfy the declared schema."""
108
+ return ActionError.protocol(
109
+ TesseronErrorCode.INPUT_VALIDATION,
110
+ "Invalid input",
111
+ [issue.to_wire() for issue in issues],
112
+ )
113
+
114
+
115
+ def typed_dispatch(model: type[InputModel], handler: LooseHandler) -> DispatchHandler:
116
+ """Wraps a model-annotated handler so the session sees one raw-JSON entry point.
117
+
118
+ The model is validated before the handler body runs, so an action whose input does not
119
+ fit its declared shape never reaches application code.
120
+ """
121
+
122
+ async def dispatch(raw_input: JsonValue, context: ActionContext) -> JsonValue:
123
+ try:
124
+ parsed = model.model_validate(raw_input)
125
+ except ValidationError as problem:
126
+ raise input_validation_error(issues_from_validation_error(problem)) from problem
127
+ return to_json_value(await handler(parsed, context))
128
+
129
+ return dispatch
130
+
131
+
132
+ def raw_dispatch(handler: LooseHandler, validator: InputValidator | None) -> DispatchHandler:
133
+ """Wraps a raw-JSON handler, running the optional validator before the handler body."""
134
+
135
+ async def dispatch(raw_input: JsonValue, context: ActionContext) -> JsonValue:
136
+ if validator is not None:
137
+ issues = validator(raw_input)
138
+ if issues:
139
+ raise input_validation_error(issues)
140
+ return to_json_value(await handler(raw_input, context))
141
+
142
+ return dispatch