-
Notifications
You must be signed in to change notification settings - Fork 887
Expand file tree
/
Copy pathsandbox_api.py
More file actions
351 lines (290 loc) · 10.5 KB
/
sandbox_api.py
File metadata and controls
351 lines (290 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any, Dict, List, Literal, Optional, TypedDict, Union, cast
from typing_extensions import NotRequired, Unpack
from e2b import ConnectionConfig
from e2b.api.client.models import (
ListedSandbox,
SandboxDetail,
SandboxLifecycle as ClientSandboxLifecycle,
SandboxNetworkConfig as ClientSandboxNetworkConfig,
SandboxState,
)
from e2b.api.client.types import Unset
from e2b.connection_config import ApiParams
from e2b.sandbox.mcp import McpServer as BaseMcpServer
class GitHubMcpServerConfig(TypedDict):
"""
Configuration for a GitHub-based MCP server.
"""
run_cmd: str
"""
Command to run the MCP server. Must start a stdio-compatible server.
"""
install_cmd: NotRequired[str]
"""
Command to install dependencies for the MCP server. Working directory is the root of the github repository.
"""
envs: NotRequired[Dict[str, str]]
"""
Environment variables to set in the MCP process.
"""
# Extended MCP server configuration that includes base servers
# and allows dynamic GitHub-based MCP servers with custom run and install commands.
# For GitHub servers, use keys in the format "github/owner/repo"
GitHubMcpServer = Dict[str, Union[GitHubMcpServerConfig, Any]]
# Union type that combines base MCP servers with GitHub-based servers
McpServer = Union[BaseMcpServer, GitHubMcpServer]
class SandboxNetworkOpts(TypedDict):
"""
Sandbox network configuration options.
"""
allow_out: NotRequired[List[str]]
"""
Allow outbound traffic from the sandbox to the specified addresses.
If `allow_out` is not specified, all outbound traffic is allowed.
Examples:
- To allow traffic to specific addresses: `["1.1.1.1", "8.8.8.0/24"]`
"""
deny_out: NotRequired[List[str]]
"""
Deny outbound traffic from the sandbox to the specified addresses.
Examples:
- To deny traffic to specific addresses: `["1.1.1.1", "8.8.8.0/24"]`
"""
allow_public_traffic: NotRequired[bool]
"""
Controls whether sandbox URLs should be publicly accessible or require authentication.
Defaults to True.
"""
mask_request_host: NotRequired[str]
"""
Allows specifying a custom host mask for all sandbox requests.
Supports ${PORT} variable. Defaults to "${PORT}-sandboxid.e2b.app".
Examples:
- Custom subdomain: `"${PORT}-myapp.example.com"`
"""
class SandboxLifecycle(TypedDict):
"""
Sandbox lifecycle configuration; defines post-timeout behavior and auto-resume settings.
Defaults to `on_timeout="kill"` and `auto_resume=False`.
"""
on_timeout: Literal["pause", "kill"]
"""
What should happen to the sandbox when timeout is reached. `"kill"` means the sandbox will be terminated, while `"pause"` means the sandbox will be paused and can be resumed later. Defaults to `"kill"`.
"""
auto_resume: NotRequired[bool]
"""
Whether activity should cause the sandbox to resume when paused. Defaults to `False`.
Can be `True` only when `on_timeout` is `pause`.
"""
class SandboxInfoLifecycle(TypedDict):
"""
Sandbox lifecycle configuration returned by sandbox info.
"""
on_timeout: Literal["pause", "kill"]
"""
What should happen to the sandbox when timeout is reached.
"""
auto_resume: bool
"""
Whether activity should cause the sandbox to resume when paused.
"""
def get_auto_resume_enabled(lifecycle: Optional[SandboxLifecycle]) -> Optional[bool]:
if lifecycle is None or lifecycle.get("on_timeout") != "pause":
return None
return lifecycle.get("auto_resume", False)
def from_client_network_config(
network: Union[Unset, ClientSandboxNetworkConfig],
) -> Optional[SandboxNetworkOpts]:
if isinstance(network, Unset):
return None
result: SandboxNetworkOpts = {}
if not isinstance(network.allow_out, Unset):
result["allow_out"] = list(network.allow_out)
if not isinstance(network.deny_out, Unset):
result["deny_out"] = list(network.deny_out)
if not isinstance(network.allow_public_traffic, Unset):
result["allow_public_traffic"] = network.allow_public_traffic
if not isinstance(network.mask_request_host, Unset):
result["mask_request_host"] = network.mask_request_host
return result
def from_client_lifecycle(
lifecycle: Union[Unset, ClientSandboxLifecycle],
) -> Optional[SandboxInfoLifecycle]:
if isinstance(lifecycle, Unset):
return None
result: SandboxInfoLifecycle = {
"on_timeout": cast(Literal["pause", "kill"], lifecycle.on_timeout),
"auto_resume": lifecycle.auto_resume,
}
return result
@dataclass
class SandboxInfo:
"""Information about a sandbox."""
sandbox_id: str
"""Sandbox ID."""
sandbox_domain: Optional[str]
"""Domain where the sandbox is hosted."""
template_id: str
"""Template ID."""
name: Optional[str]
"""Template name."""
metadata: Dict[str, str]
"""Saved sandbox metadata."""
started_at: datetime
"""Sandbox start time."""
end_at: datetime
"""Sandbox expiration date."""
state: SandboxState
"""Sandbox state."""
cpu_count: int
"""Sandbox CPU count."""
memory_mb: int
"""Sandbox Memory size in MiB."""
envd_version: str
"""Envd version."""
_envd_access_token: Optional[str]
"""Envd access token."""
allow_internet_access: Optional[bool] = None
"""Whether internet access was explicitly enabled or disabled for the sandbox."""
network: Optional[SandboxNetworkOpts] = None
"""Sandbox network configuration."""
lifecycle: Optional[SandboxInfoLifecycle] = None
"""Sandbox lifecycle configuration."""
volume_mounts: List[Dict[str, str]] = field(default_factory=list)
"""Volume mounts for the sandbox."""
@classmethod
def _from_sandbox_data(
cls,
sandbox: Union[ListedSandbox, SandboxDetail],
envd_access_token: Optional[str] = None,
sandbox_domain: Optional[str] = None,
allow_internet_access: Optional[bool] = None,
network: Optional[SandboxNetworkOpts] = None,
lifecycle: Optional[SandboxInfoLifecycle] = None,
):
return cls(
sandbox_domain=sandbox_domain,
sandbox_id=sandbox.sandbox_id,
template_id=sandbox.template_id,
name=(sandbox.alias if isinstance(sandbox.alias, str) else None),
metadata=cast(
Dict[str, str],
sandbox.metadata if isinstance(sandbox.metadata, dict) else {},
),
started_at=sandbox.started_at,
end_at=sandbox.end_at,
state=sandbox.state,
cpu_count=sandbox.cpu_count,
memory_mb=sandbox.memory_mb,
envd_version=sandbox.envd_version,
volume_mounts=[
{"name": vm.name, "path": vm.path} for vm in sandbox.volume_mounts
]
if not isinstance(sandbox.volume_mounts, Unset)
else [],
_envd_access_token=envd_access_token,
allow_internet_access=allow_internet_access,
network=network,
lifecycle=lifecycle,
)
@classmethod
def _from_listed_sandbox(cls, listed_sandbox: ListedSandbox):
return cls._from_sandbox_data(listed_sandbox)
@classmethod
def _from_sandbox_detail(cls, sandbox_detail: SandboxDetail):
return cls._from_sandbox_data(
sandbox_detail,
(
sandbox_detail.envd_access_token
if isinstance(sandbox_detail.envd_access_token, str)
else None
),
sandbox_domain=(
sandbox_detail.domain
if isinstance(sandbox_detail.domain, str)
else None
),
allow_internet_access=(
sandbox_detail.allow_internet_access
if isinstance(sandbox_detail.allow_internet_access, bool)
else None
),
network=from_client_network_config(sandbox_detail.network),
lifecycle=from_client_lifecycle(sandbox_detail.lifecycle),
)
@dataclass
class SandboxQuery:
"""Query parameters for listing sandboxes."""
metadata: Optional[dict[str, str]] = None
"""Filter sandboxes by metadata."""
state: Optional[list[SandboxState]] = None
"""Filter sandboxes by state."""
@dataclass
class SandboxMetrics:
"""Sandbox metrics."""
cpu_count: int
"""Number of CPUs."""
cpu_used_pct: float
"""CPU usage percentage."""
disk_total: int
"""Total disk space in bytes."""
disk_used: int
"""Disk used in bytes."""
mem_total: int
"""Total memory in bytes."""
mem_used: int
"""Memory used in bytes."""
timestamp: datetime
"""Timestamp of the metric entry."""
@dataclass
class SnapshotInfo:
"""Information about a snapshot."""
snapshot_id: str
"""Snapshot identifier — template ID with tag, or namespaced name with tag (e.g. my-snapshot:latest). Can be used with Sandbox.create() to create a new sandbox from this snapshot."""
names: List[str] = field(default_factory=list)
"""Full names of the snapshot template including team namespace and tag (e.g. team-slug/my-snapshot:v2)."""
class PaginatorBase:
def __init__(
self,
limit: Optional[int] = None,
next_token: Optional[str] = None,
**opts: Unpack[ApiParams],
):
self._config = ConnectionConfig(**opts)
self.limit = limit
self._has_next = True
self._next_token = next_token
@property
def has_next(self) -> bool:
"""
Returns True if there are more items to fetch.
"""
return self._has_next
@property
def next_token(self) -> Optional[str]:
"""
Returns the next token to use for pagination.
"""
return self._next_token
class SnapshotPaginatorBase(PaginatorBase):
def __init__(
self,
sandbox_id: Optional[str] = None,
limit: Optional[int] = None,
next_token: Optional[str] = None,
**opts: Unpack[ApiParams],
):
super().__init__(limit=limit, next_token=next_token, **opts)
self.sandbox_id = sandbox_id
class SandboxPaginatorBase(PaginatorBase):
def __init__(
self,
query: Optional[SandboxQuery] = None,
limit: Optional[int] = None,
next_token: Optional[str] = None,
**opts: Unpack[ApiParams],
):
super().__init__(limit=limit, next_token=next_token, **opts)
self.query = query