microcld 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,14 @@
1
+ /target/
2
+ **/target/
3
+ *.key
4
+ *.csr
5
+ *.srl
6
+
7
+ # Артефакты сборки образа и ядра (images/build-*.sh)
8
+ /images/out/
9
+ # Python (sdk/python)
10
+ .venv/
11
+ __pycache__/
12
+ *.egg-info/
13
+ .pytest_cache/
14
+ dist/
microcld-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 microcloud
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,207 @@
1
+ Metadata-Version: 2.5
2
+ Name: microcld
3
+ Version: 0.1.0
4
+ Summary: Python SDK and CLI for microcloud: hosting (apps, Postgres, S3 buckets) and sandboxes for AI agents
5
+ Project-URL: Homepage, https://microcloud.mn
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Keywords: ai-agents,cli,hosting,microvm,sandbox
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Requires-Python: >=3.10
13
+ Requires-Dist: httpx>=0.27
14
+ Provides-Extra: dev
15
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
16
+ Requires-Dist: pytest>=8; extra == 'dev'
17
+ Description-Content-Type: text/markdown
18
+
19
+ # microcld
20
+
21
+ Python SDK and CLI for [microcloud](https://microcloud.mn): hosting (apps,
22
+ managed Postgres, S3 buckets) and sandboxes for AI agents — isolated
23
+ micro-VMs that start in a fraction of a second, run code, sleep for free and
24
+ clone with their whole state. Execution and data stay in Mongolia.
25
+
26
+ ```bash
27
+ pip install microcld
28
+ export SANDBOX_API_KEY=mc_... # organization API key
29
+ export SANDBOX_API_URL=http://127.0.0.1:7900 # your API endpoint (this is the default)
30
+ ```
31
+
32
+ ```python
33
+ from microcld import Sandbox
34
+
35
+ with Sandbox.create(cpus=1, memory_mb=512, egress="none") as sb: # deleted on exit
36
+ sb.files.write("/tmp/data.csv", "a,b\n1,2\n3,4\n")
37
+ r = sb.exec("awk -F, 'NR>1 {s+=$2} END {print s}' /tmp/data.csv")
38
+ print(r.check().stdout) # 6; check() raises CommandError if the exit code is not 0
39
+
40
+ sb.sleep() # memory goes to a snapshot, not billed
41
+ sb.wake() # ~0.1 s, everything is still there
42
+ with sb.fork() as clone: # a clone with memory and disk - try another path
43
+ clone.exec("rm /tmp/data.csv")
44
+ print(sb.files.read_text("/tmp/data.csv")) # the original is intact
45
+ ```
46
+
47
+ ## Code interpreter (`python` template)
48
+
49
+ Stateful Python, like a Jupyter kernel: variables and imports live between
50
+ calls, the last expression is returned, plots come back as images.
51
+
52
+ ```python
53
+ with Sandbox.create(template="python", memory_mb=1024) as sb:
54
+ sb.files.write("/work/sales.csv", open("sales.csv", "rb").read())
55
+ sb.run_code("import pandas as pd\ndf = pd.read_csv('sales.csv')")
56
+ r = sb.run_code("df.describe()")
57
+ print(r.result) # repr of the last expression
58
+ r = sb.run_code("df.plot(); import matplotlib.pyplot as plt; plt.title('Sales')")
59
+ open("plot.png", "wb").write(r.images[0]) # PNG
60
+ r = sb.run_code("df.nope")
61
+ print(r.ok, r.error.name) # False AttributeError - an error in the result, not an exception
62
+ ```
63
+
64
+ `CodeResult`: `stdout`, `stderr`, `result`, `error` (`name`, `value`,
65
+ `traceback`), `images` (PNG bytes), `duration_ms`, `.ok`, `.text` (all text
66
+ together - handy to return to a model as a tool result). `timeout`
67
+ interrupts the code but keeps the state; `reset_code()` clears it. The state
68
+ survives `sleep`/`wake` and is copied by `fork()`. A template without an
69
+ interpreter raises `InterpreterError`.
70
+
71
+ Async works the same way, with `await`:
72
+
73
+ ```python
74
+ from microcld import AsyncSandbox
75
+
76
+ async with await AsyncSandbox.create() as sb:
77
+ r = await sb.exec("echo hi")
78
+ ```
79
+
80
+ ## Tools for AI agents (function calling)
81
+
82
+ A sandbox as a set of model tools: `run_python` (stateful interpreter),
83
+ `run_shell`, `read_file`, `write_file`. Definitions fit the Anthropic
84
+ Messages API (`strict: true`) and OpenAI-compatible function calling; the
85
+ handler runs the call in the sandbox and returns a ready result. Errors
86
+ (code crashed, no such file) go back to the model with `is_error` instead
87
+ of raising, so the agent sees them and corrects itself. Plots from
88
+ `run_python` and images from `read_file` are returned as image blocks (the
89
+ model sees them). Output is truncated (`max_output`, 20,000 characters).
90
+
91
+ ```python
92
+ from microcld import Sandbox, tools
93
+
94
+ sb = Sandbox.create(template="python", egress="none")
95
+ t = tools.for_sandbox(sb) # or enabled=["run_python"], timeout=..., max_output=...
96
+
97
+ response = client.messages.create(model="claude-opus-5-5", max_tokens=16000,
98
+ tools=t.anthropic(), messages=messages)
99
+ messages.append({"role": "assistant", "content": response.content})
100
+ results = [t.handle_anthropic(b) for b in response.content if b.type == "tool_use"]
101
+ messages.append({"role": "user", "content": results}) # all results in one message
102
+ ```
103
+
104
+ OpenAI-compatible APIs: `tools=t.openai()`, and for each `tool_call`
105
+ `messages.append(t.handle_openai(call))` (images are not included - only a
106
+ note). For `AsyncSandbox` the methods are the same, with `await`.
107
+
108
+ A ready-made analyst agent: [`examples/data_analyst.py`](examples/data_analyst.py).
109
+ The CSV is uploaded to a sandbox without internet access, Claude analyzes it
110
+ with pandas, looks at its own plots and answers; the plots are saved next to
111
+ the script.
112
+
113
+ pip install anthropic
114
+ python examples/data_analyst.py examples/sales.csv "How did sales change by region? Plot it."
115
+
116
+ ## Storage bucket
117
+
118
+ An organization bucket (created in the dashboard or with `POST /v1/buckets`)
119
+ can be attached to a sandbox: the sandbox gets its own key, and every
120
+ command sees `S3_ENDPOINT`, `S3_BUCKET` and `AWS_*` in its environment,
121
+ which boto3 and `aws` understand. Storage is reachable even with
122
+ `egress="none"`. A fork gets its own key, and deleting the sandbox
123
+ (including by TTL) revokes the key.
124
+
125
+ ```python
126
+ sb = Sandbox.create(template="python", egress="none", bucket="data") # bucket_mode="read" for read-only
127
+ sb.exec("python3 -c 'import boto3, os; boto3.client(\"s3\").upload_file(\"out.csv\", os.environ[\"S3_BUCKET\"], \"out.csv\")'")
128
+ ```
129
+
130
+ ## Sandbox API
131
+
132
+ | | |
133
+ |---|---|
134
+ | `Sandbox.create(template=, cpus=, memory_mb=, disk_gb=, idle_timeout_secs=, ttl_secs=, port=, egress=, bucket=, bucket_mode=)` | Create. Returns when the sandbox is ready for `exec`. `egress`: `"internet"` (default, no SMTP), `"none"`, or a list such as `["1.1.1.1:53", "10.0.0.0/8"]` (only those). `ttl_secs` deletes it after N seconds (insurance against forgotten sandboxes), `idle_timeout_secs` puts an idle one to sleep, `bucket` attaches a storage bucket (see above) |
135
+ | `Sandbox.connect(id)` | Connect to an existing sandbox |
136
+ | `sb.exec(cmd, env=, cwd=, timeout=60, stdin=)` | A string runs through `sh -c`, a list is used as argv. Returns `ExecResult(exit_code, stdout, stderr, timed_out, truncated)`, `.ok`, `.check()` |
137
+ | `sb.exec_stream(cmd, ...)` · `sb.exec(cmd, on_stdout=, on_stderr=)` | Output as it appears (no 1 MiB limit): an iterator of `OutputChunk(stream, data)`, then `.result` (`ExecResult`). Leaving the loop kills the command |
138
+ | `sb.files.write(path, data, mode=)` · `read(path)` · `read_text(path)` | Files (up to 64 MiB; binary data as `bytes`) |
139
+ | `sb.run_code(code, timeout=60)` · `sb.reset_code()` | Stateful Python (`python` template) -> `CodeResult` |
140
+ | `sb.sleep()` · `sb.wake()` | Sleep / wake; `exec` on a sleeping sandbox raises `ConflictError` |
141
+ | `sb.fork(snapshot=None, ttl_secs=None)` · `sb.snapshot(name)` | A clone (from the current state or a snapshot) / a named snapshot |
142
+ | `sb.set_idle_timeout(secs)` | Sleep after N idle seconds (0 - never, `None` - platform default); immediate, no restart |
143
+ | `sb.set_ttl(secs)` · `sb.info.expires_at` | Extend the lifetime (from now) or remove it (`None`); when it will be deleted |
144
+ | `sb.set_egress(...)` | Change the network policy immediately (drops open connections) |
145
+ | `sb.delete()` | Delete (already gone is not an error); `with` does it for you |
146
+ | `Client(api_key, base_url)` | A shared connection: `client.create()`, `client.list()`, `client.get(id)`, `client.usage(start, end)` |
147
+
148
+ Errors are subclasses of `SandboxError` (`.status` is the HTTP code):
149
+ `AuthError` 401, `QuotaError` 403 (organization limit), `NotFoundError` 404,
150
+ `ConflictError` 409, `BadRequestError` 400/422, `CapacityError` 503 (no
151
+ capacity - retry), `TimeoutError` 504, `ServerError` - anything else and API
152
+ unavailability; `InterpreterError` - `run_code` on a template without an
153
+ interpreter.
154
+
155
+ ## Hosting: apps, databases, buckets
156
+
157
+ ```python
158
+ from microcld import Client
159
+
160
+ c = Client()
161
+ c.databases.create("pg", size_gb=5)
162
+ c.buckets.create("media")
163
+ c.apps.create("web", port=8080, git={"url": "https://github.com/me/web"})
164
+ c.apps.attach_database("web", "pg") # DATABASE_URL in the app env
165
+ c.apps.attach_bucket("web", "media", env_prefix="MEDIA")
166
+ c.apps.add_domain("web", "example.com")
167
+ print(c.apps.logs("web"), c.account.billing())
168
+ ```
169
+
170
+ | Resource | Methods |
171
+ |---|---|
172
+ | `c.apps` | `list` `get` `create` `update` `delete` `deploy` `rollback` `deployments` `deployment_log` `logs` `rotate_webhook` · `domains` `add_domain` `verify_domain` `remove_domain` · `attach_database` `detach_database` `attach_bucket` `detach_bucket` |
173
+ | `c.databases` | `list` `get` `create` (branch with `from_database`, `from_snapshot`) `update` `delete` · `snapshots` `create_snapshot` `delete_snapshot` `restore` · `dumps` `download_dump` |
174
+ | `c.buckets` | `list` `get` `create` `delete(force=)` · `keys` `create_key` `revoke_key` · `presign` |
175
+ | `c.account` | `me` `billing` `pricing` `limits` |
176
+
177
+ Responses are dicts, as in the REST API. `AsyncClient` has the same methods;
178
+ every call must be awaited (`await c.apps.list()`).
179
+
180
+ ## CLI
181
+
182
+ ```bash
183
+ microcld login # key -> ~/.config/microcld/config.json (mode 0600)
184
+ microcld apps create web --port 8080 --git https://github.com/me/web
185
+ microcld db create pg --size-gb 5 && microcld apps attach-db web pg
186
+ microcld buckets create media && microcld buckets presign media a.csv --expires 3600
187
+ microcld sandbox create --template python # prints the id
188
+ microcld sandbox exec <id> -- python3 -V # exit code is the command's
189
+ microcld balance
190
+ ```
191
+
192
+ Groups: `apps` (ls show create deploy rollback deployments logs rm env domain
193
+ attach-db detach-db attach-bucket detach-bucket), `db` (ls show create rm
194
+ snapshots snapshot snapshot-rm restore dumps), `buckets` (ls show create rm
195
+ key presign), `sandbox` (ls create exec rm), plus `whoami` `balance`
196
+ `pricing` `limits` `usage`. `--json` before the command prints JSON. The
197
+ environment (`SANDBOX_API_KEY`, `SANDBOX_API_URL`) wins over the file saved
198
+ by `login`. Exit codes: 0 success, 1 API error, 2 bad arguments.
199
+
200
+ ## Development
201
+
202
+ ```bash
203
+ cd sdk/python
204
+ python3 -m venv .venv && .venv/bin/pip install -e '.[dev]'
205
+ .venv/bin/python -m pytest -q # fake API (httpx.MockTransport)
206
+ SANDBOX_E2E=1 SANDBOX_API_KEY=mc_... .venv/bin/python -m pytest tests/test_e2e.py -v -s # against a real API
207
+ ```
@@ -0,0 +1,189 @@
1
+ # microcld
2
+
3
+ Python SDK and CLI for [microcloud](https://microcloud.mn): hosting (apps,
4
+ managed Postgres, S3 buckets) and sandboxes for AI agents — isolated
5
+ micro-VMs that start in a fraction of a second, run code, sleep for free and
6
+ clone with their whole state. Execution and data stay in Mongolia.
7
+
8
+ ```bash
9
+ pip install microcld
10
+ export SANDBOX_API_KEY=mc_... # organization API key
11
+ export SANDBOX_API_URL=http://127.0.0.1:7900 # your API endpoint (this is the default)
12
+ ```
13
+
14
+ ```python
15
+ from microcld import Sandbox
16
+
17
+ with Sandbox.create(cpus=1, memory_mb=512, egress="none") as sb: # deleted on exit
18
+ sb.files.write("/tmp/data.csv", "a,b\n1,2\n3,4\n")
19
+ r = sb.exec("awk -F, 'NR>1 {s+=$2} END {print s}' /tmp/data.csv")
20
+ print(r.check().stdout) # 6; check() raises CommandError if the exit code is not 0
21
+
22
+ sb.sleep() # memory goes to a snapshot, not billed
23
+ sb.wake() # ~0.1 s, everything is still there
24
+ with sb.fork() as clone: # a clone with memory and disk - try another path
25
+ clone.exec("rm /tmp/data.csv")
26
+ print(sb.files.read_text("/tmp/data.csv")) # the original is intact
27
+ ```
28
+
29
+ ## Code interpreter (`python` template)
30
+
31
+ Stateful Python, like a Jupyter kernel: variables and imports live between
32
+ calls, the last expression is returned, plots come back as images.
33
+
34
+ ```python
35
+ with Sandbox.create(template="python", memory_mb=1024) as sb:
36
+ sb.files.write("/work/sales.csv", open("sales.csv", "rb").read())
37
+ sb.run_code("import pandas as pd\ndf = pd.read_csv('sales.csv')")
38
+ r = sb.run_code("df.describe()")
39
+ print(r.result) # repr of the last expression
40
+ r = sb.run_code("df.plot(); import matplotlib.pyplot as plt; plt.title('Sales')")
41
+ open("plot.png", "wb").write(r.images[0]) # PNG
42
+ r = sb.run_code("df.nope")
43
+ print(r.ok, r.error.name) # False AttributeError - an error in the result, not an exception
44
+ ```
45
+
46
+ `CodeResult`: `stdout`, `stderr`, `result`, `error` (`name`, `value`,
47
+ `traceback`), `images` (PNG bytes), `duration_ms`, `.ok`, `.text` (all text
48
+ together - handy to return to a model as a tool result). `timeout`
49
+ interrupts the code but keeps the state; `reset_code()` clears it. The state
50
+ survives `sleep`/`wake` and is copied by `fork()`. A template without an
51
+ interpreter raises `InterpreterError`.
52
+
53
+ Async works the same way, with `await`:
54
+
55
+ ```python
56
+ from microcld import AsyncSandbox
57
+
58
+ async with await AsyncSandbox.create() as sb:
59
+ r = await sb.exec("echo hi")
60
+ ```
61
+
62
+ ## Tools for AI agents (function calling)
63
+
64
+ A sandbox as a set of model tools: `run_python` (stateful interpreter),
65
+ `run_shell`, `read_file`, `write_file`. Definitions fit the Anthropic
66
+ Messages API (`strict: true`) and OpenAI-compatible function calling; the
67
+ handler runs the call in the sandbox and returns a ready result. Errors
68
+ (code crashed, no such file) go back to the model with `is_error` instead
69
+ of raising, so the agent sees them and corrects itself. Plots from
70
+ `run_python` and images from `read_file` are returned as image blocks (the
71
+ model sees them). Output is truncated (`max_output`, 20,000 characters).
72
+
73
+ ```python
74
+ from microcld import Sandbox, tools
75
+
76
+ sb = Sandbox.create(template="python", egress="none")
77
+ t = tools.for_sandbox(sb) # or enabled=["run_python"], timeout=..., max_output=...
78
+
79
+ response = client.messages.create(model="claude-opus-5-5", max_tokens=16000,
80
+ tools=t.anthropic(), messages=messages)
81
+ messages.append({"role": "assistant", "content": response.content})
82
+ results = [t.handle_anthropic(b) for b in response.content if b.type == "tool_use"]
83
+ messages.append({"role": "user", "content": results}) # all results in one message
84
+ ```
85
+
86
+ OpenAI-compatible APIs: `tools=t.openai()`, and for each `tool_call`
87
+ `messages.append(t.handle_openai(call))` (images are not included - only a
88
+ note). For `AsyncSandbox` the methods are the same, with `await`.
89
+
90
+ A ready-made analyst agent: [`examples/data_analyst.py`](examples/data_analyst.py).
91
+ The CSV is uploaded to a sandbox without internet access, Claude analyzes it
92
+ with pandas, looks at its own plots and answers; the plots are saved next to
93
+ the script.
94
+
95
+ pip install anthropic
96
+ python examples/data_analyst.py examples/sales.csv "How did sales change by region? Plot it."
97
+
98
+ ## Storage bucket
99
+
100
+ An organization bucket (created in the dashboard or with `POST /v1/buckets`)
101
+ can be attached to a sandbox: the sandbox gets its own key, and every
102
+ command sees `S3_ENDPOINT`, `S3_BUCKET` and `AWS_*` in its environment,
103
+ which boto3 and `aws` understand. Storage is reachable even with
104
+ `egress="none"`. A fork gets its own key, and deleting the sandbox
105
+ (including by TTL) revokes the key.
106
+
107
+ ```python
108
+ sb = Sandbox.create(template="python", egress="none", bucket="data") # bucket_mode="read" for read-only
109
+ sb.exec("python3 -c 'import boto3, os; boto3.client(\"s3\").upload_file(\"out.csv\", os.environ[\"S3_BUCKET\"], \"out.csv\")'")
110
+ ```
111
+
112
+ ## Sandbox API
113
+
114
+ | | |
115
+ |---|---|
116
+ | `Sandbox.create(template=, cpus=, memory_mb=, disk_gb=, idle_timeout_secs=, ttl_secs=, port=, egress=, bucket=, bucket_mode=)` | Create. Returns when the sandbox is ready for `exec`. `egress`: `"internet"` (default, no SMTP), `"none"`, or a list such as `["1.1.1.1:53", "10.0.0.0/8"]` (only those). `ttl_secs` deletes it after N seconds (insurance against forgotten sandboxes), `idle_timeout_secs` puts an idle one to sleep, `bucket` attaches a storage bucket (see above) |
117
+ | `Sandbox.connect(id)` | Connect to an existing sandbox |
118
+ | `sb.exec(cmd, env=, cwd=, timeout=60, stdin=)` | A string runs through `sh -c`, a list is used as argv. Returns `ExecResult(exit_code, stdout, stderr, timed_out, truncated)`, `.ok`, `.check()` |
119
+ | `sb.exec_stream(cmd, ...)` · `sb.exec(cmd, on_stdout=, on_stderr=)` | Output as it appears (no 1 MiB limit): an iterator of `OutputChunk(stream, data)`, then `.result` (`ExecResult`). Leaving the loop kills the command |
120
+ | `sb.files.write(path, data, mode=)` · `read(path)` · `read_text(path)` | Files (up to 64 MiB; binary data as `bytes`) |
121
+ | `sb.run_code(code, timeout=60)` · `sb.reset_code()` | Stateful Python (`python` template) -> `CodeResult` |
122
+ | `sb.sleep()` · `sb.wake()` | Sleep / wake; `exec` on a sleeping sandbox raises `ConflictError` |
123
+ | `sb.fork(snapshot=None, ttl_secs=None)` · `sb.snapshot(name)` | A clone (from the current state or a snapshot) / a named snapshot |
124
+ | `sb.set_idle_timeout(secs)` | Sleep after N idle seconds (0 - never, `None` - platform default); immediate, no restart |
125
+ | `sb.set_ttl(secs)` · `sb.info.expires_at` | Extend the lifetime (from now) or remove it (`None`); when it will be deleted |
126
+ | `sb.set_egress(...)` | Change the network policy immediately (drops open connections) |
127
+ | `sb.delete()` | Delete (already gone is not an error); `with` does it for you |
128
+ | `Client(api_key, base_url)` | A shared connection: `client.create()`, `client.list()`, `client.get(id)`, `client.usage(start, end)` |
129
+
130
+ Errors are subclasses of `SandboxError` (`.status` is the HTTP code):
131
+ `AuthError` 401, `QuotaError` 403 (organization limit), `NotFoundError` 404,
132
+ `ConflictError` 409, `BadRequestError` 400/422, `CapacityError` 503 (no
133
+ capacity - retry), `TimeoutError` 504, `ServerError` - anything else and API
134
+ unavailability; `InterpreterError` - `run_code` on a template without an
135
+ interpreter.
136
+
137
+ ## Hosting: apps, databases, buckets
138
+
139
+ ```python
140
+ from microcld import Client
141
+
142
+ c = Client()
143
+ c.databases.create("pg", size_gb=5)
144
+ c.buckets.create("media")
145
+ c.apps.create("web", port=8080, git={"url": "https://github.com/me/web"})
146
+ c.apps.attach_database("web", "pg") # DATABASE_URL in the app env
147
+ c.apps.attach_bucket("web", "media", env_prefix="MEDIA")
148
+ c.apps.add_domain("web", "example.com")
149
+ print(c.apps.logs("web"), c.account.billing())
150
+ ```
151
+
152
+ | Resource | Methods |
153
+ |---|---|
154
+ | `c.apps` | `list` `get` `create` `update` `delete` `deploy` `rollback` `deployments` `deployment_log` `logs` `rotate_webhook` · `domains` `add_domain` `verify_domain` `remove_domain` · `attach_database` `detach_database` `attach_bucket` `detach_bucket` |
155
+ | `c.databases` | `list` `get` `create` (branch with `from_database`, `from_snapshot`) `update` `delete` · `snapshots` `create_snapshot` `delete_snapshot` `restore` · `dumps` `download_dump` |
156
+ | `c.buckets` | `list` `get` `create` `delete(force=)` · `keys` `create_key` `revoke_key` · `presign` |
157
+ | `c.account` | `me` `billing` `pricing` `limits` |
158
+
159
+ Responses are dicts, as in the REST API. `AsyncClient` has the same methods;
160
+ every call must be awaited (`await c.apps.list()`).
161
+
162
+ ## CLI
163
+
164
+ ```bash
165
+ microcld login # key -> ~/.config/microcld/config.json (mode 0600)
166
+ microcld apps create web --port 8080 --git https://github.com/me/web
167
+ microcld db create pg --size-gb 5 && microcld apps attach-db web pg
168
+ microcld buckets create media && microcld buckets presign media a.csv --expires 3600
169
+ microcld sandbox create --template python # prints the id
170
+ microcld sandbox exec <id> -- python3 -V # exit code is the command's
171
+ microcld balance
172
+ ```
173
+
174
+ Groups: `apps` (ls show create deploy rollback deployments logs rm env domain
175
+ attach-db detach-db attach-bucket detach-bucket), `db` (ls show create rm
176
+ snapshots snapshot snapshot-rm restore dumps), `buckets` (ls show create rm
177
+ key presign), `sandbox` (ls create exec rm), plus `whoami` `balance`
178
+ `pricing` `limits` `usage`. `--json` before the command prints JSON. The
179
+ environment (`SANDBOX_API_KEY`, `SANDBOX_API_URL`) wins over the file saved
180
+ by `login`. Exit codes: 0 success, 1 API error, 2 bad arguments.
181
+
182
+ ## Development
183
+
184
+ ```bash
185
+ cd sdk/python
186
+ python3 -m venv .venv && .venv/bin/pip install -e '.[dev]'
187
+ .venv/bin/python -m pytest -q # fake API (httpx.MockTransport)
188
+ SANDBOX_E2E=1 SANDBOX_API_KEY=mc_... .venv/bin/python -m pytest tests/test_e2e.py -v -s # against a real API
189
+ ```
@@ -0,0 +1,128 @@
1
+ """Demo: Claude analyzes your CSV in an isolated sandbox.
2
+
3
+ Data is uploaded to the sandbox with no internet access (egress "none"): the code,
4
+ which the model writes, runs inside, and the data never leaves.
5
+ The model uses run_python (pandas, matplotlib), looks at its own charts
6
+ and answers; the charts are saved alongside as chart-N.png.
7
+
8
+ pip install -e sdk/python anthropic
9
+ export ANTHROPIC_API_KEY=… # or `ant auth login`
10
+ export SANDBOX_API_KEY=mc_… SANDBOX_API_URL=http://127.0.0.1:7900
11
+ python sdk/python/examples/data_analyst.py sales.csv "Which months are best? Plot a chart."
12
+
13
+ Needs the `python` template on the node.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import os
19
+ import sys
20
+ from typing import Any, Callable
21
+
22
+ from microcld import Sandbox, tools
23
+
24
+ MODEL = "claude-opus-5-5"
25
+ SYSTEM = (
26
+ "You are a careful data analyst working in an isolated Linux sandbox with no internet access. "
27
+ "The user's data file is in /work. Analyze it with Python; when a chart helps, plot it - you will see "
28
+ "the image. Check your numbers before answering. Answer in the user's language, concisely, with the "
29
+ "key figures."
30
+ )
31
+
32
+
33
+ def _text(content: list[Any]) -> str:
34
+ return "\n".join(b.text for b in content if getattr(b, "type", None) == "text").strip()
35
+
36
+
37
+ def run_agent(
38
+ client: Any,
39
+ sb: Sandbox,
40
+ task: str,
41
+ *,
42
+ max_turns: int = 20,
43
+ on_step: Callable[[str], None] = print,
44
+ on_image: Callable[[bytes], None] | None = None,
45
+ ) -> str:
46
+ """Tool use loop: request to Claude → run tools in the sandbox →
47
+ return the results → … until the model answers with text."""
48
+ t = tools.for_sandbox(sb)
49
+ messages: list[dict[str, Any]] = [{"role": "user", "content": task}]
50
+ for _ in range(max_turns):
51
+ response = client.beta.messages.create(
52
+ model=MODEL,
53
+ max_tokens=16000,
54
+ system=SYSTEM,
55
+ tools=t.anthropic(),
56
+ messages=messages,
57
+ # Multi-step analysis with number checks: Opus 5.5 defaults to medium.
58
+ output_config={"effort": "high"},
59
+ # Model refusal under policy — the request itself moves to a fallback
60
+ # model (server-side fallback; the API picks the model).
61
+ betas=["server-side-fallback-2026-07-01"],
62
+ fallbacks="default",
63
+ )
64
+ if response.stop_reason == "refusal":
65
+ raise RuntimeError("the model refused the request")
66
+ # Cut off by max_tokens (thinking counts toward the limit too): the last call
67
+ # of a tool may have been cut off with incomplete arguments — do not run it.
68
+ if response.stop_reason == "max_tokens":
69
+ return _text(response.content) + "\n[answer truncated at max_tokens]"
70
+ # Tools — only if the model stopped for them.
71
+ if response.stop_reason != "tool_use":
72
+ return _text(response.content)
73
+ # The whole model reply (with thinking blocks) — into history as is.
74
+ messages.append({"role": "assistant", "content": response.content})
75
+ uses = [b for b in response.content if b.type == "tool_use"]
76
+ results = []
77
+ for block in uses:
78
+ arg = next(iter(block.input.values()), "") if isinstance(block.input, dict) else ""
79
+ first = str(arg).strip().splitlines()[0] if str(arg).strip() else ""
80
+ on_step(f"→ {block.name}: {first[:100]}")
81
+ result = t.handle_anthropic(block)
82
+ if on_image:
83
+ for c in result["content"]:
84
+ if c["type"] == "image":
85
+ import base64
86
+
87
+ on_image(base64.b64decode(c["source"]["data"]))
88
+ results.append(result)
89
+ # All results — in one message (parallel calls).
90
+ messages.append({"role": "user", "content": results})
91
+ raise RuntimeError(f"the agent did not finish in {max_turns} steps")
92
+
93
+
94
+ def main() -> int:
95
+ if len(sys.argv) != 3:
96
+ print(__doc__, file=sys.stderr)
97
+ return 2
98
+ path, question = sys.argv[1], sys.argv[2]
99
+ import anthropic
100
+
101
+ client = anthropic.Anthropic()
102
+ name = os.path.basename(path)
103
+ charts = []
104
+
105
+ def save(png: bytes) -> None:
106
+ charts.append(f"chart-{len(charts) + 1}.png")
107
+ with open(charts[-1], "wb") as f:
108
+ f.write(png)
109
+
110
+ with Sandbox.create(template="python", memory_mb=1024, egress="none") as sb:
111
+ print(f"sandbox {sb.id} (no internet)", file=sys.stderr)
112
+ with open(path, "rb") as f:
113
+ sb.files.write(f"/work/{name}", f.read())
114
+ answer = run_agent(
115
+ client,
116
+ sb,
117
+ f"File: /work/{name}\n\n{question}",
118
+ on_step=lambda s: print(s, file=sys.stderr),
119
+ on_image=save,
120
+ )
121
+ print(answer)
122
+ if charts:
123
+ print(f"\ncharts: {', '.join(charts)}", file=sys.stderr)
124
+ return 0
125
+
126
+
127
+ if __name__ == "__main__":
128
+ sys.exit(main())
@@ -0,0 +1,13 @@
1
+ month,region,amount
2
+ 2026-01,Ulaanbaatar,120
3
+ 2026-01,Erdenet,45
4
+ 2026-02,Ulaanbaatar,135
5
+ 2026-02,Erdenet,52
6
+ 2026-03,Ulaanbaatar,98
7
+ 2026-03,Erdenet,61
8
+ 2026-04,Ulaanbaatar,160
9
+ 2026-04,Erdenet,58
10
+ 2026-05,Ulaanbaatar,175
11
+ 2026-05,Erdenet,70
12
+ 2026-06,Ulaanbaatar,190
13
+ 2026-06,Erdenet,66
@@ -0,0 +1,62 @@
1
+ """Python SDK and CLI for microcloud: hosting (apps, databases, buckets) and AI-agent sandboxes (`microcld`).
2
+
3
+ from microcld import Sandbox
4
+
5
+ with Sandbox.create(template="python") as sb:
6
+ sb.files.write("/tmp/data.csv", "a,b\\n1,2\\n")
7
+ print(sb.exec("python3 -c 'import sys; print(sys.version)'").check().stdout)
8
+
9
+ Hosting: `Client().apps`, `.databases`, `.buckets` (see `microcld.hosting`).
10
+
11
+ API key and URL: arguments or `SANDBOX_API_KEY` / `SANDBOX_API_URL`.
12
+ """
13
+
14
+ from . import tools
15
+ from ._types import CodeError, CodeResult, CommandError, ExecResult, OutputChunk, SandboxInfo, Usage, UsageReport
16
+ from .aio import AsyncClient, AsyncSandbox
17
+ from .client import Client, Sandbox
18
+ from .errors import (
19
+ AuthError,
20
+ BadRequestError,
21
+ CapacityError,
22
+ ConflictError,
23
+ InterpreterError,
24
+ NotFoundError,
25
+ QuotaError,
26
+ SandboxError,
27
+ ServerError,
28
+ TimeoutError,
29
+ )
30
+ from .hosting import Account, Apps, Buckets, Databases
31
+
32
+ __version__ = "0.1.0"
33
+
34
+ __all__ = [
35
+ "tools",
36
+ "Apps",
37
+ "Databases",
38
+ "Buckets",
39
+ "Account",
40
+ "Sandbox",
41
+ "AsyncSandbox",
42
+ "Client",
43
+ "AsyncClient",
44
+ "ExecResult",
45
+ "OutputChunk",
46
+ "CommandError",
47
+ "CodeResult",
48
+ "CodeError",
49
+ "InterpreterError",
50
+ "SandboxInfo",
51
+ "Usage",
52
+ "UsageReport",
53
+ "SandboxError",
54
+ "AuthError",
55
+ "BadRequestError",
56
+ "CapacityError",
57
+ "ConflictError",
58
+ "NotFoundError",
59
+ "QuotaError",
60
+ "ServerError",
61
+ "TimeoutError",
62
+ ]