mpaka-sdk 0.1.0__py3-none-any.whl

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.
CONTRACT.md ADDED
@@ -0,0 +1,60 @@
1
+ # mPaka API contract used by the SDKs
2
+
3
+ ## Source revisions
4
+
5
+ | Source | Revision | Evidence |
6
+ | --- | --- | --- |
7
+ | RustBox API and domain | `130004a7d5e073ea966bb1e8fc99f26da802c6a9` | `crates/api/openapi.json`, route handlers in `crates/api/src/lib.rs`, API HTTP tests, domain status model |
8
+ | Official CLI | `a907c5411d6409df1e898be806d68d14bc4aa314` | Local checkout `/home/apardo/Projects/mpaka-cli`; request construction, polling, environment examples, OpenAPI snapshot |
9
+ | Official MCP server | `8c361d582016bc301468c6cd5cd8630adcf210a7` | Local checkout `/home/apardo/Projects/mpaka-mcp`; authenticated API client, wait logic, Node environment reuse tests |
10
+
11
+ RustBox OpenAPI snapshot SHA-256: `6a7b7bf9f6ba34934f9ffb4de206c7d6304cb64abbe00fdbeccec8c5441d1954`.
12
+
13
+ The SDKs default to `https://api.mpaka.dev`, allow an explicit base URL, and authenticate workload routes with `Authorization: Bearer <API key>`. They accept HTTPS URLs and loopback HTTP URLs for tests. The API key is supplied as a constructor argument; documentation shows loading it from `MPAKA_API_KEY`.
14
+
15
+ ## Routes used
16
+
17
+ | Route | SDK behavior |
18
+ | --- | --- |
19
+ | `POST /v1/executions` | Submit code; requires `Idempotency-Key` (1–128 characters); returns HTTP 202 and an execution projection |
20
+ | `GET /v1/executions/{id}` | Read status and result fields (`stdout`, `stderr`, `exit_code`, `mode`) |
21
+ | `GET /v1/executions` | List executions with `page`, `page_size`, `status`, `language`, `q`, and `created_on` filters |
22
+ | `POST /v1/executions/{id}/cancel` | Request cancellation; SDK does not retry this mutation |
23
+ | `POST /v1/environments` | Build reusable Python or Node environment; requires `Idempotency-Key` |
24
+ | `GET /v1/environments/{id}` | Read environment build status and metadata |
25
+ | `GET /v1/environments` | List environments with `page` and `page_size` |
26
+ | `GET /v1/limits` | Read request bounds, supported languages, and instance-enabled languages |
27
+ | `GET /v1/quota` | Read tenant quota snapshot |
28
+
29
+ The HTTP implementation adds `x-request-id`; SDK errors preserve it when present. Structured API failures use `{ "error": { "code": "...", "message": "..." } }`.
30
+
31
+ ## Models and terminal states
32
+
33
+ Execution responses include ID, status, language, timeout, memory and CPU limits, creation/finish timestamps, stdout, stderr, exit code, and execution `mode`. Execution lifecycle values are `queued`, `assigned`, `leased`, `provisioning`, `running`, `completed`, `failed`, `timed_out`, and `cancelled`. Terminal values are `completed`, `failed`, `timed_out`, and `cancelled`.
34
+
35
+ Environment responses carry ID, runtime language, status, dependency inputs, artifact metadata, and timestamps. Environment lifecycle values are `queued`, `building`, `ready`, and `failed`; terminal values are `ready` and `failed`.
36
+
37
+ Python environments use pinned `requirements`. Node environments use `package_json` and the complete npm lockfile v3 object. The Node package policy requires `registry.npmjs.org`, SHA-512 integrity, and no install scripts. A ready Node environment may be attached to either JavaScript or TypeScript jobs; API tests prove this reuse.
38
+
39
+ ## Errors and retry rules
40
+
41
+ | HTTP/status condition | SDK error behavior |
42
+ | --- | --- |
43
+ | `401` invalid bearer key | `AuthenticationError` |
44
+ | `400`, `409`, `422` invalid input, idempotency conflict, or environment not ready | `ValidationError` |
45
+ | `429` tenant rate/concurrency/quota limit | `QuotaError` |
46
+ | Other non-2xx response | `ApiError`, preserving status, structured code, and request ID |
47
+ | Transport failure | `NetworkError` |
48
+ | HTTP request or total polling deadline | SDK timeout error |
49
+
50
+ GET requests may retry a bounded number of times after transport failure or HTTP 502/503/504. Job submission and environment creation may retry only because their API contract requires a stable idempotency key; each attempt uses the exact same key. Cancellation is not retried. Redirects are rejected so bearer credentials are not forwarded to a redirected URL. API keys are never logged or emitted in errors; returned error text/code/request IDs are redacted if the server echoes the key.
51
+
52
+ ## Capabilities and discrepancies
53
+
54
+ - The schema recognizes Python, JavaScript, and TypeScript. Python is enabled by default; Node language execution requires `RUSTBOX_NODE_ENABLED`. `/v1/limits` distinguishes `supported_languages` from `enabled_languages`. SDK method availability therefore does not imply a particular instance has Node enabled.
55
+ - Node environment creation also requires the Node environment builder and approved npm proxy. OpenAPI describes `503 node_builder_unavailable` while that proxy is unavailable. The SDK does not claim that public deployment has Node environment builds ready.
56
+ - The 25 October 2026 functional beta audit in this revision describes Python-only submission, unpaginated execution listing, and the mock control-plane path. Those statements conflict with the later OpenAPI/source contract and HTTP tests in this revision, which document three languages (with Node gated), paginated execution listing, and a durable scheduled execution path. The SDK follows executable current route/schema evidence and preserves runtime-gate errors.
57
+ - The production operations guide and repository deployment instructions say the dedicated production guest runs Python through a remote Firecracker executor and must never select the mock; the functional beta audit snapshot says public real-execution admission evidence is pending. The documented host state and the audit's admission assessment are not aligned. SDKs expose the returned `mode`, make no claim about live endpoint readiness, and do not present `mock_no_code_execution` as a sandbox.
58
+ - Request ID is attached by API middleware but is not part of the OpenAPI response body schema; clients read the `x-request-id` header and tolerate a body `request_id` if a future API returns one.
59
+
60
+ Live endpoint capabilities and a production smoke check were not verified: no authorized test credential was supplied for this work.
mpaka/__init__.py ADDED
@@ -0,0 +1,46 @@
1
+ """Official mPaka Python SDK."""
2
+
3
+ from .client import Language, MpakaClient
4
+ from .errors import (
5
+ ApiError,
6
+ AuthenticationError,
7
+ InvalidResponseError,
8
+ MpakaError,
9
+ MpakaTimeoutError,
10
+ NetworkError,
11
+ QuotaError,
12
+ ValidationError,
13
+ )
14
+ from .models import (
15
+ Environment,
16
+ EnvironmentPage,
17
+ EnvironmentStatus,
18
+ Execution,
19
+ ExecutionPage,
20
+ ExecutionStatus,
21
+ ExecutionSummary,
22
+ Quota,
23
+ RequestBounds,
24
+ )
25
+
26
+ __all__ = [
27
+ "ApiError",
28
+ "AuthenticationError",
29
+ "Environment",
30
+ "EnvironmentPage",
31
+ "EnvironmentStatus",
32
+ "Execution",
33
+ "ExecutionPage",
34
+ "ExecutionStatus",
35
+ "ExecutionSummary",
36
+ "InvalidResponseError",
37
+ "Language",
38
+ "MpakaClient",
39
+ "MpakaError",
40
+ "MpakaTimeoutError",
41
+ "NetworkError",
42
+ "Quota",
43
+ "QuotaError",
44
+ "RequestBounds",
45
+ "ValidationError",
46
+ ]
mpaka/client.py ADDED
@@ -0,0 +1,423 @@
1
+ """Async mPaka API client implemented with Python's standard library."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import json
7
+ import socket
8
+ import time
9
+ from typing import Any, Literal
10
+ from urllib.error import HTTPError, URLError
11
+ from urllib.parse import urlencode, urlsplit
12
+ from urllib.request import HTTPRedirectHandler, Request, build_opener
13
+
14
+ from .errors import (
15
+ ApiError,
16
+ AuthenticationError,
17
+ InvalidResponseError,
18
+ MpakaError,
19
+ MpakaTimeoutError,
20
+ NetworkError,
21
+ QuotaError,
22
+ ValidationError,
23
+ )
24
+ from .models import (
25
+ Environment,
26
+ EnvironmentPage,
27
+ Execution,
28
+ ExecutionPage,
29
+ ExecutionStatus,
30
+ RequestBounds,
31
+ Quota,
32
+ )
33
+
34
+ Language = Literal["python", "javascript", "typescript"]
35
+ _TRANSIENT_STATUSES = {502, 503, 504}
36
+
37
+
38
+ class _NoRedirectHandler(HTTPRedirectHandler):
39
+ def redirect_request(self, *_: Any, **__: Any) -> None:
40
+ return None
41
+
42
+
43
+ class MpakaClient:
44
+ """Async tenant API client. Use as an async context manager or call close()."""
45
+
46
+ def __init__(
47
+ self,
48
+ api_key: str,
49
+ *,
50
+ base_url: str = "https://api.mpaka.dev",
51
+ timeout: float = 15.0,
52
+ retries: int = 2,
53
+ ) -> None:
54
+ if not api_key or not api_key.strip():
55
+ raise ValueError("api_key must not be empty")
56
+ if timeout <= 0:
57
+ raise ValueError("timeout must be positive")
58
+ if retries < 0:
59
+ raise ValueError("retries must not be negative")
60
+ parts = urlsplit(base_url)
61
+ loopback = parts.hostname in {"localhost", "127.0.0.1", "::1"}
62
+ if (
63
+ parts.scheme not in {"http", "https"}
64
+ or not parts.hostname
65
+ or parts.username
66
+ or parts.password
67
+ or parts.query
68
+ or parts.fragment
69
+ or (parts.scheme != "https" and not loopback)
70
+ ):
71
+ raise ValueError("base_url must be HTTPS, or HTTP on loopback")
72
+ self._api_key = api_key
73
+ self.base_url = base_url.rstrip("/")
74
+ self.timeout = timeout
75
+ self.retries = retries
76
+ self._closed = False
77
+
78
+ def __repr__(self) -> str:
79
+ return (
80
+ f"MpakaClient(base_url={self.base_url!r}, api_key='[REDACTED]', "
81
+ f"timeout={self.timeout!r}, retries={self.retries!r})"
82
+ )
83
+
84
+ async def __aenter__(self) -> MpakaClient:
85
+ return self
86
+
87
+ async def __aexit__(self, *_: Any) -> None:
88
+ self.close()
89
+
90
+ def close(self) -> None:
91
+ self._closed = True
92
+
93
+ async def submit(
94
+ self,
95
+ code: str,
96
+ *,
97
+ language: Language = "python",
98
+ idempotency_key: str,
99
+ environment_id: str | None = None,
100
+ timeout_ms: int | None = None,
101
+ memory_profile: str | None = None,
102
+ cpu_profile: str | None = None,
103
+ memory_mb: int | None = None,
104
+ vcpu_count: int | None = None,
105
+ ) -> Execution:
106
+ self._validate_idempotency_key(idempotency_key)
107
+ if language not in {"python", "javascript", "typescript"}:
108
+ raise ValueError("language must be python, javascript, or typescript")
109
+ body: dict[str, Any] = {"language": language, "code": code}
110
+ optional = {
111
+ "environment_id": environment_id,
112
+ "timeout_ms": timeout_ms,
113
+ "memory_profile": memory_profile,
114
+ "cpu_profile": cpu_profile,
115
+ "memory_mb": memory_mb,
116
+ "vcpu_count": vcpu_count,
117
+ }
118
+ body.update({key: value for key, value in optional.items() if value is not None})
119
+ data = await self._request(
120
+ "POST", "/v1/executions", body=body, idempotency_key=idempotency_key
121
+ )
122
+ return self._model(Execution.from_dict, data)
123
+
124
+ async def get_execution(self, execution_id: str) -> Execution:
125
+ data = await self._request("GET", f"/v1/executions/{self._path_id(execution_id)}")
126
+ return self._model(Execution.from_dict, data)
127
+
128
+ async def list_executions(
129
+ self,
130
+ *,
131
+ page: int | None = None,
132
+ page_size: int | None = None,
133
+ status: ExecutionStatus | str | None = None,
134
+ language: Language | None = None,
135
+ query: str | None = None,
136
+ created_on: str | None = None,
137
+ ) -> ExecutionPage:
138
+ params = {
139
+ "page": page,
140
+ "page_size": page_size,
141
+ "status": status.value if isinstance(status, ExecutionStatus) else status,
142
+ "language": language,
143
+ "q": query,
144
+ "created_on": created_on,
145
+ }
146
+ data = await self._request("GET", "/v1/executions", query=params)
147
+ return self._model(ExecutionPage.from_dict, data)
148
+
149
+ async def cancel_execution(self, execution_id: str) -> Execution:
150
+ data = await self._request(
151
+ "POST", f"/v1/executions/{self._path_id(execution_id)}/cancel"
152
+ )
153
+ return self._model(Execution.from_dict, data)
154
+
155
+ async def wait_for_execution(
156
+ self,
157
+ execution_id: str,
158
+ *,
159
+ timeout: float = 30.0,
160
+ poll_interval: float = 0.5,
161
+ ) -> Execution:
162
+ return await self._wait(
163
+ lambda remaining: self._get_execution_with_timeout(execution_id, remaining),
164
+ timeout=timeout,
165
+ poll_interval=poll_interval,
166
+ terminal=lambda result: result.status.is_terminal,
167
+ )
168
+
169
+ async def create_environment(
170
+ self,
171
+ *,
172
+ idempotency_key: str,
173
+ language: Literal["python", "node"] = "python",
174
+ requirements: list[str] | None = None,
175
+ package_json: dict[str, Any] | None = None,
176
+ package_lock: dict[str, Any] | None = None,
177
+ ) -> Environment:
178
+ self._validate_idempotency_key(idempotency_key)
179
+ body: dict[str, Any] = {"language": language}
180
+ if language == "python":
181
+ body["requirements"] = requirements or []
182
+ elif language == "node":
183
+ if package_json is None or package_lock is None:
184
+ raise ValueError("Node environments require package_json and package_lock")
185
+ body.update(package_json=package_json, package_lock=package_lock)
186
+ else:
187
+ raise ValueError("environment language must be python or node")
188
+ data = await self._request(
189
+ "POST", "/v1/environments", body=body, idempotency_key=idempotency_key
190
+ )
191
+ return self._model(Environment.from_dict, data)
192
+
193
+ async def get_environment(self, environment_id: str) -> Environment:
194
+ data = await self._request("GET", f"/v1/environments/{self._path_id(environment_id)}")
195
+ return self._model(Environment.from_dict, data)
196
+
197
+ async def list_environments(
198
+ self, *, page: int | None = None, page_size: int | None = None
199
+ ) -> EnvironmentPage:
200
+ data = await self._request(
201
+ "GET", "/v1/environments", query={"page": page, "page_size": page_size}
202
+ )
203
+ return self._model(EnvironmentPage.from_dict, data)
204
+
205
+ async def wait_for_environment(
206
+ self,
207
+ environment_id: str,
208
+ *,
209
+ timeout: float = 60.0,
210
+ poll_interval: float = 1.0,
211
+ ) -> Environment:
212
+ return await self._wait(
213
+ lambda remaining: self._get_environment_with_timeout(environment_id, remaining),
214
+ timeout=timeout,
215
+ poll_interval=poll_interval,
216
+ terminal=lambda result: result.status.is_terminal,
217
+ )
218
+
219
+ async def get_limits(self) -> RequestBounds:
220
+ return self._model(RequestBounds.from_dict, await self._request("GET", "/v1/limits"))
221
+
222
+ async def get_quota(self) -> Quota:
223
+ return self._model(Quota.from_dict, await self._request("GET", "/v1/quota"))
224
+
225
+ async def _get_execution_with_timeout(self, execution_id: str, remaining: float) -> Execution:
226
+ try:
227
+ data = await asyncio.wait_for(
228
+ self._request(
229
+ "GET", f"/v1/executions/{self._path_id(execution_id)}", timeout=remaining
230
+ ),
231
+ timeout=remaining,
232
+ )
233
+ except TimeoutError as error:
234
+ raise MpakaTimeoutError("mPaka wait deadline expired") from error
235
+ return self._model(Execution.from_dict, data)
236
+
237
+ async def _get_environment_with_timeout(
238
+ self, environment_id: str, remaining: float
239
+ ) -> Environment:
240
+ try:
241
+ data = await asyncio.wait_for(
242
+ self._request(
243
+ "GET", f"/v1/environments/{self._path_id(environment_id)}", timeout=remaining
244
+ ),
245
+ timeout=remaining,
246
+ )
247
+ except TimeoutError as error:
248
+ raise MpakaTimeoutError("mPaka wait deadline expired") from error
249
+ return self._model(Environment.from_dict, data)
250
+
251
+ async def _wait(
252
+ self,
253
+ getter: Any,
254
+ *,
255
+ timeout: float,
256
+ poll_interval: float,
257
+ terminal: Any,
258
+ ) -> Any:
259
+ if timeout <= 0 or poll_interval <= 0:
260
+ raise ValueError("timeout and poll_interval must be positive")
261
+ deadline = time.monotonic() + timeout
262
+ while True:
263
+ remaining = deadline - time.monotonic()
264
+ if remaining <= 0:
265
+ raise MpakaTimeoutError("mPaka wait deadline expired")
266
+ try:
267
+ result = await getter(remaining)
268
+ except TimeoutError as error:
269
+ raise MpakaTimeoutError("mPaka wait deadline expired") from error
270
+ if terminal(result):
271
+ return result
272
+ remaining = deadline - time.monotonic()
273
+ if remaining <= 0:
274
+ raise MpakaTimeoutError("mPaka wait deadline expired")
275
+ await asyncio.sleep(min(poll_interval, remaining))
276
+
277
+ async def _request(
278
+ self,
279
+ method: str,
280
+ path: str,
281
+ *,
282
+ body: dict[str, Any] | None = None,
283
+ query: dict[str, Any] | None = None,
284
+ idempotency_key: str | None = None,
285
+ timeout: float | None = None,
286
+ ) -> dict[str, Any]:
287
+ if self._closed:
288
+ raise MpakaError("client is closed")
289
+ url = f"{self.base_url}{path}"
290
+ if query:
291
+ pairs = {key: value for key, value in query.items() if value is not None}
292
+ if pairs:
293
+ url += "?" + urlencode(pairs)
294
+ headers = {"Authorization": f"Bearer {self._api_key}", "Accept": "application/json"}
295
+ data = None
296
+ if body is not None:
297
+ headers["Content-Type"] = "application/json"
298
+ data = json.dumps(body, separators=(",", ":")).encode("utf-8")
299
+ if idempotency_key is not None:
300
+ headers["Idempotency-Key"] = idempotency_key
301
+ can_retry = method == "GET" or (method == "POST" and idempotency_key is not None)
302
+ retries = self.retries if can_retry else 0
303
+ request_deadline = time.monotonic() + (timeout if timeout is not None else self.timeout)
304
+ for attempt in range(retries + 1):
305
+ remaining = request_deadline - time.monotonic()
306
+ if remaining <= 0:
307
+ raise MpakaTimeoutError("mPaka API request timed out")
308
+ try:
309
+ status, response_headers, payload = await asyncio.to_thread(
310
+ self._send,
311
+ Request(url, data=data, headers=headers, method=method),
312
+ remaining,
313
+ )
314
+ except MpakaTimeoutError:
315
+ if attempt < retries:
316
+ continue
317
+ raise
318
+ except NetworkError:
319
+ if attempt < retries:
320
+ continue
321
+ raise
322
+ if status in _TRANSIENT_STATUSES and attempt < retries:
323
+ continue
324
+ if not 200 <= status < 300:
325
+ raise self._api_error(status, response_headers, payload)
326
+ if not payload:
327
+ return {}
328
+ try:
329
+ result = json.loads(payload)
330
+ except (json.JSONDecodeError, UnicodeDecodeError) as error:
331
+ raise InvalidResponseError(
332
+ "mPaka API returned invalid JSON",
333
+ status_code=status,
334
+ request_id=response_headers.get("x-request-id"),
335
+ ) from error
336
+ if not isinstance(result, dict):
337
+ raise InvalidResponseError(
338
+ "mPaka API returned an invalid response",
339
+ status_code=status,
340
+ request_id=response_headers.get("x-request-id"),
341
+ )
342
+ return result
343
+ raise MpakaError("mPaka request could not be completed")
344
+
345
+ @staticmethod
346
+ def _send(request: Request, timeout: float) -> tuple[int, dict[str, str], bytes]:
347
+ try:
348
+ opener = build_opener(_NoRedirectHandler())
349
+ with opener.open(request, timeout=timeout) as response:
350
+ return (
351
+ response.status,
352
+ {key.lower(): value for key, value in response.headers.items()},
353
+ response.read(),
354
+ )
355
+ except HTTPError as response:
356
+ try:
357
+ return (
358
+ response.code,
359
+ {key.lower(): value for key, value in response.headers.items()},
360
+ response.read(),
361
+ )
362
+ finally:
363
+ response.close()
364
+ except (socket.timeout, TimeoutError) as error:
365
+ raise MpakaTimeoutError("mPaka API request timed out") from error
366
+ except URLError as error:
367
+ if isinstance(error.reason, (socket.timeout, TimeoutError)):
368
+ raise MpakaTimeoutError("mPaka API request timed out") from error
369
+ raise NetworkError("mPaka API could not be reached") from error
370
+ except OSError as error:
371
+ raise NetworkError("mPaka API could not be reached") from error
372
+
373
+ def _api_error(self, status: int, headers: dict[str, str], payload: bytes) -> ApiError:
374
+ code = "http_error"
375
+ message = f"mPaka API returned HTTP {status}"
376
+ try:
377
+ body = json.loads(payload)
378
+ error = body.get("error", {})
379
+ if isinstance(error, dict):
380
+ code = str(error.get("code", code))
381
+ message = str(error.get("message", message))
382
+ request_id = headers.get("x-request-id") or body.get("request_id")
383
+ except (json.JSONDecodeError, UnicodeDecodeError, AttributeError):
384
+ request_id = headers.get("x-request-id")
385
+ if request_id is not None:
386
+ request_id = str(request_id).replace(self._api_key, "[REDACTED]")
387
+ error_type: type[ApiError]
388
+ if status == 401:
389
+ error_type = AuthenticationError
390
+ elif status == 429:
391
+ error_type = QuotaError
392
+ elif status in {400, 409, 422}:
393
+ error_type = ValidationError
394
+ else:
395
+ error_type = ApiError
396
+ return error_type(
397
+ message.replace(self._api_key, "[REDACTED]"),
398
+ status_code=status,
399
+ code=code.replace(self._api_key, "[REDACTED]"),
400
+ request_id=request_id,
401
+ )
402
+
403
+ @staticmethod
404
+ def _model(factory: Any, data: dict[str, Any]) -> Any:
405
+ try:
406
+ return factory(data)
407
+ except (KeyError, TypeError, ValueError) as error:
408
+ raise InvalidResponseError("mPaka API response did not match the contract") from error
409
+
410
+ @staticmethod
411
+ def _validate_idempotency_key(key: str) -> None:
412
+ try:
413
+ raw = key.encode("ascii")
414
+ except (AttributeError, UnicodeEncodeError) as error:
415
+ raise ValueError("idempotency_key must be 1 to 128 visible ASCII characters") from error
416
+ if not raw or len(raw) > 128 or any(value < 0x21 or value > 0x7E for value in raw):
417
+ raise ValueError("idempotency_key must be 1 to 128 visible ASCII characters")
418
+
419
+ @staticmethod
420
+ def _path_id(value: str) -> str:
421
+ if not value or "/" in value or "?" in value or "#" in value:
422
+ raise ValueError("identifier is invalid")
423
+ return value
mpaka/errors.py ADDED
@@ -0,0 +1,48 @@
1
+ """Typed errors raised by the mPaka API client."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class MpakaError(Exception):
7
+ """Base error; API metadata is present when the server returned it."""
8
+
9
+ def __init__(
10
+ self,
11
+ message: str,
12
+ *,
13
+ status_code: int | None = None,
14
+ code: str | None = None,
15
+ request_id: str | None = None,
16
+ ) -> None:
17
+ super().__init__(message)
18
+ self.status_code = status_code
19
+ self.code = code
20
+ self.request_id = request_id
21
+
22
+
23
+ class ApiError(MpakaError):
24
+ """An HTTP/API error response."""
25
+
26
+
27
+ class AuthenticationError(ApiError):
28
+ """The API key is missing or invalid."""
29
+
30
+
31
+ class ValidationError(ApiError):
32
+ """The request did not satisfy API validation."""
33
+
34
+
35
+ class QuotaError(ApiError):
36
+ """A tenant quota or rate limit rejected the request."""
37
+
38
+
39
+ class NetworkError(MpakaError):
40
+ """The API could not be reached."""
41
+
42
+
43
+ class MpakaTimeoutError(MpakaError):
44
+ """An HTTP request or total wait deadline expired."""
45
+
46
+
47
+ class InvalidResponseError(MpakaError):
48
+ """The API returned a response that does not match the public contract."""
mpaka/models.py ADDED
@@ -0,0 +1,206 @@
1
+ """Public response models for mPaka."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from enum import StrEnum
7
+ from typing import Any
8
+
9
+
10
+ class ExecutionStatus(StrEnum):
11
+ QUEUED = "queued"
12
+ ASSIGNED = "assigned"
13
+ LEASED = "leased"
14
+ PROVISIONING = "provisioning"
15
+ RUNNING = "running"
16
+ COMPLETED = "completed"
17
+ FAILED = "failed"
18
+ TIMED_OUT = "timed_out"
19
+ CANCELLED = "cancelled"
20
+
21
+ @property
22
+ def is_terminal(self) -> bool:
23
+ return self in {
24
+ ExecutionStatus.COMPLETED,
25
+ ExecutionStatus.FAILED,
26
+ ExecutionStatus.TIMED_OUT,
27
+ ExecutionStatus.CANCELLED,
28
+ }
29
+
30
+
31
+ class EnvironmentStatus(StrEnum):
32
+ QUEUED = "queued"
33
+ BUILDING = "building"
34
+ READY = "ready"
35
+ FAILED = "failed"
36
+
37
+ @property
38
+ def is_terminal(self) -> bool:
39
+ return self in {EnvironmentStatus.READY, EnvironmentStatus.FAILED}
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class Execution:
44
+ id: str
45
+ status: ExecutionStatus
46
+ language: str
47
+ timeout_ms: int
48
+ memory_mb: int
49
+ vcpu_count: int
50
+ created_at: str
51
+ finished_at: str | None
52
+ stdout: str
53
+ stderr: str
54
+ exit_code: int | None
55
+ mode: str
56
+
57
+ @classmethod
58
+ def from_dict(cls, data: dict[str, Any]) -> Execution:
59
+ try:
60
+ return cls(
61
+ id=str(data["id"]),
62
+ status=ExecutionStatus(data["status"]),
63
+ language=str(data["language"]),
64
+ timeout_ms=int(data["timeout_ms"]),
65
+ memory_mb=int(data["memory_mb"]),
66
+ vcpu_count=int(data["vcpu_count"]),
67
+ created_at=str(data["created_at"]),
68
+ finished_at=data.get("finished_at"),
69
+ stdout=str(data["stdout"]),
70
+ stderr=str(data["stderr"]),
71
+ exit_code=data.get("exit_code"),
72
+ mode=str(data["mode"]),
73
+ )
74
+ except (KeyError, TypeError, ValueError) as error:
75
+ raise ValueError("invalid execution response") from error
76
+
77
+
78
+ @dataclass(frozen=True)
79
+ class ExecutionSummary:
80
+ id: str
81
+ status: ExecutionStatus
82
+ language: str
83
+ created_at: str
84
+ finished_at: str | None
85
+
86
+ @classmethod
87
+ def from_dict(cls, data: dict[str, Any]) -> ExecutionSummary:
88
+ return cls(
89
+ id=str(data["id"]),
90
+ status=ExecutionStatus(data["status"]),
91
+ language=str(data["language"]),
92
+ created_at=str(data["created_at"]),
93
+ finished_at=data.get("finished_at"),
94
+ )
95
+
96
+
97
+ @dataclass(frozen=True)
98
+ class ExecutionPage:
99
+ items: tuple[ExecutionSummary, ...]
100
+ page: int
101
+ page_size: int
102
+ total: int
103
+ has_next: bool
104
+
105
+ @classmethod
106
+ def from_dict(cls, data: dict[str, Any]) -> ExecutionPage:
107
+ return cls(
108
+ items=tuple(ExecutionSummary.from_dict(item) for item in data["items"]),
109
+ page=int(data["page"]),
110
+ page_size=int(data["page_size"]),
111
+ total=int(data["total"]),
112
+ has_next=bool(data["has_next"]),
113
+ )
114
+
115
+
116
+ @dataclass(frozen=True)
117
+ class Environment:
118
+ id: str
119
+ language: str
120
+ status: EnvironmentStatus
121
+ requirements: tuple[str, ...]
122
+ package_json: dict[str, Any] | None
123
+ package_lock: dict[str, Any] | None
124
+ artifact_sha256: str | None
125
+ artifact_size_bytes: int | None
126
+ resolved_digest: str | None
127
+ created_at: str
128
+ updated_at: str
129
+
130
+ @classmethod
131
+ def from_dict(cls, data: dict[str, Any]) -> Environment:
132
+ try:
133
+ return cls(
134
+ id=str(data["id"]),
135
+ language=str(data["language"]),
136
+ status=EnvironmentStatus(data["status"]),
137
+ requirements=tuple(data.get("requirements", ())),
138
+ package_json=data.get("package_json"),
139
+ package_lock=data.get("package_lock"),
140
+ artifact_sha256=data.get("artifact_sha256"),
141
+ artifact_size_bytes=data.get("artifact_size_bytes"),
142
+ resolved_digest=data.get("resolved_digest"),
143
+ created_at=str(data["created_at"]),
144
+ updated_at=str(data["updated_at"]),
145
+ )
146
+ except (KeyError, TypeError, ValueError) as error:
147
+ raise ValueError("invalid environment response") from error
148
+
149
+
150
+ @dataclass(frozen=True)
151
+ class EnvironmentPage:
152
+ items: tuple[Environment, ...]
153
+ page: int
154
+ page_size: int
155
+ total: int
156
+ has_next: bool
157
+
158
+ @classmethod
159
+ def from_dict(cls, data: dict[str, Any]) -> EnvironmentPage:
160
+ return cls(
161
+ items=tuple(Environment.from_dict(item) for item in data["items"]),
162
+ page=int(data["page"]),
163
+ page_size=int(data["page_size"]),
164
+ total=int(data["total"]),
165
+ has_next=bool(data["has_next"]),
166
+ )
167
+
168
+
169
+ @dataclass(frozen=True)
170
+ class RequestBounds:
171
+ language: str
172
+ supported_languages: tuple[str, ...]
173
+ enabled_languages: tuple[str, ...]
174
+ max_code_bytes: int
175
+ min_timeout_ms: int
176
+ max_timeout_ms: int
177
+ default_timeout_ms: int
178
+ min_memory_mb: int
179
+ max_memory_mb: int
180
+ default_memory_mb: int
181
+ guest_memory_profiles: tuple[str, ...]
182
+ guest_cpu_profiles: tuple[str, ...]
183
+ min_vcpu_count: int
184
+ max_vcpu_count: int
185
+ default_vcpu_count: int
186
+
187
+ @classmethod
188
+ def from_dict(cls, data: dict[str, Any]) -> RequestBounds:
189
+ values = {key: value for key, value in data.items()}
190
+ values["supported_languages"] = tuple(values["supported_languages"])
191
+ values["enabled_languages"] = tuple(values["enabled_languages"])
192
+ values["guest_memory_profiles"] = tuple(values["guest_memory_profiles"])
193
+ values["guest_cpu_profiles"] = tuple(values["guest_cpu_profiles"])
194
+ return cls(**values)
195
+
196
+
197
+ @dataclass(frozen=True)
198
+ class Quota:
199
+ used_units: int
200
+ limit_units: int
201
+ active_count: int
202
+ active_limit: int
203
+
204
+ @classmethod
205
+ def from_dict(cls, data: dict[str, Any]) -> Quota:
206
+ return cls(**{key: int(data[key]) for key in cls.__dataclass_fields__})
@@ -0,0 +1,216 @@
1
+ Metadata-Version: 2.5
2
+ Name: mpaka-sdk
3
+ Version: 0.1.0
4
+ Summary: Official asynchronous Python SDK for the mPaka API
5
+ Author: mPaka
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Keywords: api,execution,mpaka,sdk
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Framework :: AsyncIO
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Programming Language :: Python :: 3.14
16
+ Requires-Python: >=3.11
17
+ Description-Content-Type: text/markdown
18
+
19
+ # mPaka Python SDK
20
+
21
+ Official asynchronous Python client for the mPaka API. The package is named `mpaka-sdk` on PyPI and imported as `mpaka`.
22
+
23
+ ## Install
24
+
25
+ Install the published package when available:
26
+
27
+ ```bash
28
+ uv add mpaka-sdk
29
+ ```
30
+
31
+ To install a local wheel:
32
+
33
+ ```bash
34
+ uv pip install dist/mpaka_sdk-0.1.0-py3-none-any.whl
35
+ ```
36
+
37
+ The SDK requires Python 3.11 or newer and has no runtime dependencies.
38
+
39
+ ## Verify a source checkout
40
+
41
+ ```bash
42
+ uv build
43
+ python -m unittest discover -s tests -v
44
+ ```
45
+
46
+ The wheel build and tests were verified with Python 3.14.5 and `uv` 0.13.13.
47
+
48
+ ## Configure and submit a job
49
+
50
+ Create an API key in mPaka, then load it from your environment. Do not put keys in source code or log them.
51
+
52
+ ```bash
53
+ export MPAKA_API_KEY="your-key"
54
+ ```
55
+
56
+ ```python
57
+ import asyncio
58
+ import os
59
+ from mpaka import MpakaClient
60
+
61
+ async def main():
62
+ async with MpakaClient(
63
+ os.environ["MPAKA_API_KEY"],
64
+ base_url=os.getenv("MPAKA_API_BASE_URL", "https://api.mpaka.dev"),
65
+ ) as client:
66
+ accepted = await client.submit(
67
+ "print(1 + 1)",
68
+ language="python",
69
+ idempotency_key="job-2026-01-15-001",
70
+ )
71
+ print(f"Accepted {accepted.id}: {accepted.status}")
72
+
73
+ result = await client.wait_for_execution(
74
+ accepted.id, timeout=30, poll_interval=0.5
75
+ )
76
+ print(result.stdout)
77
+ if result.status.value != "completed":
78
+ print(result.stderr)
79
+
80
+ asyncio.run(main())
81
+ ```
82
+
83
+ The default base URL is `https://api.mpaka.dev`. Pass another `base_url` for a test server or staging. Non-loopback URLs must use HTTPS. Every submission needs an idempotency key (1–128 visible ASCII characters); the client reuses that same key when safely retrying a transient submit response.
84
+
85
+ The client rejects HTTP redirects so it will not forward the bearer key to a second URL.
86
+
87
+ Use individual operations (`submit`, `get_execution`, `list_executions`, and `cancel_execution`) when you need to control polling yourself. `wait_for_execution` applies a total deadline and returns only on `completed`, `failed`, `timed_out`, or `cancelled`.
88
+
89
+ ## JavaScript and TypeScript jobs
90
+
91
+ The instance may enable JavaScript and TypeScript independently of the SDK. Check `await client.get_limits()` and its `enabled_languages` field. The API accepts JavaScript and TypeScript source when the Node.js runtime is enabled. TypeScript accepts a single `.mts` file using erasable types only; syntax requiring transformation, such as enums, is rejected by Node.
92
+
93
+ ```python
94
+ js = await client.submit(
95
+ "console.log(42)", language="javascript", idempotency_key="node-js-001"
96
+ )
97
+ ts = await client.submit(
98
+ "const answer: number = 42; console.log(answer)",
99
+ language="typescript",
100
+ idempotency_key="node-ts-001",
101
+ )
102
+ ```
103
+
104
+ ## Reusable dependency environments
105
+
106
+ ### Python dependencies
107
+
108
+ Send pinned requirements when building an environment:
109
+
110
+ ```python
111
+ environment = await client.create_environment(
112
+ language="python",
113
+ requirements=["requests==2.32.3"],
114
+ idempotency_key="python-env-001",
115
+ )
116
+ ready = await client.wait_for_environment(environment.id, timeout=300, poll_interval=2)
117
+ job = await client.submit(
118
+ "import requests; print(requests.__version__)",
119
+ environment_id=ready.id,
120
+ idempotency_key="python-env-job-001",
121
+ )
122
+ ```
123
+
124
+ ### Node dependencies shared by JavaScript and TypeScript
125
+
126
+ Generate a complete npm lockfile v3 locally so the API receives pinned package versions and integrity hashes:
127
+
128
+ ```bash
129
+ mkdir mpaka-node-env && cd mpaka-node-env
130
+ npm init -y
131
+ npm install lodash@4.17.21 --package-lock-only
132
+ ```
133
+
134
+ ```python
135
+ import json
136
+
137
+ with open("package.json", encoding="utf-8") as file:
138
+ package_json = json.load(file)
139
+ with open("package-lock.json", encoding="utf-8") as file:
140
+ package_lock = json.load(file)
141
+
142
+ node_env = await client.create_environment(
143
+ language="node",
144
+ package_json=package_json,
145
+ package_lock=package_lock,
146
+ idempotency_key="node-env-001",
147
+ )
148
+ ready_node = await client.wait_for_environment(node_env.id, timeout=300, poll_interval=2)
149
+
150
+ js_job = await client.submit(
151
+ "const _ = require('lodash'); console.log(_.camelCase('mPaka SDK'))",
152
+ language="javascript",
153
+ environment_id=ready_node.id,
154
+ idempotency_key="node-js-env-job-001",
155
+ )
156
+ ts_job = await client.submit(
157
+ "import _ from 'lodash'; console.log(_.camelCase('mPaka SDK'))",
158
+ language="typescript",
159
+ environment_id=ready_node.id,
160
+ idempotency_key="node-ts-env-job-001",
161
+ )
162
+ ```
163
+
164
+ The same ready Node environment can be selected by JavaScript and TypeScript jobs. Node execution is instance-gated, and environment creation can return `node_builder_unavailable` until the approved npm proxy is configured. Python environments use pinned requirements. Package build constraints are enforced by the API.
165
+
166
+ ## Errors
167
+
168
+ ```python
169
+ from mpaka import (
170
+ ApiError,
171
+ AuthenticationError,
172
+ MpakaTimeoutError,
173
+ NetworkError,
174
+ QuotaError,
175
+ ValidationError,
176
+ )
177
+
178
+ try:
179
+ result = await client.submit("print('hello')", idempotency_key="example-001")
180
+ except AuthenticationError:
181
+ # Check that MPAKA_API_KEY is valid.
182
+ raise
183
+ except ValidationError as error:
184
+ print(error.code, error.status_code, error.request_id)
185
+ except QuotaError as error:
186
+ print("Rate or quota limit", error.status_code, error.request_id)
187
+ except MpakaTimeoutError:
188
+ print("The HTTP request or total wait deadline expired")
189
+ except NetworkError:
190
+ print("The API could not be reached")
191
+ except ApiError as error:
192
+ print(error.code, error.status_code, error.request_id)
193
+ ```
194
+
195
+ API exceptions retain `status_code`, the server's structured `code`, and `request_id` from the `x-request-id` response header when present. The SDK never includes the API key in exception text or its `repr` output.
196
+
197
+ `Execution.mode` is part of the result. A value of `mock_no_code_execution` means the submitted source was not run; the SDK does not claim that a mock is a production sandbox.
198
+
199
+ ## Feature coverage
200
+
201
+ | Feature | Supported |
202
+ | --- | --- |
203
+ | Python, JavaScript, and TypeScript submission | Yes; Node languages depend on instance capability |
204
+ | Get execution status and result | Yes |
205
+ | List execution history | Yes |
206
+ | Cancel execution | Yes |
207
+ | Wait with total timeout and poll interval | Yes |
208
+ | Create, get, list, and wait for reusable environments | Yes |
209
+ | Reuse Node environment for JavaScript and TypeScript | Yes |
210
+ | Read runtime limits and tenant quota | Yes |
211
+ | Safe bounded retries | GET reads; POST only with a stable idempotency key |
212
+ | Typed auth, validation, quota, API, network, and timeout errors | Yes |
213
+
214
+ ## Contract source
215
+
216
+ The SDK contract is based on RustBox revision `130004a7d5e073ea966bb1e8fc99f26da802c6a9` and cross-checked against the mPaka CLI revision `a907c5411d6409df1e898be806d68d14bc4aa314` and MCP revision `8c361d582016bc301468c6cd5cd8630adcf210a7`. The OpenAPI schema recognizes Python, JavaScript, and TypeScript, while `/v1/limits` reports which languages are enabled on a particular instance. Node environment creation can return HTTP 503 when its approved builder or npm proxy is unavailable. See the accompanying contract record for the schema hash and route details.
@@ -0,0 +1,9 @@
1
+ mpaka/__init__.py,sha256=JkOCZ-rqx_Hm0OHDS8TZfnPnlA6O7WornJh99vCplbA,862
2
+ mpaka/client.py,sha256=pAGJcmtIsmMk2flLmhucP160xdm3R12MRBIszT0d-Eo,16066
3
+ mpaka/errors.py,sha256=P8NZhyoNq2LOwWymersRQwAEqnLYAUub8HHpo9a_iJM,1145
4
+ mpaka/models.py,sha256=0l-ctTQmCctwoS-hzTT0epMZVAxJ8JlXoDPrV2vGDAE,6012
5
+ CONTRACT.md,sha256=pOXzAuQ52vZwjHLvhM7gu_Gau-xucIJw8o0Am10tJLE,6018
6
+ mpaka_sdk-0.1.0.dist-info/METADATA,sha256=yjvuW8ALOuEqNnssILrcV02hzqZzC07nLwKRFKywZAM,7761
7
+ mpaka_sdk-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
8
+ mpaka_sdk-0.1.0.dist-info/licenses/LICENSE,sha256=lNBbGlJ74QT_7N19q-LpFvIVzOKHMETRpRyKu7iiGtQ,1063
9
+ mpaka_sdk-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Spluca
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.