cavi-mcp-core 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.
- cavi_mcp_core-0.1.0/.gitignore +10 -0
- cavi_mcp_core-0.1.0/CHANGELOG.md +13 -0
- cavi_mcp_core-0.1.0/LICENSE +21 -0
- cavi_mcp_core-0.1.0/PKG-INFO +123 -0
- cavi_mcp_core-0.1.0/README.md +96 -0
- cavi_mcp_core-0.1.0/pyproject.toml +49 -0
- cavi_mcp_core-0.1.0/src/cavi_mcp_core/__init__.py +1 -0
- cavi_mcp_core-0.1.0/src/cavi_mcp_core/contracts.py +105 -0
- cavi_mcp_core-0.1.0/src/cavi_mcp_core/files.py +56 -0
- cavi_mcp_core-0.1.0/src/cavi_mcp_core/journal.py +66 -0
- cavi_mcp_core-0.1.0/src/cavi_mcp_core/proc.py +189 -0
- cavi_mcp_core-0.1.0/src/cavi_mcp_core/schema.py +111 -0
- cavi_mcp_core-0.1.0/src/cavi_mcp_core/server.py +128 -0
- cavi_mcp_core-0.1.0/tests/test_contracts.py +113 -0
- cavi_mcp_core-0.1.0/tests/test_files.py +71 -0
- cavi_mcp_core-0.1.0/tests/test_journal.py +67 -0
- cavi_mcp_core-0.1.0/tests/test_proc.py +377 -0
- cavi_mcp_core-0.1.0/tests/test_schema.py +53 -0
- cavi_mcp_core-0.1.0/tests/test_server.py +169 -0
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## Unreleased
|
|
4
|
+
|
|
5
|
+
## 0.1.0 - 2026-11-04
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- `Server` with compact tool schemas, anticipated-error reporting and one structured failure for every tool error, including unknown tools.
|
|
10
|
+
- `Result`, `VariantResult`, `OperationRejected`, `OperationUnknown` and `failure` result contracts.
|
|
11
|
+
- Schema compaction and variant validation helpers.
|
|
12
|
+
- Bounded subprocess runner with process-group termination.
|
|
13
|
+
- Workspace-confined bounded file reads and an atomic JSON operation journal.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Sasan Sotoodehfar
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: cavi-mcp-core
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Server type, result contracts, schemas, bounded processes and file journals for CAVI MCP servers
|
|
5
|
+
Project-URL: Homepage, https://github.com/cavi-ai/mcp-core#readme
|
|
6
|
+
Project-URL: Repository, https://github.com/cavi-ai/mcp-core
|
|
7
|
+
Project-URL: Issues, https://github.com/cavi-ai/mcp-core/issues
|
|
8
|
+
Project-URL: Changelog, https://github.com/cavi-ai/mcp-core/blob/main/CHANGELOG.md
|
|
9
|
+
Author: CAVI AI
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: mcp,mcp-server,model-context-protocol
|
|
13
|
+
Classifier: Development Status :: 3 - Alpha
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Operating System :: MacOS
|
|
16
|
+
Classifier: Operating System :: Microsoft :: Windows
|
|
17
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
18
|
+
Classifier: Programming Language :: Python :: 3
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
22
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
23
|
+
Requires-Python: >=3.11
|
|
24
|
+
Requires-Dist: mcp<3,>=2.3
|
|
25
|
+
Requires-Dist: pydantic<3,>=2.11
|
|
26
|
+
Description-Content-Type: text/markdown
|
|
27
|
+
|
|
28
|
+
# Cavi MCP Core
|
|
29
|
+
|
|
30
|
+
Shared plumbing for the CAVI MCP servers ([blender-mcp](https://github.com/cavi-ai/blender-mcp),
|
|
31
|
+
[substance-mcp](https://github.com/cavi-ai/substance-mcp),
|
|
32
|
+
[houdini-mcp](https://github.com/cavi-ai/houdini-mcp),
|
|
33
|
+
[adobe-mcp](https://github.com/cavi-ai/adobe-mcp)): one server type, one failure contract,
|
|
34
|
+
one schema compaction, one bounded process runner, bounded file reads and an operation
|
|
35
|
+
journal.
|
|
36
|
+
|
|
37
|
+
## Install
|
|
38
|
+
|
|
39
|
+
```sh
|
|
40
|
+
uv add cavi-mcp-core
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Requires Python 3.11+ and the MCP Python SDK 2.
|
|
44
|
+
|
|
45
|
+
## Server
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
from cavi_mcp_core.server import READ_ONLY, Server
|
|
49
|
+
|
|
50
|
+
mcp = Server("my-mcp", package="my-mcp", instructions="Inspect before editing.")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@mcp.tool(annotations=READ_ONLY)
|
|
54
|
+
async def status() -> dict:
|
|
55
|
+
return {"ready": True}
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
`Server` extends `mcp.server.mcpserver.MCPServer`:
|
|
59
|
+
|
|
60
|
+
- `package` sets the reported server version from that distribution's metadata.
|
|
61
|
+
- Tool schemas are compacted (`compact=False` keeps the SDK's schemas).
|
|
62
|
+
- `ValueError`, `RuntimeError` and `OSError` raised by a tool reach the caller with their
|
|
63
|
+
text; any other exception is logged on the server and reported without details. Pass
|
|
64
|
+
`anticipated=()` to leave tool errors to the SDK.
|
|
65
|
+
- Every tool error, including an unknown tool name, returns one structured result:
|
|
66
|
+
|
|
67
|
+
```json
|
|
68
|
+
{"error": {"version": 1, "code": "INVALID_ARGUMENT", "operation": "status",
|
|
69
|
+
"outcome": "rejected", "retry_safe": false, "next_action": "inspect_inputs"}}
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
`outcome` is `rejected` only for invalid arguments, missing inputs and unknown tools;
|
|
73
|
+
anything else is `unknown`, and `retry_safe` is always false. Raise
|
|
74
|
+
`contracts.OperationRejected(message, code)` or `contracts.OperationUnknown(message, code)`
|
|
75
|
+
to report a specific code. Override `Server.failure` to name a different recovery tool
|
|
76
|
+
for unknown outcomes.
|
|
77
|
+
|
|
78
|
+
`need(value, name, action)` and `reject_foreign(action, given, allowed)` validate
|
|
79
|
+
action-style arguments. `READ_ONLY`, `WRITES` and `DESTRUCTIVE` are the tool annotations.
|
|
80
|
+
|
|
81
|
+
## Contracts
|
|
82
|
+
|
|
83
|
+
`contracts.Result` is a strict pydantic model whose unset optional fields stay off the
|
|
84
|
+
wire. `contracts.VariantResult` accepts one of several declared field sets (`shapes`)
|
|
85
|
+
without a discriminator field.
|
|
86
|
+
|
|
87
|
+
## Schemas
|
|
88
|
+
|
|
89
|
+
`schema.compact_schema(schema, output=False)` returns a copy without titles or
|
|
90
|
+
`additionalProperties: true`, with equivalent union forms shortened, and validates the same
|
|
91
|
+
values; `output=True` also drops defaults, which are documentation only in a response.
|
|
92
|
+
`schema.validate_variant` and `schema.variant_schema` back `VariantResult`.
|
|
93
|
+
|
|
94
|
+
## Processes
|
|
95
|
+
|
|
96
|
+
`proc.run(args, timeout)` runs a command with bounded output and one deadline. On a
|
|
97
|
+
timeout or a cancellation it stops the whole process group (process tree on Windows) and
|
|
98
|
+
returns once the process exits. `proc.run_sync` is the blocking form and
|
|
99
|
+
`proc.diagnostics(result)` formats what a failed run printed.
|
|
100
|
+
|
|
101
|
+
## Files and journals
|
|
102
|
+
|
|
103
|
+
`files.inside(workspace, path)` resolves a path inside an existing workspace and refuses
|
|
104
|
+
`..`, escapes through symbolic links and the workspace root. `files.read_bytes`,
|
|
105
|
+
`files.load_json` and `files.digest` read bounded regular files and refuse a file that
|
|
106
|
+
changes while it is read; `files.parse_json` refuses NaN and Infinity.
|
|
107
|
+
|
|
108
|
+
`journal.write_json` replaces a JSON file atomically, durably and readable only by its
|
|
109
|
+
owner. `journal.completion` reads the completion receipt of one operation,
|
|
110
|
+
`journal.archive` records how an interrupted operation was resolved, and
|
|
111
|
+
`journal.fingerprint` hashes canonical JSON.
|
|
112
|
+
|
|
113
|
+
## Development
|
|
114
|
+
|
|
115
|
+
```sh
|
|
116
|
+
uv sync --locked --dev
|
|
117
|
+
uv run --locked python -m unittest discover -s tests
|
|
118
|
+
uv run --locked ruff check .
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
## License
|
|
122
|
+
|
|
123
|
+
MIT
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
# Cavi MCP Core
|
|
2
|
+
|
|
3
|
+
Shared plumbing for the CAVI MCP servers ([blender-mcp](https://github.com/cavi-ai/blender-mcp),
|
|
4
|
+
[substance-mcp](https://github.com/cavi-ai/substance-mcp),
|
|
5
|
+
[houdini-mcp](https://github.com/cavi-ai/houdini-mcp),
|
|
6
|
+
[adobe-mcp](https://github.com/cavi-ai/adobe-mcp)): one server type, one failure contract,
|
|
7
|
+
one schema compaction, one bounded process runner, bounded file reads and an operation
|
|
8
|
+
journal.
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
uv add cavi-mcp-core
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
Requires Python 3.11+ and the MCP Python SDK 2.
|
|
17
|
+
|
|
18
|
+
## Server
|
|
19
|
+
|
|
20
|
+
```python
|
|
21
|
+
from cavi_mcp_core.server import READ_ONLY, Server
|
|
22
|
+
|
|
23
|
+
mcp = Server("my-mcp", package="my-mcp", instructions="Inspect before editing.")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@mcp.tool(annotations=READ_ONLY)
|
|
27
|
+
async def status() -> dict:
|
|
28
|
+
return {"ready": True}
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
`Server` extends `mcp.server.mcpserver.MCPServer`:
|
|
32
|
+
|
|
33
|
+
- `package` sets the reported server version from that distribution's metadata.
|
|
34
|
+
- Tool schemas are compacted (`compact=False` keeps the SDK's schemas).
|
|
35
|
+
- `ValueError`, `RuntimeError` and `OSError` raised by a tool reach the caller with their
|
|
36
|
+
text; any other exception is logged on the server and reported without details. Pass
|
|
37
|
+
`anticipated=()` to leave tool errors to the SDK.
|
|
38
|
+
- Every tool error, including an unknown tool name, returns one structured result:
|
|
39
|
+
|
|
40
|
+
```json
|
|
41
|
+
{"error": {"version": 1, "code": "INVALID_ARGUMENT", "operation": "status",
|
|
42
|
+
"outcome": "rejected", "retry_safe": false, "next_action": "inspect_inputs"}}
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
`outcome` is `rejected` only for invalid arguments, missing inputs and unknown tools;
|
|
46
|
+
anything else is `unknown`, and `retry_safe` is always false. Raise
|
|
47
|
+
`contracts.OperationRejected(message, code)` or `contracts.OperationUnknown(message, code)`
|
|
48
|
+
to report a specific code. Override `Server.failure` to name a different recovery tool
|
|
49
|
+
for unknown outcomes.
|
|
50
|
+
|
|
51
|
+
`need(value, name, action)` and `reject_foreign(action, given, allowed)` validate
|
|
52
|
+
action-style arguments. `READ_ONLY`, `WRITES` and `DESTRUCTIVE` are the tool annotations.
|
|
53
|
+
|
|
54
|
+
## Contracts
|
|
55
|
+
|
|
56
|
+
`contracts.Result` is a strict pydantic model whose unset optional fields stay off the
|
|
57
|
+
wire. `contracts.VariantResult` accepts one of several declared field sets (`shapes`)
|
|
58
|
+
without a discriminator field.
|
|
59
|
+
|
|
60
|
+
## Schemas
|
|
61
|
+
|
|
62
|
+
`schema.compact_schema(schema, output=False)` returns a copy without titles or
|
|
63
|
+
`additionalProperties: true`, with equivalent union forms shortened, and validates the same
|
|
64
|
+
values; `output=True` also drops defaults, which are documentation only in a response.
|
|
65
|
+
`schema.validate_variant` and `schema.variant_schema` back `VariantResult`.
|
|
66
|
+
|
|
67
|
+
## Processes
|
|
68
|
+
|
|
69
|
+
`proc.run(args, timeout)` runs a command with bounded output and one deadline. On a
|
|
70
|
+
timeout or a cancellation it stops the whole process group (process tree on Windows) and
|
|
71
|
+
returns once the process exits. `proc.run_sync` is the blocking form and
|
|
72
|
+
`proc.diagnostics(result)` formats what a failed run printed.
|
|
73
|
+
|
|
74
|
+
## Files and journals
|
|
75
|
+
|
|
76
|
+
`files.inside(workspace, path)` resolves a path inside an existing workspace and refuses
|
|
77
|
+
`..`, escapes through symbolic links and the workspace root. `files.read_bytes`,
|
|
78
|
+
`files.load_json` and `files.digest` read bounded regular files and refuse a file that
|
|
79
|
+
changes while it is read; `files.parse_json` refuses NaN and Infinity.
|
|
80
|
+
|
|
81
|
+
`journal.write_json` replaces a JSON file atomically, durably and readable only by its
|
|
82
|
+
owner. `journal.completion` reads the completion receipt of one operation,
|
|
83
|
+
`journal.archive` records how an interrupted operation was resolved, and
|
|
84
|
+
`journal.fingerprint` hashes canonical JSON.
|
|
85
|
+
|
|
86
|
+
## Development
|
|
87
|
+
|
|
88
|
+
```sh
|
|
89
|
+
uv sync --locked --dev
|
|
90
|
+
uv run --locked python -m unittest discover -s tests
|
|
91
|
+
uv run --locked ruff check .
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
## License
|
|
95
|
+
|
|
96
|
+
MIT
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.27"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "cavi-mcp-core"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Server type, result contracts, schemas, bounded processes and file journals for CAVI MCP servers"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
authors = [{ name = "CAVI AI" }]
|
|
13
|
+
keywords = ["mcp", "model-context-protocol", "mcp-server"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 3 - Alpha",
|
|
16
|
+
"Intended Audience :: Developers",
|
|
17
|
+
"Operating System :: MacOS",
|
|
18
|
+
"Operating System :: Microsoft :: Windows",
|
|
19
|
+
"Operating System :: POSIX :: Linux",
|
|
20
|
+
"Programming Language :: Python :: 3",
|
|
21
|
+
"Programming Language :: Python :: 3.11",
|
|
22
|
+
"Programming Language :: Python :: 3.12",
|
|
23
|
+
"Programming Language :: Python :: 3.13",
|
|
24
|
+
"Topic :: Software Development :: Libraries",
|
|
25
|
+
]
|
|
26
|
+
requires-python = ">=3.11"
|
|
27
|
+
dependencies = ["mcp>=2.3,<3", "pydantic>=2.11,<3"]
|
|
28
|
+
|
|
29
|
+
[project.urls]
|
|
30
|
+
Homepage = "https://github.com/cavi-ai/mcp-core#readme"
|
|
31
|
+
Repository = "https://github.com/cavi-ai/mcp-core"
|
|
32
|
+
Issues = "https://github.com/cavi-ai/mcp-core/issues"
|
|
33
|
+
Changelog = "https://github.com/cavi-ai/mcp-core/blob/main/CHANGELOG.md"
|
|
34
|
+
|
|
35
|
+
[dependency-groups]
|
|
36
|
+
dev = ["ruff>=0.14,<1"]
|
|
37
|
+
|
|
38
|
+
[tool.hatch.build.targets.wheel]
|
|
39
|
+
packages = ["src/cavi_mcp_core"]
|
|
40
|
+
|
|
41
|
+
[tool.hatch.build.targets.sdist]
|
|
42
|
+
include = ["/src", "/tests", "/README.md", "/LICENSE", "/CHANGELOG.md", "/pyproject.toml"]
|
|
43
|
+
|
|
44
|
+
[tool.ruff]
|
|
45
|
+
line-length = 100
|
|
46
|
+
target-version = "py311"
|
|
47
|
+
|
|
48
|
+
[tool.ruff.lint]
|
|
49
|
+
select = ["E", "F", "I", "B", "UP", "SIM"]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Shared plumbing for CAVI MCP servers: server type, result contracts, schemas, processes."""
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""Response models and the structured failure every tool error reports."""
|
|
2
|
+
|
|
3
|
+
from typing import ClassVar
|
|
4
|
+
|
|
5
|
+
from mcp.server.mcpserver.exceptions import ToolError, UnexpectedToolError
|
|
6
|
+
from mcp.types import CallToolResult, TextContent
|
|
7
|
+
from pydantic import BaseModel, ConfigDict, ValidationError, model_serializer, model_validator
|
|
8
|
+
|
|
9
|
+
from .schema import validate_variant, variant_schema
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Result(BaseModel):
|
|
13
|
+
"""A tool result. Optional fields the tool did not set stay off the wire."""
|
|
14
|
+
|
|
15
|
+
model_config = ConfigDict(extra="allow", strict=True)
|
|
16
|
+
|
|
17
|
+
@model_serializer(mode="wrap")
|
|
18
|
+
def preserve_shape(self, handler):
|
|
19
|
+
present = set(self.model_fields_set)
|
|
20
|
+
for name in self.model_fields_set:
|
|
21
|
+
field = type(self).model_fields.get(name)
|
|
22
|
+
if field is not None and field.alias:
|
|
23
|
+
present.add(field.alias)
|
|
24
|
+
return {key: value for key, value in handler(self).items() if key in present}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class VariantResult(Result):
|
|
28
|
+
"""A result with several valid shapes, validated without adding a discriminator field."""
|
|
29
|
+
|
|
30
|
+
shapes: ClassVar[tuple[tuple[str, ...], ...]] = ()
|
|
31
|
+
nullable_shape_fields: ClassVar[frozenset[str]] = frozenset()
|
|
32
|
+
|
|
33
|
+
@model_validator(mode="before")
|
|
34
|
+
@classmethod
|
|
35
|
+
def require_shape(cls, value):
|
|
36
|
+
fields = {field.alias or name for name, field in cls.model_fields.items()}
|
|
37
|
+
return validate_variant(value, fields, cls.shapes, cls.nullable_shape_fields)
|
|
38
|
+
|
|
39
|
+
@classmethod
|
|
40
|
+
def __get_pydantic_json_schema__(cls, core_schema, handler):
|
|
41
|
+
return variant_schema(core_schema, handler, cls.shapes, cls.nullable_shape_fields)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class UnknownToolError(ToolError):
|
|
45
|
+
"""The requested name was absent before any tool execution."""
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class OperationRejected(ValueError):
|
|
49
|
+
"""Refused before any effect; ``error_code`` names the reason."""
|
|
50
|
+
|
|
51
|
+
def __init__(self, message, code="INVALID_ARGUMENT"):
|
|
52
|
+
super().__init__(message)
|
|
53
|
+
self.error_code = code
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class OperationUnknown(RuntimeError):
|
|
57
|
+
"""The effect may or may not have happened; inspect before any retry."""
|
|
58
|
+
|
|
59
|
+
def __init__(self, message, code="OUTCOME_UNKNOWN"):
|
|
60
|
+
super().__init__(message)
|
|
61
|
+
self.error_code = code
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def failure(name, error, unknown_next_action="inspect_application_and_outputs"):
|
|
65
|
+
"""The error result for ``error`` raised by tool ``name``; never authorizes a retry.
|
|
66
|
+
|
|
67
|
+
Only local validation, a missing input or a missing tool counts as rejected. Anything
|
|
68
|
+
else leaves the outcome unknown and points the caller at ``unknown_next_action``.
|
|
69
|
+
"""
|
|
70
|
+
cause = error
|
|
71
|
+
while (isinstance(cause, ToolError) and not isinstance(cause, UnexpectedToolError)
|
|
72
|
+
and cause.__cause__ is not None):
|
|
73
|
+
cause = cause.__cause__
|
|
74
|
+
missing_tool = isinstance(cause, UnknownToolError)
|
|
75
|
+
rejected = missing_tool or isinstance(cause, (ValueError, ValidationError, FileNotFoundError))
|
|
76
|
+
if isinstance(cause, (OperationRejected, OperationUnknown)):
|
|
77
|
+
code = cause.error_code
|
|
78
|
+
else:
|
|
79
|
+
code = (
|
|
80
|
+
"TOOL_NOT_FOUND"
|
|
81
|
+
if missing_tool
|
|
82
|
+
else "INVALID_ARGUMENT"
|
|
83
|
+
if isinstance(cause, (ValueError, ValidationError))
|
|
84
|
+
else "INPUT_NOT_FOUND"
|
|
85
|
+
if isinstance(cause, FileNotFoundError)
|
|
86
|
+
else "OUTCOME_UNKNOWN"
|
|
87
|
+
)
|
|
88
|
+
return CallToolResult(
|
|
89
|
+
isError=True,
|
|
90
|
+
content=[TextContent(type="text", text=str(error))],
|
|
91
|
+
structuredContent={
|
|
92
|
+
"error": {
|
|
93
|
+
"version": 1,
|
|
94
|
+
"code": code,
|
|
95
|
+
"operation": name,
|
|
96
|
+
"outcome": "rejected" if rejected else "unknown",
|
|
97
|
+
"retry_safe": False,
|
|
98
|
+
"next_action": "list_tools"
|
|
99
|
+
if missing_tool
|
|
100
|
+
else "inspect_inputs"
|
|
101
|
+
if rejected
|
|
102
|
+
else unknown_next_action,
|
|
103
|
+
}
|
|
104
|
+
},
|
|
105
|
+
)
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""Bounded, workspace-confined file reads shared by local tool workflows."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import stat
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def inside(workspace, value):
|
|
11
|
+
"""``value`` resolved inside ``workspace``; refuses traversal, escapes and the root itself."""
|
|
12
|
+
root = Path(workspace).resolve(strict=True)
|
|
13
|
+
path = Path(value)
|
|
14
|
+
if '..' in path.parts:
|
|
15
|
+
raise ValueError('Use workspace paths without parent traversal')
|
|
16
|
+
logical = Path(os.path.abspath(root / path))
|
|
17
|
+
resolved = logical.resolve()
|
|
18
|
+
if (not logical.is_relative_to(root) or not resolved.is_relative_to(root)
|
|
19
|
+
or resolved == root):
|
|
20
|
+
raise ValueError('Path must remain inside the shared workspace')
|
|
21
|
+
return resolved
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def read_bytes(path, limit):
|
|
25
|
+
"""A regular file's bytes, at most ``limit``; refuses a file that changes while read."""
|
|
26
|
+
descriptor = os.open(path, os.O_RDONLY | getattr(os, 'O_NONBLOCK', 0))
|
|
27
|
+
with os.fdopen(descriptor, 'rb') as stream:
|
|
28
|
+
before = os.fstat(stream.fileno())
|
|
29
|
+
if not stat.S_ISREG(before.st_mode) or before.st_size > limit:
|
|
30
|
+
raise ValueError('Expected a bounded regular file')
|
|
31
|
+
data = stream.read(limit + 1)
|
|
32
|
+
after = os.fstat(stream.fileno())
|
|
33
|
+
current = Path(path).stat()
|
|
34
|
+
if (len(data) > limit or (before.st_size, before.st_mtime_ns, before.st_ino)
|
|
35
|
+
!= (after.st_size, after.st_mtime_ns, after.st_ino)
|
|
36
|
+
or (current.st_size, current.st_mtime_ns, current.st_ino)
|
|
37
|
+
!= (after.st_size, after.st_mtime_ns, after.st_ino)):
|
|
38
|
+
raise ValueError('Input changed while reading')
|
|
39
|
+
return data
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def digest(path):
|
|
43
|
+
"""SHA-256 of a regular file of at most 64 MiB."""
|
|
44
|
+
return hashlib.sha256(read_bytes(path, 64 * 1024 * 1024)).hexdigest()
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def parse_json(raw):
|
|
48
|
+
"""JSON without NaN or Infinity."""
|
|
49
|
+
def invalid(value):
|
|
50
|
+
raise ValueError('Non-finite JSON number: ' + value)
|
|
51
|
+
return json.loads(raw, parse_constant=invalid)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def load_json(path):
|
|
55
|
+
"""``parse_json`` of a regular file of at most 1 MiB."""
|
|
56
|
+
return parse_json(read_bytes(path, 1024 * 1024))
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""Durable JSON state and retained native completion receipts."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import uuid
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def write_json(path, value):
|
|
11
|
+
"""Replace ``path`` with ``value`` atomically and durably; the file is private to the user."""
|
|
12
|
+
path = Path(path)
|
|
13
|
+
temporary = path.with_name("." + uuid.uuid4().hex + ".tmp")
|
|
14
|
+
descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
15
|
+
try:
|
|
16
|
+
with os.fdopen(descriptor, "w") as stream:
|
|
17
|
+
json.dump(value, stream, indent=2, allow_nan=False)
|
|
18
|
+
stream.flush()
|
|
19
|
+
os.fsync(stream.fileno())
|
|
20
|
+
os.replace(temporary, path)
|
|
21
|
+
# Windows cannot open a directory to flush it; NTFS journals the rename itself.
|
|
22
|
+
if os.name != "nt":
|
|
23
|
+
parent = os.open(path.parent, os.O_RDONLY)
|
|
24
|
+
try:
|
|
25
|
+
os.fsync(parent)
|
|
26
|
+
finally:
|
|
27
|
+
os.close(parent)
|
|
28
|
+
finally:
|
|
29
|
+
temporary.unlink(missing_ok=True)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def fingerprint(value):
|
|
33
|
+
"""SHA-256 of ``value`` as canonical JSON."""
|
|
34
|
+
return hashlib.sha256(
|
|
35
|
+
json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()
|
|
36
|
+
).hexdigest()
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def completion(path, operation_id):
|
|
40
|
+
"""The completion receipt for ``operation_id`` at ``path``, or None before it exists."""
|
|
41
|
+
path = Path(path)
|
|
42
|
+
if path.is_symlink() or path.parent.is_symlink():
|
|
43
|
+
raise ValueError("Native receipt must not be a symbolic link")
|
|
44
|
+
if not path.exists():
|
|
45
|
+
return None
|
|
46
|
+
if not path.is_file() or not 1 <= path.stat().st_size <= 8 * 1024 * 1024:
|
|
47
|
+
raise ValueError("Native completion receipt is missing, unsafe or too large")
|
|
48
|
+
value = json.loads(path.read_text())
|
|
49
|
+
if (
|
|
50
|
+
not isinstance(value, dict)
|
|
51
|
+
or value.get("operation_id") != operation_id
|
|
52
|
+
or type(value.get("ok")) is not bool
|
|
53
|
+
):
|
|
54
|
+
raise ValueError("Native completion receipt does not match the operation")
|
|
55
|
+
return value
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def archive(path, record, resolution):
|
|
59
|
+
"""Record how an interrupted operation was resolved; repeating the same record is a no-op."""
|
|
60
|
+
path = Path(path)
|
|
61
|
+
value = {"prior_operation": record, **resolution}
|
|
62
|
+
if path.exists():
|
|
63
|
+
if json.loads(path.read_text()) != value:
|
|
64
|
+
raise ValueError("Recovery record already exists with a different outcome")
|
|
65
|
+
return
|
|
66
|
+
write_json(path, value)
|