devzero-sandbox 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.
- devzero_sandbox/__init__.py +41 -0
- devzero_sandbox/_bgscript.py +104 -0
- devzero_sandbox/_proto/__init__.py +1 -0
- devzero_sandbox/_proto/sandbox/__init__.py +1 -0
- devzero_sandbox/_proto/sandbox/v1/__init__.py +1 -0
- devzero_sandbox/_proto/sandbox/v1/error_pb2.py +40 -0
- devzero_sandbox/_proto/sandbox/v1/error_pb2.pyi +23 -0
- devzero_sandbox/_proto/sandbox/v1/service_connect.py +381 -0
- devzero_sandbox/_proto/sandbox/v1/service_pb2.py +227 -0
- devzero_sandbox/_proto/sandbox/v1/service_pb2.pyi +898 -0
- devzero_sandbox/auth.py +363 -0
- devzero_sandbox/commands.py +818 -0
- devzero_sandbox/connect.py +381 -0
- devzero_sandbox/errors.py +453 -0
- devzero_sandbox/files.py +217 -0
- devzero_sandbox/incluster.py +42 -0
- devzero_sandbox/mcp/__init__.py +55 -0
- devzero_sandbox/mcp/__main__.py +7 -0
- devzero_sandbox/mcp/config.py +132 -0
- devzero_sandbox/mcp/server.py +259 -0
- devzero_sandbox/mcp/tools.py +1007 -0
- devzero_sandbox/py.typed +0 -0
- devzero_sandbox/redaction.py +78 -0
- devzero_sandbox/sandbox.py +634 -0
- devzero_sandbox/terminal.py +428 -0
- devzero_sandbox/transport.py +546 -0
- devzero_sandbox-0.1.0.dist-info/METADATA +113 -0
- devzero_sandbox-0.1.0.dist-info/RECORD +31 -0
- devzero_sandbox-0.1.0.dist-info/WHEEL +4 -0
- devzero_sandbox-0.1.0.dist-info/entry_points.txt +2 -0
- devzero_sandbox-0.1.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""In-cluster trust for the sandbox gateway (ADR-005 §In-cluster certificate).
|
|
2
|
+
|
|
3
|
+
A caller pod mounts ``ConfigMap/devzero-sandbox-ca`` (published by the sandbox
|
|
4
|
+
operator into the caller's own namespace) at ``/var/run/dz-sandbox/ca.crt`` and
|
|
5
|
+
a projected service-account token at ``/var/run/dz-sandbox/token``. The gateway
|
|
6
|
+
serves ``devzero-sandbox-gateway.devzero-system.svc`` with a leaf issued by the
|
|
7
|
+
operator's in-cluster CA, so in-cluster clients trust that bundle and never
|
|
8
|
+
need ``verify=False``.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import os
|
|
14
|
+
import ssl
|
|
15
|
+
|
|
16
|
+
IN_CLUSTER_CA_PATH = "/var/run/dz-sandbox/ca.crt"
|
|
17
|
+
IN_CLUSTER_TOKEN_PATH = "/var/run/dz-sandbox/token"
|
|
18
|
+
IN_CLUSTER_GATEWAY_URL = "https://devzero-sandbox-gateway.devzero-system.svc"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class InClusterCAMissingError(FileNotFoundError):
|
|
22
|
+
"""The in-cluster CA bundle is not mounted where the SDK expects it."""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def in_cluster_ssl_context(ca_path: str = IN_CLUSTER_CA_PATH) -> ssl.SSLContext:
|
|
26
|
+
"""Return a client ``SSLContext`` that trusts only the in-cluster CA bundle.
|
|
27
|
+
|
|
28
|
+
The context verifies the certificate chain and the hostname; it does not
|
|
29
|
+
fall back to the system trust store. Pass it as ``verify=`` to an
|
|
30
|
+
``httpx.Client``. The context holds the bundle as read now: a re-issued CA
|
|
31
|
+
is published beside the old one for 30 days before it signs, and kubelet
|
|
32
|
+
refreshes the mounted file, so a client that rebuilds its context at least
|
|
33
|
+
that often, or on ``ssl.SSLCertVerificationError``, never misses a rotation.
|
|
34
|
+
"""
|
|
35
|
+
if not os.path.isfile(ca_path):
|
|
36
|
+
raise InClusterCAMissingError(
|
|
37
|
+
f"in-cluster CA bundle not found at {ca_path}; mount ConfigMap "
|
|
38
|
+
"devzero-sandbox-ca (key ca.crt) from the pod's namespace there"
|
|
39
|
+
)
|
|
40
|
+
ctx = ssl.create_default_context(ssl.Purpose.SERVER_AUTH, cafile=ca_path)
|
|
41
|
+
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
|
|
42
|
+
return ctx
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""The ``sandbox-mcp`` tools over the SDK (ADR-007-W14; the server is ADR-003-W11).
|
|
2
|
+
|
|
3
|
+
:mod:`devzero_sandbox.mcp.tools` maps the seven MCP tools of ADR-003 §MCP onto
|
|
4
|
+
SDK calls: their names, input schemas, result shapes, the defaults the model
|
|
5
|
+
does not have to pass, output truncation for a model's context, and the
|
|
6
|
+
mapping from every SDK error to a tool error. It imports nothing from the
|
|
7
|
+
``mcp`` package, so it is usable (and tested) without the ``[mcp]`` extra.
|
|
8
|
+
|
|
9
|
+
:func:`main` is the ``sandbox-mcp`` console script (ADR-003-W11): the stdio
|
|
10
|
+
server in :mod:`devzero_sandbox.mcp.server`, configured from the environment
|
|
11
|
+
(:mod:`devzero_sandbox.mcp.config`). It needs the extra:
|
|
12
|
+
``pip install 'devzero-sandbox[mcp]'``.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from collections.abc import Sequence
|
|
18
|
+
|
|
19
|
+
from devzero_sandbox.mcp.tools import (
|
|
20
|
+
TOOLS,
|
|
21
|
+
SandboxTools,
|
|
22
|
+
Settings,
|
|
23
|
+
ToolError,
|
|
24
|
+
ToolResult,
|
|
25
|
+
ToolSpec,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
30
|
+
"""Run the stdio MCP server (``sandbox-mcp``); imported lazily, so the
|
|
31
|
+
mapping above works without the ``mcp`` package."""
|
|
32
|
+
try:
|
|
33
|
+
from devzero_sandbox.mcp.server import main as serve
|
|
34
|
+
except ImportError as e:
|
|
35
|
+
if e.name is None or not e.name.startswith(("mcp", "anyio")):
|
|
36
|
+
raise
|
|
37
|
+
import sys
|
|
38
|
+
|
|
39
|
+
print(
|
|
40
|
+
"sandbox-mcp needs the mcp extra: pip install 'devzero-sandbox[mcp]'",
|
|
41
|
+
file=sys.stderr,
|
|
42
|
+
)
|
|
43
|
+
return 2
|
|
44
|
+
return serve(argv)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
__all__ = [
|
|
48
|
+
"TOOLS",
|
|
49
|
+
"SandboxTools",
|
|
50
|
+
"Settings",
|
|
51
|
+
"ToolError",
|
|
52
|
+
"ToolResult",
|
|
53
|
+
"ToolSpec",
|
|
54
|
+
"main",
|
|
55
|
+
]
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""``sandbox-mcp`` configuration, from the environment only (ADR-003-W11).
|
|
2
|
+
|
|
3
|
+
An MCP host starts the server with an ``env`` block and no terminal, so every
|
|
4
|
+
setting is an environment variable; nothing is read from or written to disk.
|
|
5
|
+
|
|
6
|
+
========================================== ===============================================
|
|
7
|
+
``DEVZERO_TOKEN`` DevZero credential (``dzu-`` PAT or ``dzs-``
|
|
8
|
+
service-account token). Required.
|
|
9
|
+
``DEVZERO_DAKR_URL`` DevZero API (default ``https://dakr.devzero.io``)
|
|
10
|
+
``DEVZERO_SANDBOX_POLICY`` ``create_sandbox``'s policy when the model names
|
|
11
|
+
none (empty: the tool lists the policies)
|
|
12
|
+
``DEVZERO_SANDBOX_CLUSTER_ID`` ``create_sandbox``'s default cluster
|
|
13
|
+
``DEVZERO_SANDBOX_CA_BUNDLE`` PEM CA bundle for a gateway with a private CA
|
|
14
|
+
(a BYO endpoint)
|
|
15
|
+
``DEVZERO_SANDBOX_MCP_CLEANUP_ON_EXIT`` delete this session's sandboxes when it ends
|
|
16
|
+
(default ``true``)
|
|
17
|
+
``DEVZERO_SANDBOX_MCP_UPLOAD_ROOT`` the only local directory ``upload`` reads from
|
|
18
|
+
(unset: ``upload`` is off); the server refuses
|
|
19
|
+
to start with the filesystem root, the home
|
|
20
|
+
directory or above it, or a credential dir
|
|
21
|
+
``DEVZERO_SANDBOX_MCP_TIMEOUT_S`` ``run_command``'s default ``timeout_s`` (60)
|
|
22
|
+
``DEVZERO_SANDBOX_MCP_MAX_TIMEOUT_S`` the largest ``timeout_s`` allowed (3600)
|
|
23
|
+
``DEVZERO_SANDBOX_MCP_MAX_OUTPUT_BYTES`` stdout / stderr bytes per command (32768)
|
|
24
|
+
``DEVZERO_SANDBOX_MCP_MAX_READ_BYTES`` largest file ``read_file`` returns (262144)
|
|
25
|
+
``DEVZERO_SANDBOX_MCP_LOG_LEVEL`` ``DEBUG`` … ``ERROR`` (default ``INFO``); logs go
|
|
26
|
+
to stderr, redacted
|
|
27
|
+
========================================== ===============================================
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
from __future__ import annotations
|
|
31
|
+
|
|
32
|
+
import os
|
|
33
|
+
from collections.abc import Mapping
|
|
34
|
+
from dataclasses import dataclass
|
|
35
|
+
|
|
36
|
+
from devzero_sandbox.mcp.tools import Settings, check_upload_root
|
|
37
|
+
from devzero_sandbox.sandbox import DEFAULT_API_URL, ENV_API_URL, ENV_TOKEN
|
|
38
|
+
|
|
39
|
+
_PREFIX = "DEVZERO_SANDBOX_MCP_"
|
|
40
|
+
_TRUE = {"1", "true", "yes", "on"}
|
|
41
|
+
_FALSE = {"0", "false", "no", "off"}
|
|
42
|
+
_LEVELS = {"DEBUG", "INFO", "WARNING", "ERROR"}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class ConfigError(ValueError):
|
|
46
|
+
"""A missing or malformed environment variable; the message names it."""
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass(frozen=True)
|
|
50
|
+
class Config:
|
|
51
|
+
token: str
|
|
52
|
+
api_url: str
|
|
53
|
+
ca_bundle: str | None
|
|
54
|
+
log_level: str
|
|
55
|
+
settings: Settings
|
|
56
|
+
|
|
57
|
+
def __repr__(self) -> str: # never print the token
|
|
58
|
+
return f"Config(api_url={self.api_url!r}, settings={self.settings!r})"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _int(env: Mapping[str, str], name: str, default: int) -> int:
|
|
62
|
+
raw = env.get(name, "").strip()
|
|
63
|
+
if not raw:
|
|
64
|
+
return default
|
|
65
|
+
try:
|
|
66
|
+
value = int(raw)
|
|
67
|
+
except ValueError:
|
|
68
|
+
raise ConfigError(f"{name} must be a whole number, got {raw!r}") from None
|
|
69
|
+
if value < 1:
|
|
70
|
+
raise ConfigError(f"{name} must be at least 1, got {value}")
|
|
71
|
+
return value
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _bool(env: Mapping[str, str], name: str, default: bool) -> bool:
|
|
75
|
+
raw = env.get(name, "").strip().lower()
|
|
76
|
+
if not raw:
|
|
77
|
+
return default
|
|
78
|
+
if raw in _TRUE:
|
|
79
|
+
return True
|
|
80
|
+
if raw in _FALSE:
|
|
81
|
+
return False
|
|
82
|
+
raise ConfigError(f"{name} must be true or false, got {raw!r}")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def from_env(env: Mapping[str, str] | None = None) -> Config:
|
|
86
|
+
"""The configuration in ``env`` (default ``os.environ``); raises :class:`ConfigError`."""
|
|
87
|
+
env = os.environ if env is None else env
|
|
88
|
+
token = env.get(ENV_TOKEN, "").strip()
|
|
89
|
+
if not token:
|
|
90
|
+
raise ConfigError(
|
|
91
|
+
f"{ENV_TOKEN} is not set: put a DevZero personal access token (dzu-...) or "
|
|
92
|
+
"team service-account token (dzs-...) in the MCP server's env"
|
|
93
|
+
)
|
|
94
|
+
ca_bundle = env.get("DEVZERO_SANDBOX_CA_BUNDLE", "").strip() or None
|
|
95
|
+
if ca_bundle is not None and not os.path.isfile(ca_bundle):
|
|
96
|
+
raise ConfigError(f"DEVZERO_SANDBOX_CA_BUNDLE: no such file {ca_bundle!r}")
|
|
97
|
+
level = env.get(_PREFIX + "LOG_LEVEL", "").strip().upper() or "INFO"
|
|
98
|
+
if level not in _LEVELS:
|
|
99
|
+
raise ConfigError(
|
|
100
|
+
f"{_PREFIX}LOG_LEVEL must be one of {sorted(_LEVELS)}, got {level!r}"
|
|
101
|
+
)
|
|
102
|
+
upload_root = env.get(_PREFIX + "UPLOAD_ROOT", "").strip()
|
|
103
|
+
if upload_root:
|
|
104
|
+
try:
|
|
105
|
+
upload_root = str(check_upload_root(upload_root))
|
|
106
|
+
except ValueError as e:
|
|
107
|
+
raise ConfigError(f"{_PREFIX}UPLOAD_ROOT: {e}") from None
|
|
108
|
+
defaults = Settings()
|
|
109
|
+
settings = Settings(
|
|
110
|
+
default_policy=env.get("DEVZERO_SANDBOX_POLICY", "").strip(),
|
|
111
|
+
default_cluster_id=env.get("DEVZERO_SANDBOX_CLUSTER_ID", "").strip(),
|
|
112
|
+
default_timeout_s=_int(env, _PREFIX + "TIMEOUT_S", defaults.default_timeout_s),
|
|
113
|
+
max_timeout_s=_int(env, _PREFIX + "MAX_TIMEOUT_S", defaults.max_timeout_s),
|
|
114
|
+
max_output_bytes=_int(
|
|
115
|
+
env, _PREFIX + "MAX_OUTPUT_BYTES", defaults.max_output_bytes
|
|
116
|
+
),
|
|
117
|
+
max_read_bytes=_int(env, _PREFIX + "MAX_READ_BYTES", defaults.max_read_bytes),
|
|
118
|
+
upload_root=upload_root,
|
|
119
|
+
cleanup_on_exit=_bool(env, _PREFIX + "CLEANUP_ON_EXIT", True),
|
|
120
|
+
)
|
|
121
|
+
if settings.default_timeout_s > settings.max_timeout_s:
|
|
122
|
+
raise ConfigError(
|
|
123
|
+
f"{_PREFIX}TIMEOUT_S ({settings.default_timeout_s}) is above "
|
|
124
|
+
f"{_PREFIX}MAX_TIMEOUT_S ({settings.max_timeout_s})"
|
|
125
|
+
)
|
|
126
|
+
return Config(
|
|
127
|
+
token=token,
|
|
128
|
+
api_url=env.get(ENV_API_URL, "").strip() or DEFAULT_API_URL,
|
|
129
|
+
ca_bundle=ca_bundle,
|
|
130
|
+
log_level=level,
|
|
131
|
+
settings=settings,
|
|
132
|
+
)
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
"""``sandbox-mcp``: the stdio MCP server over the Python SDK (ADR-003-W11).
|
|
2
|
+
|
|
3
|
+
A local process an MCP host starts with ``sandbox-mcp`` (or
|
|
4
|
+
``python -m devzero_sandbox.mcp``). It serves exactly the seven tools of
|
|
5
|
+
ADR-003 §MCP, mapped onto the SDK by :mod:`devzero_sandbox.mcp.tools`
|
|
6
|
+
(ADR-007-W14), on the official MCP Python SDK's low-level server and stdio
|
|
7
|
+
transport.
|
|
8
|
+
|
|
9
|
+
- **stdout is the protocol.** Logs go to stderr only, through the SDK's
|
|
10
|
+
redacting filter (so no token reaches them, whatever logged it); while the
|
|
11
|
+
transport serves, the MCP SDK also points fd 1 at stderr, so a stray print
|
|
12
|
+
or child process cannot corrupt the stream.
|
|
13
|
+
- **Configuration is the environment** (:mod:`devzero_sandbox.mcp.config`).
|
|
14
|
+
- **Tool failures are tool results** (``isError: true`` with the error as
|
|
15
|
+
structured content), so the model reads them and corrects its call; only an
|
|
16
|
+
unknown tool name is a JSON-RPC error.
|
|
17
|
+
- **Session end** (stdin closed, SIGTERM or SIGINT) deletes the sandboxes the
|
|
18
|
+
session created (``DEVZERO_SANDBOX_MCP_CLEANUP_ON_EXIT``, default true). A
|
|
19
|
+
tool call still running when stdin closes does not hold the session open:
|
|
20
|
+
its client is gone (MCP's stdio shutdown starts by closing stdin) and never
|
|
21
|
+
reads the result, so after :data:`EOF_GRACE_S` the session ends anyway.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import argparse
|
|
27
|
+
import json
|
|
28
|
+
import logging
|
|
29
|
+
import os
|
|
30
|
+
import signal
|
|
31
|
+
import sys
|
|
32
|
+
from collections.abc import Callable, Sequence
|
|
33
|
+
from typing import Any, NoReturn
|
|
34
|
+
|
|
35
|
+
import anyio
|
|
36
|
+
import anyio.to_thread
|
|
37
|
+
import mcp_types as types
|
|
38
|
+
from mcp.server import Server, ServerRequestContext
|
|
39
|
+
from mcp.server.stdio import stdio_server
|
|
40
|
+
from mcp.shared.exceptions import MCPError
|
|
41
|
+
from mcp.shared.message import SessionMessage
|
|
42
|
+
|
|
43
|
+
from devzero_sandbox import Client, __version__
|
|
44
|
+
from devzero_sandbox.mcp import config
|
|
45
|
+
from devzero_sandbox.mcp.tools import TOOLS, SandboxTools, ToolError
|
|
46
|
+
from devzero_sandbox.redaction import RedactingFilter, get_logger
|
|
47
|
+
|
|
48
|
+
log = get_logger("devzero_sandbox.mcp")
|
|
49
|
+
|
|
50
|
+
NAME = "devzero-sandbox"
|
|
51
|
+
|
|
52
|
+
#: How long a closed stdin waits for tool calls still running before the session
|
|
53
|
+
#: ends without them. Without it, a client that crashed mid-call would keep the
|
|
54
|
+
#: process and its sandboxes alive until the call returned: up to ``run_command``'s
|
|
55
|
+
#: ``max_timeout_s`` (an hour), or ``create_sandbox``'s wait.
|
|
56
|
+
EOF_GRACE_S = 1.0
|
|
57
|
+
|
|
58
|
+
_INSTRUCTIONS = (
|
|
59
|
+
"Run code in DevZero sandboxes: isolated Linux containers in your team's own "
|
|
60
|
+
"Kubernetes cluster. Call create_sandbox (without a policy to see the policies), "
|
|
61
|
+
"then run_command, read_file, write_file, list_files and upload with its sandbox_id; "
|
|
62
|
+
"paths are relative to /workspace. Call delete_sandbox when done; sandboxes this "
|
|
63
|
+
"session created are deleted when it ends."
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
_ANNOTATIONS = {
|
|
67
|
+
"create_sandbox": types.ToolAnnotations(
|
|
68
|
+
read_only_hint=False, destructive_hint=False, open_world_hint=True
|
|
69
|
+
),
|
|
70
|
+
"run_command": types.ToolAnnotations(
|
|
71
|
+
read_only_hint=False, destructive_hint=True, open_world_hint=True
|
|
72
|
+
),
|
|
73
|
+
"read_file": types.ToolAnnotations(read_only_hint=True, open_world_hint=False),
|
|
74
|
+
"write_file": types.ToolAnnotations(
|
|
75
|
+
read_only_hint=False, destructive_hint=True, open_world_hint=False
|
|
76
|
+
),
|
|
77
|
+
"list_files": types.ToolAnnotations(read_only_hint=True, open_world_hint=False),
|
|
78
|
+
"upload": types.ToolAnnotations(
|
|
79
|
+
read_only_hint=False, destructive_hint=True, open_world_hint=False
|
|
80
|
+
),
|
|
81
|
+
"delete_sandbox": types.ToolAnnotations(
|
|
82
|
+
read_only_hint=False,
|
|
83
|
+
destructive_hint=True,
|
|
84
|
+
idempotent_hint=True,
|
|
85
|
+
open_world_hint=False,
|
|
86
|
+
),
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
_TOOL_LIST = [
|
|
90
|
+
types.Tool(
|
|
91
|
+
name=t.name,
|
|
92
|
+
description=t.description,
|
|
93
|
+
input_schema=t.input_schema,
|
|
94
|
+
annotations=_ANNOTATIONS[t.name],
|
|
95
|
+
)
|
|
96
|
+
for t in TOOLS
|
|
97
|
+
]
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def build_server(tools: SandboxTools) -> Server[Any]:
|
|
101
|
+
"""The MCP server for ``tools``: ``tools/list`` and ``tools/call``, nothing else."""
|
|
102
|
+
|
|
103
|
+
async def list_tools(
|
|
104
|
+
ctx: ServerRequestContext[Any], params: types.PaginatedRequestParams | None
|
|
105
|
+
) -> types.ListToolsResult:
|
|
106
|
+
return types.ListToolsResult(tools=_TOOL_LIST)
|
|
107
|
+
|
|
108
|
+
async def call_tool(
|
|
109
|
+
ctx: ServerRequestContext[Any], params: types.CallToolRequestParams
|
|
110
|
+
) -> types.CallToolResult:
|
|
111
|
+
name = params.name
|
|
112
|
+
if name not in _ANNOTATIONS:
|
|
113
|
+
raise MCPError(types.INVALID_PARAMS, f"unknown tool: {name}")
|
|
114
|
+
log.info("tool %s called", name)
|
|
115
|
+
try:
|
|
116
|
+
# The SDK is synchronous: each call runs in a worker thread.
|
|
117
|
+
result = await anyio.to_thread.run_sync(
|
|
118
|
+
tools.call, name, dict(params.arguments or {})
|
|
119
|
+
)
|
|
120
|
+
except ToolError as e:
|
|
121
|
+
log.info("tool %s failed: %s", name, e)
|
|
122
|
+
body = e.to_dict()
|
|
123
|
+
return types.CallToolResult(
|
|
124
|
+
content=[types.TextContent(type="text", text=json.dumps(body))],
|
|
125
|
+
structured_content=body,
|
|
126
|
+
is_error=True,
|
|
127
|
+
)
|
|
128
|
+
return types.CallToolResult(
|
|
129
|
+
content=[types.TextContent(type="text", text=result.text)],
|
|
130
|
+
structured_content=result.structured,
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
return Server(
|
|
134
|
+
NAME,
|
|
135
|
+
version=__version__,
|
|
136
|
+
title="DevZero sandboxes",
|
|
137
|
+
instructions=_INSTRUCTIONS,
|
|
138
|
+
on_list_tools=list_tools,
|
|
139
|
+
on_call_tool=call_tool,
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
async def serve(tools: SandboxTools, finish: Callable[[], None]) -> None:
|
|
144
|
+
"""Serve one MCP session on stdin/stdout until stdin closes or a signal arrives.
|
|
145
|
+
|
|
146
|
+
On SIGTERM or SIGINT the session ends at once: ``finish`` (which deletes
|
|
147
|
+
the session's sandboxes) runs and the process exits 0. Cancelling the
|
|
148
|
+
transport is not enough, because its stdin reader blocks in a worker
|
|
149
|
+
thread until a line or EOF arrives, and a host may signal with stdin open.
|
|
150
|
+
When stdin closes, the server loop returns once the calls in flight are
|
|
151
|
+
answered; if one is still running after :data:`EOF_GRACE_S`, the session
|
|
152
|
+
ends the same way, since nobody is left to read its result.
|
|
153
|
+
"""
|
|
154
|
+
server = build_server(tools)
|
|
155
|
+
ending = False
|
|
156
|
+
|
|
157
|
+
async def end_session(why: str) -> NoReturn:
|
|
158
|
+
nonlocal ending
|
|
159
|
+
if ending:
|
|
160
|
+
# A second trigger (SIGTERM while stdin's EOF ends the session) waits
|
|
161
|
+
# for the first, which deletes the sandboxes and exits.
|
|
162
|
+
await anyio.sleep_forever()
|
|
163
|
+
ending = True
|
|
164
|
+
log.info("%s; ending the session", why)
|
|
165
|
+
await anyio.to_thread.run_sync(finish)
|
|
166
|
+
logging.shutdown()
|
|
167
|
+
os._exit(0)
|
|
168
|
+
|
|
169
|
+
async with anyio.create_task_group() as tg:
|
|
170
|
+
if sys.platform != "win32":
|
|
171
|
+
|
|
172
|
+
async def stop_on_signal() -> None:
|
|
173
|
+
with anyio.open_signal_receiver(signal.SIGTERM, signal.SIGINT) as sigs:
|
|
174
|
+
async for signum in sigs:
|
|
175
|
+
await end_session(f"received {signal.Signals(signum).name}")
|
|
176
|
+
|
|
177
|
+
tg.start_soon(stop_on_signal)
|
|
178
|
+
served = anyio.Event()
|
|
179
|
+
to_server, from_stdin = anyio.create_memory_object_stream[
|
|
180
|
+
SessionMessage | Exception
|
|
181
|
+
]()
|
|
182
|
+
|
|
183
|
+
async with stdio_server() as (stdin_stream, write_stream):
|
|
184
|
+
|
|
185
|
+
async def relay_stdin() -> None:
|
|
186
|
+
async with to_server:
|
|
187
|
+
async for message in stdin_stream:
|
|
188
|
+
await to_server.send(message)
|
|
189
|
+
with anyio.move_on_after(EOF_GRACE_S):
|
|
190
|
+
await served.wait()
|
|
191
|
+
if not served.is_set():
|
|
192
|
+
await end_session("stdin closed with a tool call still running")
|
|
193
|
+
|
|
194
|
+
tg.start_soon(relay_stdin)
|
|
195
|
+
await server.run(
|
|
196
|
+
from_stdin, write_stream, server.create_initialization_options()
|
|
197
|
+
)
|
|
198
|
+
served.set()
|
|
199
|
+
tg.cancel_scope.cancel()
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def configure_logging(level: str) -> None:
|
|
203
|
+
"""Every log record to stderr, redacted; stdout carries only the protocol."""
|
|
204
|
+
handler = logging.StreamHandler(sys.stderr)
|
|
205
|
+
handler.addFilter(RedactingFilter()) # covers httpx, mcp and every other library
|
|
206
|
+
handler.setFormatter(
|
|
207
|
+
logging.Formatter("%(asctime)s %(levelname)s %(name)s: %(message)s")
|
|
208
|
+
)
|
|
209
|
+
root = logging.getLogger()
|
|
210
|
+
root.handlers[:] = [handler]
|
|
211
|
+
root.setLevel(level)
|
|
212
|
+
# httpx logs every request line at INFO; keep that for DEBUG.
|
|
213
|
+
logging.getLogger("httpx").setLevel(
|
|
214
|
+
max(logging.getLevelName(level), logging.WARNING)
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _parser() -> argparse.ArgumentParser:
|
|
219
|
+
return argparse.ArgumentParser(
|
|
220
|
+
prog="sandbox-mcp",
|
|
221
|
+
description="DevZero sandboxes MCP server (stdio). Configured from the environment: "
|
|
222
|
+
"DEVZERO_TOKEN (required), DEVZERO_DAKR_URL, DEVZERO_SANDBOX_POLICY, "
|
|
223
|
+
"DEVZERO_SANDBOX_CLUSTER_ID, DEVZERO_SANDBOX_CA_BUNDLE and DEVZERO_SANDBOX_MCP_* "
|
|
224
|
+
"(see devzero_sandbox.mcp.config).",
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
229
|
+
"""The ``sandbox-mcp`` console script."""
|
|
230
|
+
parser = _parser()
|
|
231
|
+
parser.add_argument(
|
|
232
|
+
"--version", action="version", version=f"%(prog)s {__version__}"
|
|
233
|
+
)
|
|
234
|
+
parser.parse_args(argv)
|
|
235
|
+
try:
|
|
236
|
+
cfg = config.from_env()
|
|
237
|
+
except config.ConfigError as e:
|
|
238
|
+
print(f"sandbox-mcp: {e}", file=sys.stderr)
|
|
239
|
+
return 2
|
|
240
|
+
configure_logging(cfg.log_level)
|
|
241
|
+
gateway_options: dict[str, Any] = {}
|
|
242
|
+
if cfg.ca_bundle:
|
|
243
|
+
gateway_options["ca_bundle"] = cfg.ca_bundle
|
|
244
|
+
client = Client(cfg.token, api_url=cfg.api_url, gateway_options=gateway_options)
|
|
245
|
+
tools = SandboxTools(client, cfg.settings)
|
|
246
|
+
|
|
247
|
+
def finish() -> None:
|
|
248
|
+
tools.close() # deletes this session's sandboxes (cleanup_on_exit); idempotent
|
|
249
|
+
client.close()
|
|
250
|
+
log.info("session ended")
|
|
251
|
+
|
|
252
|
+
log.info("sandbox-mcp %s serving on stdio (API %s)", __version__, cfg.api_url)
|
|
253
|
+
try:
|
|
254
|
+
anyio.run(serve, tools, finish)
|
|
255
|
+
except KeyboardInterrupt:
|
|
256
|
+
pass
|
|
257
|
+
finally:
|
|
258
|
+
finish()
|
|
259
|
+
return 0
|