sandcrab 0.3.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.
sandcrab-0.3.0/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,197 @@
1
+ Metadata-Version: 2.4
2
+ Name: sandcrab
3
+ Version: 0.3.0
4
+ Summary: Native Python client, template workflows, host-call dispatcher and stdio MCP server for Sandcrab
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Repository, https://github.com/core607/sandcrab
7
+ Project-URL: Documentation, https://github.com/core607/sandcrab/tree/main/sdk/python
8
+ Requires-Python: >=3.11
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Requires-Dist: httpx<1,>=0.28.1
12
+ Dynamic: license-file
13
+
14
+ # Sandcrab Python SDK and MCP server
15
+
16
+ The `sandcrab` package provides synchronous and asynchronous clients for Sandcrab's
17
+ native control API (`SandcrabClient`, `AsyncSandcrabClient`), declarative caller-side
18
+ host-call dispatch (`HostCallDispatcher`, `AsyncHostCallDispatcher`), a standard-library
19
+ JSON-RPC 2.0 stdio MCP server (`sandcrab-mcp`), and the `sandcrab_templates` extension
20
+ used alongside the published OpenSandbox SDK. It requires Python 3.11+ and `httpx>=0.28.1,<1`.
21
+
22
+ ## Run your first session
23
+
24
+ Run this example on the Linux host where Sandcrab is installed. Use the application
25
+ account that owns the token from the [service setup](https://github.com/core607/sandcrab#cookbook).
26
+ In an empty directory, create a virtual environment. Use the PyPI command below
27
+ for a published version. For a version awaiting publication, give pip the
28
+ absolute path to `sdk/python` in the [matching checkout](https://github.com/core607/sandcrab/tree/v0.3.0)
29
+ in place of `sandcrab==0.3.0`.
30
+
31
+ ```sh
32
+ python3 -m venv .venv
33
+ .venv/bin/python -m pip install sandcrab==0.3.0
34
+ ```
35
+
36
+ Save this as `example.py`.
37
+
38
+ ```python
39
+ from sandcrab import SandcrabClient
40
+
41
+ with SandcrabClient(
42
+ endpoint="http://127.0.0.1:9011",
43
+ token_file="/etc/sandcrab-client/token",
44
+ default_profile="default",
45
+ ) as client:
46
+ with client.open_session() as session:
47
+ session.write_file("src/main.py", "print(6 * 7)\n", parents=True)
48
+ session.exec("python3 src/main.py > answer.txt", check=True)
49
+ print(session.read_text("answer.txt").strip())
50
+ ```
51
+
52
+ Run the example. It prints `42` and closes and forgets the session on exit.
53
+
54
+ ```sh
55
+ .venv/bin/python example.py
56
+ ```
57
+
58
+ ## Native client
59
+
60
+ Connect over a root-owned Unix control socket or a literal loopback HTTP endpoint with a
61
+ 64-hex service token. Redirects and environment proxies are disabled. When neither
62
+ `socket_path` nor `endpoint` is passed, the client reads `SANDCRAB_SOCKET` or
63
+ `SANDCRAB_ENDPOINT` (plus `SANDCRAB_TOKEN_FILE` and `SANDCRAB_PROFILE`), and refuses
64
+ implicit selection if both transport variables are set.
65
+
66
+ Exiting `with client.open_session() as session:` (or `async with await client.open_session()`)
67
+ closes and forgets the session unless `keep_result=True` or `auto_close=False` is set.
68
+ `run()` and `session.exec()` stream output when `on_output` is supplied, forget completed
69
+ records unless `keep_result=True`, and raise `CommandFailedError` when `check=True` and
70
+ the command does not succeed.
71
+
72
+ If transport fails after submitting a mutating request (`submit_run`, `open_session`,
73
+ `submit_session_command`, `create_volume`), the client raises `TransportUncertainError`
74
+ carrying `recovery_id` and never reposts under a new ID.
75
+
76
+ Workspace file helpers (`write_file`, `read_file`, `read_text`, `mkdir`, `list_files`,
77
+ `search_files`, `remove_file`, `diff`, `snapshot`) enforce normalized relative paths,
78
+ verify `ETag` digests on complete downloads, and support HTTP byte ranges (`byte_range`)
79
+ or 1-based line ranges (`offset`, `limit`). `import_template()` streams plain `.tar`
80
+ archives directly and gunzips `.tar.gz` / `.tgz` archives on the client before sending
81
+ bounded `application/x-tar` bytes.
82
+
83
+ ## Caller-owned host calls
84
+
85
+ `HostCallDispatcher` and `AsyncHostCallDispatcher` run handlers in the caller's process
86
+ while Sandcrab relays opaque bytes; see [host calls](https://github.com/core607/sandcrab/blob/main/crates/sandcrab/host-calls.md).
87
+
88
+ ```python
89
+ import hashlib, hmac
90
+ from sandcrab import HostCallDispatcher, SandcrabClient
91
+
92
+ dispatcher = HostCallDispatcher()
93
+
94
+ @dispatcher.on_json("sign-sha256")
95
+ def sign_digest(request: dict, context) -> dict:
96
+ digest = request["digest"]
97
+ if digest != expected_digest:
98
+ raise PermissionError("outside build grant")
99
+ sig = hmac.new(signing_key, bytes.fromhex(digest), hashlib.sha256).hexdigest()
100
+ return {"digest": digest, "signature": sig}
101
+
102
+ with SandcrabClient(socket_path="/run/sandcrab/sandcrab.sock", default_profile="python") as client:
103
+ client.run(["python3", "build_and_sign.py"], dispatcher=dispatcher, check=True)
104
+ ```
105
+
106
+ Each event's `requestSha256` and serving epoch are checked before invoking a handler.
107
+ Dispatchers sharing an `InMemoryReplyLedger` share the result of overlapping
108
+ observations of the same `(run_id, call_id)` and reject changed payloads. With a
109
+ custom ledger, share one dispatcher to coordinate concurrent calls. For durable
110
+ external effects, record the reply in the transaction that commits the effect.
111
+ Any unhandled handler exception cancels the sandbox
112
+ command and leaves its record retained for inspection.
113
+
114
+ ## Stdio MCP server
115
+
116
+ `sandcrab-mcp` (or [examples/sandcrab-mcp.py](https://github.com/core607/sandcrab/blob/main/examples/sandcrab-mcp.py)) serves
117
+ MCP `2024-11-05` and `2025-03-26` JSON-RPC 2.0 over stdio using only the Python standard
118
+ library alongside `SandcrabClient`:
119
+
120
+ ```sh
121
+ sandcrab-mcp --endpoint http://127.0.0.1:9011 --token-file /etc/sandcrab-client/token --profile default
122
+ ```
123
+
124
+ Exposed tools are bounded to sandbox execution and workspace-relative files:
125
+ `sandcrab_run`, `sandcrab_session_open`, `sandcrab_session_exec`,
126
+ `sandcrab_session_close`, `sandcrab_write_file`, `sandcrab_read_file`, `sandcrab_mkdir`,
127
+ `sandcrab_list_files`, and `sandcrab_search_files`. File tool payloads are capped at
128
+ 1 MiB per call; larger files require `offset`/`limit` or `byte_range`. Sessions opened
129
+ through MCP are closed and forgotten automatically when stdin closes.
130
+
131
+ ## Template publication alongside OpenSandbox (`sandcrab_templates`)
132
+
133
+ `sandcrab_templates` remains importable directly (and re-exported from `sandcrab`) for
134
+ filesystem capture and immutable publication beside the published OpenSandbox SDK.
135
+ From a source checkout, install both for the examples below.
136
+
137
+ ```sh
138
+ python -m pip install ./sdk/python -r evals/sdk/requirements.txt
139
+ ```
140
+
141
+ Create an authenticated `TemplateClient` with the literal loopback endpoint and service
142
+ token used by the OpenSandbox connection:
143
+
144
+ ```python
145
+ async with TemplateClient("http://127.0.0.1:9011", token) as templates:
146
+ checkpoint = await templates.capture(sandbox.id, "prepared.tar")
147
+ # The builder may now be killed and its client closed.
148
+ template = await templates.publish(checkpoint)
149
+ fresh = await Sandbox.create(checkpoint.image, connection_config=config,
150
+ timeout=timedelta(seconds=60),
151
+ resource={"cpu": "0.25", "memory": "32Mi"})
152
+ ```
153
+
154
+ Prepare and validate files before capture. `checkpoint.image` selects a rootfs
155
+ template in OpenSandbox; workspace captures use native session `templateId`.
156
+ The [native reference](https://github.com/core607/sandcrab/blob/main/crates/sandcrab/README.md#filesystem-capture) owns
157
+ freeze semantics, supported metadata, limits and omitted runtime state.
158
+ `Checkpoint.to_dict()` and `Checkpoint.from_dict()` save and load a trusted local
159
+ receipt; keep it with the captured archive outside the sandbox.
160
+
161
+ Capture checks the serving epoch, profile, filesystem kind, byte length and SHA-256
162
+ before atomically installing a new file without replacing an existing destination
163
+ (mode 0600 on POSIX). Cancellation closes the response and removes partial staging;
164
+ capture never publishes a template.
165
+
166
+ Publication verifies the local archive and sends `expectedId` to the server. Existing
167
+ matching objects are reused. After a lost transport reply, the client performs one read
168
+ to reconcile that ID and never reposts automatically; if absent, `PublicationUncertain`
169
+ carries its ID and `await templates.reconcile(checkpoint)` checks visibility later.
170
+
171
+ The [independent environment example](https://github.com/core607/sandcrab/blob/main/examples/sandcrab-environment.py) builds,
172
+ validates, captures, publishes, and starts two independent instances:
173
+
174
+ ```sh
175
+ python examples/sandcrab-environment.py --base-image PROFILE@sha256:ID \
176
+ --token-file ./client.token --archive ./prepared.tar --receipt ./prepared.json
177
+ ```
178
+
179
+ Compose independently imported layers with `await templates.compose([base_id,
180
+ toolkit_id, workspace_id])`; the [native recipe
181
+ contract](https://github.com/core607/sandcrab/blob/main/crates/sandcrab/README.md#composable-recipes) owns ordering, whiteouts,
182
+ limits and reference lifetimes. `recipe_id(layers)` computes the expected ID locally, and
183
+ [examples/sandcrab-recipe.py](https://github.com/core607/sandcrab/blob/main/examples/sandcrab-recipe.py) validates composed layers:
184
+
185
+ ```sh
186
+ python examples/sandcrab-recipe.py --token-file ./client.token --profile default \
187
+ --validate 'bash /workspace/test.sh' BASE_ID TOOLKIT_ID WORKSPACE_ID
188
+ ```
189
+
190
+ ## Development
191
+
192
+ Run the SDK checks from the repository root.
193
+
194
+ ```sh
195
+ python -m pip install ./sdk/python
196
+ python -m unittest discover -s sdk/python/tests -v
197
+ ```
@@ -0,0 +1,184 @@
1
+ # Sandcrab Python SDK and MCP server
2
+
3
+ The `sandcrab` package provides synchronous and asynchronous clients for Sandcrab's
4
+ native control API (`SandcrabClient`, `AsyncSandcrabClient`), declarative caller-side
5
+ host-call dispatch (`HostCallDispatcher`, `AsyncHostCallDispatcher`), a standard-library
6
+ JSON-RPC 2.0 stdio MCP server (`sandcrab-mcp`), and the `sandcrab_templates` extension
7
+ used alongside the published OpenSandbox SDK. It requires Python 3.11+ and `httpx>=0.28.1,<1`.
8
+
9
+ ## Run your first session
10
+
11
+ Run this example on the Linux host where Sandcrab is installed. Use the application
12
+ account that owns the token from the [service setup](https://github.com/core607/sandcrab#cookbook).
13
+ In an empty directory, create a virtual environment. Use the PyPI command below
14
+ for a published version. For a version awaiting publication, give pip the
15
+ absolute path to `sdk/python` in the [matching checkout](https://github.com/core607/sandcrab/tree/v0.3.0)
16
+ in place of `sandcrab==0.3.0`.
17
+
18
+ ```sh
19
+ python3 -m venv .venv
20
+ .venv/bin/python -m pip install sandcrab==0.3.0
21
+ ```
22
+
23
+ Save this as `example.py`.
24
+
25
+ ```python
26
+ from sandcrab import SandcrabClient
27
+
28
+ with SandcrabClient(
29
+ endpoint="http://127.0.0.1:9011",
30
+ token_file="/etc/sandcrab-client/token",
31
+ default_profile="default",
32
+ ) as client:
33
+ with client.open_session() as session:
34
+ session.write_file("src/main.py", "print(6 * 7)\n", parents=True)
35
+ session.exec("python3 src/main.py > answer.txt", check=True)
36
+ print(session.read_text("answer.txt").strip())
37
+ ```
38
+
39
+ Run the example. It prints `42` and closes and forgets the session on exit.
40
+
41
+ ```sh
42
+ .venv/bin/python example.py
43
+ ```
44
+
45
+ ## Native client
46
+
47
+ Connect over a root-owned Unix control socket or a literal loopback HTTP endpoint with a
48
+ 64-hex service token. Redirects and environment proxies are disabled. When neither
49
+ `socket_path` nor `endpoint` is passed, the client reads `SANDCRAB_SOCKET` or
50
+ `SANDCRAB_ENDPOINT` (plus `SANDCRAB_TOKEN_FILE` and `SANDCRAB_PROFILE`), and refuses
51
+ implicit selection if both transport variables are set.
52
+
53
+ Exiting `with client.open_session() as session:` (or `async with await client.open_session()`)
54
+ closes and forgets the session unless `keep_result=True` or `auto_close=False` is set.
55
+ `run()` and `session.exec()` stream output when `on_output` is supplied, forget completed
56
+ records unless `keep_result=True`, and raise `CommandFailedError` when `check=True` and
57
+ the command does not succeed.
58
+
59
+ If transport fails after submitting a mutating request (`submit_run`, `open_session`,
60
+ `submit_session_command`, `create_volume`), the client raises `TransportUncertainError`
61
+ carrying `recovery_id` and never reposts under a new ID.
62
+
63
+ Workspace file helpers (`write_file`, `read_file`, `read_text`, `mkdir`, `list_files`,
64
+ `search_files`, `remove_file`, `diff`, `snapshot`) enforce normalized relative paths,
65
+ verify `ETag` digests on complete downloads, and support HTTP byte ranges (`byte_range`)
66
+ or 1-based line ranges (`offset`, `limit`). `import_template()` streams plain `.tar`
67
+ archives directly and gunzips `.tar.gz` / `.tgz` archives on the client before sending
68
+ bounded `application/x-tar` bytes.
69
+
70
+ ## Caller-owned host calls
71
+
72
+ `HostCallDispatcher` and `AsyncHostCallDispatcher` run handlers in the caller's process
73
+ while Sandcrab relays opaque bytes; see [host calls](https://github.com/core607/sandcrab/blob/main/crates/sandcrab/host-calls.md).
74
+
75
+ ```python
76
+ import hashlib, hmac
77
+ from sandcrab import HostCallDispatcher, SandcrabClient
78
+
79
+ dispatcher = HostCallDispatcher()
80
+
81
+ @dispatcher.on_json("sign-sha256")
82
+ def sign_digest(request: dict, context) -> dict:
83
+ digest = request["digest"]
84
+ if digest != expected_digest:
85
+ raise PermissionError("outside build grant")
86
+ sig = hmac.new(signing_key, bytes.fromhex(digest), hashlib.sha256).hexdigest()
87
+ return {"digest": digest, "signature": sig}
88
+
89
+ with SandcrabClient(socket_path="/run/sandcrab/sandcrab.sock", default_profile="python") as client:
90
+ client.run(["python3", "build_and_sign.py"], dispatcher=dispatcher, check=True)
91
+ ```
92
+
93
+ Each event's `requestSha256` and serving epoch are checked before invoking a handler.
94
+ Dispatchers sharing an `InMemoryReplyLedger` share the result of overlapping
95
+ observations of the same `(run_id, call_id)` and reject changed payloads. With a
96
+ custom ledger, share one dispatcher to coordinate concurrent calls. For durable
97
+ external effects, record the reply in the transaction that commits the effect.
98
+ Any unhandled handler exception cancels the sandbox
99
+ command and leaves its record retained for inspection.
100
+
101
+ ## Stdio MCP server
102
+
103
+ `sandcrab-mcp` (or [examples/sandcrab-mcp.py](https://github.com/core607/sandcrab/blob/main/examples/sandcrab-mcp.py)) serves
104
+ MCP `2024-11-05` and `2025-03-26` JSON-RPC 2.0 over stdio using only the Python standard
105
+ library alongside `SandcrabClient`:
106
+
107
+ ```sh
108
+ sandcrab-mcp --endpoint http://127.0.0.1:9011 --token-file /etc/sandcrab-client/token --profile default
109
+ ```
110
+
111
+ Exposed tools are bounded to sandbox execution and workspace-relative files:
112
+ `sandcrab_run`, `sandcrab_session_open`, `sandcrab_session_exec`,
113
+ `sandcrab_session_close`, `sandcrab_write_file`, `sandcrab_read_file`, `sandcrab_mkdir`,
114
+ `sandcrab_list_files`, and `sandcrab_search_files`. File tool payloads are capped at
115
+ 1 MiB per call; larger files require `offset`/`limit` or `byte_range`. Sessions opened
116
+ through MCP are closed and forgotten automatically when stdin closes.
117
+
118
+ ## Template publication alongside OpenSandbox (`sandcrab_templates`)
119
+
120
+ `sandcrab_templates` remains importable directly (and re-exported from `sandcrab`) for
121
+ filesystem capture and immutable publication beside the published OpenSandbox SDK.
122
+ From a source checkout, install both for the examples below.
123
+
124
+ ```sh
125
+ python -m pip install ./sdk/python -r evals/sdk/requirements.txt
126
+ ```
127
+
128
+ Create an authenticated `TemplateClient` with the literal loopback endpoint and service
129
+ token used by the OpenSandbox connection:
130
+
131
+ ```python
132
+ async with TemplateClient("http://127.0.0.1:9011", token) as templates:
133
+ checkpoint = await templates.capture(sandbox.id, "prepared.tar")
134
+ # The builder may now be killed and its client closed.
135
+ template = await templates.publish(checkpoint)
136
+ fresh = await Sandbox.create(checkpoint.image, connection_config=config,
137
+ timeout=timedelta(seconds=60),
138
+ resource={"cpu": "0.25", "memory": "32Mi"})
139
+ ```
140
+
141
+ Prepare and validate files before capture. `checkpoint.image` selects a rootfs
142
+ template in OpenSandbox; workspace captures use native session `templateId`.
143
+ The [native reference](https://github.com/core607/sandcrab/blob/main/crates/sandcrab/README.md#filesystem-capture) owns
144
+ freeze semantics, supported metadata, limits and omitted runtime state.
145
+ `Checkpoint.to_dict()` and `Checkpoint.from_dict()` save and load a trusted local
146
+ receipt; keep it with the captured archive outside the sandbox.
147
+
148
+ Capture checks the serving epoch, profile, filesystem kind, byte length and SHA-256
149
+ before atomically installing a new file without replacing an existing destination
150
+ (mode 0600 on POSIX). Cancellation closes the response and removes partial staging;
151
+ capture never publishes a template.
152
+
153
+ Publication verifies the local archive and sends `expectedId` to the server. Existing
154
+ matching objects are reused. After a lost transport reply, the client performs one read
155
+ to reconcile that ID and never reposts automatically; if absent, `PublicationUncertain`
156
+ carries its ID and `await templates.reconcile(checkpoint)` checks visibility later.
157
+
158
+ The [independent environment example](https://github.com/core607/sandcrab/blob/main/examples/sandcrab-environment.py) builds,
159
+ validates, captures, publishes, and starts two independent instances:
160
+
161
+ ```sh
162
+ python examples/sandcrab-environment.py --base-image PROFILE@sha256:ID \
163
+ --token-file ./client.token --archive ./prepared.tar --receipt ./prepared.json
164
+ ```
165
+
166
+ Compose independently imported layers with `await templates.compose([base_id,
167
+ toolkit_id, workspace_id])`; the [native recipe
168
+ contract](https://github.com/core607/sandcrab/blob/main/crates/sandcrab/README.md#composable-recipes) owns ordering, whiteouts,
169
+ limits and reference lifetimes. `recipe_id(layers)` computes the expected ID locally, and
170
+ [examples/sandcrab-recipe.py](https://github.com/core607/sandcrab/blob/main/examples/sandcrab-recipe.py) validates composed layers:
171
+
172
+ ```sh
173
+ python examples/sandcrab-recipe.py --token-file ./client.token --profile default \
174
+ --validate 'bash /workspace/test.sh' BASE_ID TOOLKIT_ID WORKSPACE_ID
175
+ ```
176
+
177
+ ## Development
178
+
179
+ Run the SDK checks from the repository root.
180
+
181
+ ```sh
182
+ python -m pip install ./sdk/python
183
+ python -m unittest discover -s sdk/python/tests -v
184
+ ```
@@ -0,0 +1,23 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "sandcrab"
7
+ version = "0.3.0"
8
+ description = "Native Python client, template workflows, host-call dispatcher and stdio MCP server for Sandcrab"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ dependencies = ["httpx>=0.28.1,<1"]
12
+ license = "Apache-2.0"
13
+ license-files = ["LICENSE"]
14
+
15
+ [project.urls]
16
+ Repository = "https://github.com/core607/sandcrab"
17
+ Documentation = "https://github.com/core607/sandcrab/tree/main/sdk/python"
18
+
19
+ [project.scripts]
20
+ sandcrab-mcp = "sandcrab.mcp:main"
21
+
22
+ [tool.setuptools.packages.find]
23
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,46 @@
1
+ """Native Python client, template helpers, host-call dispatchers and stdio MCP server for Sandcrab."""
2
+ from sandcrab_templates import (
3
+ Checkpoint,
4
+ PublicationUncertain,
5
+ TemplateClient,
6
+ TemplateError,
7
+ recipe_id,
8
+ )
9
+
10
+ from .calls import (
11
+ AsyncHostCallDispatcher,
12
+ CallContext,
13
+ HostCallDispatcher,
14
+ InMemoryReplyLedger,
15
+ ReplyLedger,
16
+ )
17
+ from .client import AsyncSandcrabClient, AsyncSession, SandcrabClient, Session
18
+ from .errors import (
19
+ CommandFailedError,
20
+ ProtocolError,
21
+ SandcrabError,
22
+ TransportUncertainError,
23
+ )
24
+ from .mcp import SandcrabMcpServer
25
+
26
+ __all__ = [
27
+ "AsyncHostCallDispatcher",
28
+ "AsyncSandcrabClient",
29
+ "AsyncSession",
30
+ "CallContext",
31
+ "Checkpoint",
32
+ "CommandFailedError",
33
+ "HostCallDispatcher",
34
+ "InMemoryReplyLedger",
35
+ "ProtocolError",
36
+ "PublicationUncertain",
37
+ "ReplyLedger",
38
+ "SandcrabClient",
39
+ "SandcrabError",
40
+ "SandcrabMcpServer",
41
+ "Session",
42
+ "TemplateClient",
43
+ "TemplateError",
44
+ "TransportUncertainError",
45
+ "recipe_id",
46
+ ]
@@ -0,0 +1,5 @@
1
+ """CLI module entrypoint (`python3 -m sandcrab.mcp` or `python3 -m sandcrab`)."""
2
+ from .mcp import main
3
+
4
+ if __name__ == "__main__":
5
+ raise SystemExit(main())