-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathmcp_server_code_execution_mode.py
More file actions
2798 lines (2418 loc) · 105 KB
/
mcp_server_code_execution_mode.py
File metadata and controls
2798 lines (2418 loc) · 105 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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""MCP Server Code Execution Mode bridge backed by a containerised sandbox."""
from __future__ import annotations
import asyncio
import copy
import json
import keyword
import logging
import os
import re
import shlex
import shutil
import sys
try:
import tomllib
except ImportError:
tomllib = None
import inspect
import io
import tempfile
import textwrap
from asyncio import subprocess as aio_subprocess
from contextlib import suppress
from dataclasses import dataclass
from pathlib import Path
from typing import (
Any,
Awaitable,
Callable,
Dict,
List,
Literal,
NamedTuple,
Optional,
Protocol,
Sequence,
Tuple,
Union,
cast,
)
import anyio
from packaging.version import parse as _parse_version
_toon_encode: Optional[Callable[..., str]] = None
try: # Prefer the official encoder when available
import toon_format as _toon_format
_toon_encode = _toon_format.encode
except ImportError: # pragma: no cover - fallback for environments without toon
_toon_encode = None
def _check_pydantic_compatibility() -> None:
"""Check and warn/abort early for Pydantic/typing incompatibilities.
Some older Pydantic versions (or environments that shadow the stdlib
``typing`` module with a PyPI package) can cause runtime failures when
used with CPython 3.14. We try a minimal import and version check and fail
with an actionable message to help users upgrade.
"""
try:
import importlib
typing_mod = importlib.import_module("typing")
typing_file = getattr(typing_mod, "__file__", "") or "(built-in)"
except Exception: # pragma: no cover - defensive
typing_file = "(unknown)"
try:
import pydantic
pyd_version = getattr(pydantic, "__version__", "0")
except Exception as exc: # pragma: no cover - this covers TypeError mishaps
err_text = str(exc)
if "prefer_fwd_module" in err_text or "_eval_type" in err_text:
raise RuntimeError(
"Pydantic appears incompatible with the current Python/typing\n"
"configuration: \n\n"
" - This usually happens if an old version of pydantic is installed\n"
" or if a PyPI-provided 'typing' package is shadowing the standard\n"
" library typing module.\n\n"
"Recommended actions:\n"
" 1. Upgrade pydantic (e.g. `pip install -U pydantic`).\n"
" 2. If you have a 'typing' package installed from PyPI, uninstall it:\n"
" `pip uninstall typing` or `pipx uninstall typing`.\n"
" 3. Recreate the virtual environment and re-run `uv sync`.\n\n"
"For more info, check the platform and installed packages.\n"
f"typing module path: {typing_file}\n"
f"pydantic import error: {err_text}\n"
) from exc
raise
try:
if _parse_version(pyd_version) < _parse_version(
"2.12.0"
) and sys.version_info >= (3, 14):
raise RuntimeError(
f"Detected pydantic {pyd_version} in a Python 3.14 environment -\n"
"please upgrade pydantic to a more recent 2.x release (e.g., `pip install -U pydantic`)."
)
except Exception: # pragma: no cover - diagnostic fallback
pass
_check_pydantic_compatibility()
from mcp.client.session import ( # noqa: E402 (import intentionally delayed for compatibility checks)
ClientSession,
)
from mcp.client.stdio import StdioServerParameters, stdio_client # noqa: E402
from mcp.server import Server # noqa: E402
from mcp.server.stdio import stdio_server # noqa: E402
from mcp.shared.exceptions import McpError # noqa: E402
from mcp.types import ( # noqa: E402
INVALID_PARAMS,
CallToolResult,
ErrorData,
Resource,
TextContent,
Tool,
)
logger = logging.getLogger("mcp-server-code-execution-mode")
BRIDGE_NAME = "mcp-server-code-execution-mode"
DEFAULT_IMAGE = os.environ.get("MCP_BRIDGE_IMAGE", "python:3.14-slim")
DEFAULT_RUNTIME = os.environ.get("MCP_BRIDGE_RUNTIME")
DEFAULT_TIMEOUT = int(os.environ.get("MCP_BRIDGE_TIMEOUT", "30"))
MAX_TIMEOUT = int(os.environ.get("MCP_BRIDGE_MAX_TIMEOUT", "120"))
DEFAULT_MEMORY = os.environ.get("MCP_BRIDGE_MEMORY", "512m")
DEFAULT_PIDS = int(os.environ.get("MCP_BRIDGE_PIDS", "128"))
DEFAULT_CPUS = os.environ.get("MCP_BRIDGE_CPUS")
CONTAINER_USER = os.environ.get("MCP_BRIDGE_CONTAINER_USER", "65534:65534")
DEFAULT_RUNTIME_IDLE_TIMEOUT = int(
os.environ.get("MCP_BRIDGE_RUNTIME_IDLE_TIMEOUT", "300")
)
_ALLOW_SELF_SERVER = os.environ.get(
"MCP_BRIDGE_ALLOW_SELF_SERVER", "0"
).strip().lower() in {
"1",
"true",
"yes",
}
_SELF_SERVER_TOKENS = {
BRIDGE_NAME.lower(),
"mcp_server_code_execution_mode",
"mcp-server-code-execution-mode",
}
_PODMAN_PULL_PREFIXES: tuple[str, ...] = (
'Resolved "',
"Trying to pull",
"Getting image source signatures",
"Copying blob",
"Copying config",
"Extracting",
"Writing manifest",
"Storing signatures",
)
SANDBOX_HELPERS_SUMMARY = (
"Persistent Python Sandbox (state retained between tool calls). "
"1. DISCOVER: `runtime.discovered_servers()`, `runtime.search_tool_docs('query')`. "
"Use `discovered_servers(detailed=True)` for descriptions. "
"2. CALL: `await mcp_server.tool()`. "
"3. PERSIST: `save_tool(func)` for functions, `save_memory(key, value)` for data. "
"4. MEMORY: `load_memory(key)`, `list_memories()`, `update_memory(key, fn)`. "
"Run `print(runtime.capability_summary())` for the full manual."
)
_NOISE_STREAM_TOKENS = {"()"}
CAPABILITY_RESOURCE_URI = "resource://mcp-server-code-execution-mode/capabilities"
_CAPABILITY_RESOURCE_NAME = "code-execution-capabilities"
_CAPABILITY_RESOURCE_TITLE = "Code Execution Sandbox Helpers"
_CAPABILITY_RESOURCE_DESCRIPTION = "Capability overview, helper reference, and sandbox usage notes (call runtime.capability_summary() inside the sandbox for this text)."
_CAPABILITY_RESOURCE_TEXT = textwrap.dedent(
f"""
# Code Execution MCP Capabilities
{SANDBOX_HELPERS_SUMMARY}
## Quick usage
- Pass `servers=[...]` to mount MCP proxies (`mcp_<alias>` modules).
- Import `mcp.runtime as runtime`; call `runtime.capability_summary()` instead of rereading this resource for the same hint.
- Prefer the `_sync` helpers first to read cached metadata before issuing RPCs.
- Server configs support a `cwd` field to start the host MCP server in a specific working directory.
- LLMs should check `runtime.describe_server(name)` or `runtime.list_loaded_server_metadata()` for the server's configured `cwd` before assuming the working directory.
If `cwd` is absent, the host starts the server in the bridge process' current directory (i.e., the default working directory). If your workload expects a specific working directory, please configure `cwd` in the server config or run the server in a container that mounts the project directory.
Resource URI: {CAPABILITY_RESOURCE_URI}
"""
).strip()
def _build_capability_resource() -> Resource:
return Resource(
name=_CAPABILITY_RESOURCE_NAME,
title=_CAPABILITY_RESOURCE_TITLE,
description=_CAPABILITY_RESOURCE_DESCRIPTION,
uri=CAPABILITY_RESOURCE_URI, # type: ignore[arg-type]
mimeType="text/markdown",
size=len(_CAPABILITY_RESOURCE_TEXT.encode("utf-8")),
)
class ConfigSource(NamedTuple):
path: Path
type: Literal["file", "directory"]
format: Literal["json", "toml"] = "json"
name: str = "Unknown"
# Platform-specific paths
_IS_MACOS = sys.platform == "darwin"
_IS_LINUX = sys.platform.startswith("linux")
CONFIG_SOURCES = [
# Primary: User MCPs directory (recommended)
ConfigSource(Path.home() / "MCPs", "directory", name="User MCPs"),
# Standard MCP config directory
ConfigSource(
Path.home() / ".config" / "mcp" / "servers", "directory", name="Standard MCP"
),
# Local project configs
ConfigSource(Path.cwd() / "mcp-servers", "directory", name="Local Project"),
ConfigSource(Path.cwd() / ".vscode" / "mcp.json", "file", name="VS Code Workspace"),
# Claude configs
ConfigSource(Path.home() / ".claude.json", "file", name="Claude CLI"),
# Cursor
ConfigSource(Path.home() / ".cursor" / "mcp.json", "file", name="Cursor"),
# OpenCode
ConfigSource(Path.home() / ".opencode.json", "file", name="OpenCode CLI"),
# Windsurf/Codeium
ConfigSource(
Path.home() / ".codeium" / "windsurf" / "mcp_config.json",
"file",
name="Windsurf",
),
]
# Add platform-specific paths
if _IS_MACOS:
CONFIG_SOURCES.extend([
ConfigSource(
Path.home()
/ "Library"
/ "Application Support"
/ "Claude Code"
/ "claude_code_config.json",
"file",
name="Claude Code (macOS)",
),
ConfigSource(
Path.home()
/ "Library"
/ "Application Support"
/ "Claude"
/ "claude_desktop_config.json",
"file",
name="Claude Desktop (macOS)",
),
ConfigSource(
Path.home()
/ "Library"
/ "Application Support"
/ "Code"
/ "User"
/ "settings.json",
"file",
name="VS Code Global (macOS)",
),
])
elif _IS_LINUX:
CONFIG_SOURCES.extend([
ConfigSource(
Path.home() / ".config" / "Code" / "User" / "settings.json",
"file",
name="VS Code Global (Linux)",
),
])
class SandboxError(RuntimeError):
"""Raised when the sandbox cannot execute user code."""
def __init__(self, message: str, *, stdout: str = "", stderr: str = "") -> None:
super().__init__(message)
self.stdout = stdout
self.stderr = stderr
class ClientLike(Protocol):
async def list_tools(
self,
) -> List[Dict[str, object]]: # pragma: no cover - typing only
...
async def call_tool(
self, name: str, arguments: Dict[str, object]
) -> Dict[str, object]: # pragma: no cover - typing only
...
async def stop(self) -> None: # pragma: no cover - typing only
...
class SandboxLike(Protocol):
async def execute(
self, code: str, **kwargs
) -> SandboxResult: # pragma: no cover - typing only
...
async def ensure_shared_directory(
self, path: Path
) -> None: # pragma: no cover - typing only
...
class SandboxTimeout(SandboxError):
"""Raised when user code exceeds the configured timeout."""
@dataclass
class SandboxResult:
"""Execution result captured from the sandbox."""
success: bool
exit_code: int
stdout: str
stderr: str
@dataclass
class MCPServerInfo:
"""Configuration for a single MCP server binary."""
name: str
command: str
args: List[str]
env: Dict[str, str]
cwd: Optional[str] = None
description: str = ""
def _looks_like_self_server(
info: Union[MCPServerInfo, Dict[str, Any]], name: Optional[str] = None
) -> bool:
"""Return True if the config appears to launch this bridge itself."""
if isinstance(info, MCPServerInfo):
server_name = info.name.lower()
command = info.command
args = info.args
else:
server_name = (name or "").lower()
command = str(info.get("command", ""))
raw_args = info.get("args", [])
args = [str(a) for a in raw_args] if isinstance(raw_args, list) else []
if server_name in _SELF_SERVER_TOKENS:
return True
command_name = Path(command).name.lower()
if command_name in _SELF_SERVER_TOKENS or command_name.endswith(
"mcp_server_code_execution_mode.py"
):
return True
for arg in args:
arg_lower = str(arg).lower()
arg_name = Path(arg_lower).name
if (
arg_lower in _SELF_SERVER_TOKENS
or arg_name.lower() in _SELF_SERVER_TOKENS
or arg_lower.endswith("mcp_server_code_execution_mode.py")
):
return True
return False
def _split_output_lines(stream: Optional[str]) -> List[str]:
"""Return a newline-preserving list for stdout/stderr fields."""
if not stream:
return []
return stream.splitlines()
def _filter_stream_lines(lines: Sequence[str]) -> List[str]:
"""Drop whitespace-only or noise-only lines to save response tokens."""
filtered: List[str] = []
for line in lines:
text = str(line)
stripped = text.strip()
if not stripped or stripped in _NOISE_STREAM_TOKENS:
continue
filtered.append(text)
return filtered
def _render_toon_block(payload: Dict[str, object]) -> str:
"""Encode a payload in TOON format, falling back to JSON when unavailable."""
if _toon_encode is not None:
try:
body = _toon_encode(payload)
except Exception: # pragma: no cover - defensive fallback
logger.debug("Failed to encode payload as TOON", exc_info=True)
else:
body = body.rstrip()
return f"```toon\n{body}\n```" if body else "```toon\n```"
fallback = json.dumps(payload, indent=2, sort_keys=True)
return f"```json\n{fallback}\n```"
def _output_mode() -> str:
"""Return the configured output mode."""
return os.environ.get("MCP_BRIDGE_OUTPUT_MODE", "compact").strip().lower()
def _render_compact_output(payload: Dict[str, object]) -> str:
"""Render a terse, token-efficient textual summary."""
lines: List[str] = []
stdout_raw = payload.get("stdout", ())
if isinstance(stdout_raw, (list, tuple)):
stdout_lines = list(stdout_raw)
else:
stdout_lines = []
stderr_raw = payload.get("stderr", ())
if isinstance(stderr_raw, (list, tuple)):
stderr_lines = list(stderr_raw)
else:
stderr_lines = []
if stdout_lines:
lines.append("\n".join(str(item) for item in stdout_lines))
if stderr_lines:
stderr_text = "\n".join(str(item) for item in stderr_lines)
lines.append(f"stderr:\n{stderr_text}")
status = str(payload.get("status", ""))
exit_code = payload.get("exitCode")
error = payload.get("error")
if not lines and payload.get("summary"):
lines.append(str(payload["summary"]))
if error and (not lines or status != "error"):
lines.append(f"error: {error}")
if exit_code not in (None, 0):
lines.insert(0, f"exit: {exit_code}")
if status and status.lower() not in {"", "success"}:
lines.insert(0, f"status: {status}")
text = "\n".join(line for line in lines if line).strip()
if text:
return text
if status:
return status
return str(payload.get("summary", "")).strip() or "success"
def _build_compact_structured_payload(payload: Dict[str, object]) -> Dict[str, object]:
"""Return a trimmed structured representation for compact responses."""
compact: Dict[str, object] = {}
status = str(payload.get("status", ""))
exit_code = payload.get("exitCode")
if status and status.lower() != "success":
compact["status"] = status
if exit_code not in (None, 0):
compact["exitCode"] = exit_code
if payload.get("stdout"):
compact["stdout"] = payload["stdout"]
if payload.get("stderr"):
compact["stderr"] = payload["stderr"]
if payload.get("servers"):
compact["servers"] = payload["servers"]
if payload.get("timeoutSeconds"):
compact["timeoutSeconds"] = payload["timeoutSeconds"]
if payload.get("error"):
compact["error"] = payload["error"]
summary = payload.get("summary")
if summary and (status.lower() != "success" or not compact.get("stdout")):
compact["summary"] = summary
return compact or {
key: payload[key] for key in ("status", "summary") if key in payload
}
def _build_response_payload(
*,
status: str,
summary: str,
exit_code: Optional[int] = None,
stdout: Optional[str] = None,
stderr: Optional[str] = None,
servers: Optional[Sequence[str]] = None,
error: Optional[str] = None,
timeout_seconds: Optional[int] = None,
) -> Dict[str, object]:
"""Create a structured payload shared by compact/TOON responses."""
summary_lower = summary.strip().lower()
payload: Dict[str, object] = {
"status": status,
"summary": summary,
}
if exit_code is not None:
payload["exitCode"] = exit_code
if servers:
payload["servers"] = list(servers)
stdout_lines = _filter_stream_lines(_split_output_lines(stdout))
if stdout_lines:
payload["stdout"] = stdout_lines
stderr_lines = _filter_stream_lines(_split_output_lines(stderr))
if stderr_lines:
payload["stderr"] = stderr_lines
if error:
payload["error"] = error
if timeout_seconds is not None:
payload["timeoutSeconds"] = timeout_seconds
if (
status.lower() == "success"
and not payload.get("stdout")
and not payload.get("stderr")
and summary_lower == "success"
):
payload["summary"] = "Success (no output)"
return {key: value for key, value in payload.items() if not _is_empty_field(value)}
def _is_empty_field(value: object) -> bool:
"""Return True when a structured field should be omitted."""
if value is None:
return True
if isinstance(value, (list, tuple, set, dict, str)):
return len(value) == 0
return False
def _build_tool_response(
*,
status: str,
summary: str,
exit_code: Optional[int] = None,
stdout: Optional[str] = None,
stderr: Optional[str] = None,
servers: Optional[Sequence[str]] = None,
error: Optional[str] = None,
timeout_seconds: Optional[int] = None,
) -> CallToolResult:
"""Render a tool response in compact text (default) or TOON format."""
payload = _build_response_payload(
status=status,
summary=summary,
exit_code=exit_code,
stdout=stdout,
stderr=stderr,
servers=servers,
error=error,
timeout_seconds=timeout_seconds,
)
status = str(payload.get("status", "error")).lower()
is_error = status not in {"success"}
mode = _output_mode()
if mode == "compact":
message = _render_compact_output(payload)
structured = _build_compact_structured_payload(payload)
return CallToolResult(
content=[TextContent(type="text", text=message)],
structuredContent=structured,
isError=is_error,
)
message = _render_toon_block(payload)
return CallToolResult(
content=[TextContent(type="text", text=message)],
structuredContent=payload,
isError=is_error,
)
def _sanitize_identifier(value: str, *, default: str) -> str:
"""Convert an arbitrary string into a valid Python identifier."""
cleaned = re.sub(r"[^0-9a-zA-Z_]+", "_", value.strip())
cleaned = cleaned.lower() or default
if cleaned[0].isdigit():
cleaned = f"_{cleaned}"
if keyword.iskeyword(cleaned):
cleaned = f"{cleaned}_"
return cleaned
class PersistentMCPClient:
"""Maintain a persistent MCP stdio session."""
def __init__(self, server_info: MCPServerInfo) -> None:
self.server_info = server_info
self._stdio_cm: Optional[Any] = None
self._session: Optional[ClientSession] = None
self._forward_task: Optional[asyncio.Task[None]] = None
self._captured_stderr: Optional[io.TextIOBase] = None
async def start(self) -> None:
if self._session:
return
params = StdioServerParameters(
command=self.server_info.command,
args=self.server_info.args,
env=self.server_info.env or None,
cwd=self.server_info.cwd or None,
)
# Capture stderr in a real file object for cross-platform compatibility
self._captured_stderr = tempfile.TemporaryFile(mode="w+t", encoding="utf-8")
# Only pass errlog if stdio_client supports it (tests may patch stdio_client)
if "errlog" in inspect.signature(stdio_client).parameters:
client_cm = stdio_client(params, errlog=self._captured_stderr)
else:
client_cm = stdio_client(params)
self._stdio_cm = client_cm
raw_read_stream, write_stream = await client_cm.__aenter__()
# Create a filtered reader stream to hide benign XML/blank-line JSON parse errors
filtered_writer, filtered_read = anyio.create_memory_object_stream(0)
async def _forward_read() -> None:
try:
async with filtered_writer:
async for item in raw_read_stream:
# Filter out JSON parse errors that are likely caused by stray blank lines
if isinstance(item, Exception):
message = str(item)
if (
"Invalid JSON" in message
and "EOF while parsing a value" in message
and "input_value='\\n'" in message
):
# ignore blank line parse errors
continue
await filtered_writer.send(item)
except anyio.ClosedResourceError:
await anyio.lowlevel.checkpoint()
# Launch the forwarder task
self._forward_task = asyncio.create_task(_forward_read())
session = ClientSession(filtered_read, write_stream)
await session.__aenter__()
try:
await session.initialize()
except Exception as exc: # pragma: no cover - initialization failure reporting
# Read captured stderr content for diagnostics if present
stderr_text = ""
if self._captured_stderr is not None:
try:
self._captured_stderr.seek(0)
stderr_text = self._captured_stderr.read()
except Exception:
stderr_text = "<failed to read captured stderr>"
logger.debug(
"Client session failed to initialize: %s (stderr=%s)", exc, stderr_text
)
# Re-raise for callers to handle; captured stderr is useful for debugging
raise
self._session = session
async def list_tools(self) -> List[Dict[str, object]]:
if not self._session:
raise SandboxError("MCP client not started")
result = await self._session.list_tools()
return [
tool.model_dump(by_alias=True, exclude_none=True) for tool in result.tools
]
async def call_tool(
self, name: str, arguments: Dict[str, object]
) -> Dict[str, object]:
if not self._session:
raise SandboxError("MCP client not started")
call_result = await self._session.call_tool(name=name, arguments=arguments)
return call_result.model_dump(by_alias=True, exclude_none=True)
async def stop(self) -> None:
if self._session:
try:
await self._session.__aexit__(None, None, None)
except* Exception as exc: # pragma: no cover - defensive cleanup
logger.debug("MCP session shutdown raised %s", exc, exc_info=True)
finally:
self._session = None
if self._stdio_cm:
try:
await self._stdio_cm.__aexit__(None, None, None) # type: ignore[union-attr]
except* Exception as exc: # pragma: no cover - defensive cleanup
logger.debug("MCP stdio shutdown raised %s", exc, exc_info=True)
finally:
self._stdio_cm = None
# Ensure the forwarder task is cancelled
if self._forward_task:
task = self._forward_task
self._forward_task = None
task.cancel()
with suppress(asyncio.CancelledError):
await task
if self._captured_stderr is not None:
try:
self._captured_stderr.close()
except Exception:
pass
self._captured_stderr = None
class RootlessContainerSandbox:
"""Execute Python code in a locked-down container."""
def __init__(
self,
*,
runtime: Optional[str] = None,
image: str = DEFAULT_IMAGE,
memory_limit: str = DEFAULT_MEMORY,
pids_limit: int = DEFAULT_PIDS,
cpu_limit: Optional[str] = DEFAULT_CPUS,
runtime_idle_timeout: int = DEFAULT_RUNTIME_IDLE_TIMEOUT,
) -> None:
self.runtime = detect_runtime(runtime)
self.image = image
self.memory_limit = memory_limit
self.pids_limit = pids_limit
self.cpu_limit = cpu_limit
self._runtime_check_lock = asyncio.Lock()
self.runtime_idle_timeout = max(0, runtime_idle_timeout)
self._shutdown_task: Optional[asyncio.Task[None]] = None
self._share_lock = asyncio.Lock()
self._shared_paths: set[str] = set()
self._process: Optional[asyncio.subprocess.Process] = None
def _base_cmd(self) -> List[str]:
if not self.runtime:
raise SandboxError(
"No container runtime found. Install podman or rootless docker and set "
"MCP_BRIDGE_RUNTIME if multiple runtimes are available."
)
cmd: List[str] = [
self.runtime,
"run",
"--rm",
"--interactive",
"--network",
"none",
"--read-only",
"--pids-limit",
str(self.pids_limit),
"--memory",
self.memory_limit,
"--tmpfs",
"/tmp:rw,noexec,nosuid,nodev,size=64m",
"--tmpfs",
"/workspace:rw,noexec,nosuid,nodev,size=128m",
"--workdir",
"/workspace",
"--env",
"HOME=/workspace",
"--env",
"PYTHONUNBUFFERED=1",
"--env",
"PYTHONIOENCODING=utf-8",
"--env",
"PYTHONDONTWRITEBYTECODE=1",
"--security-opt",
"no-new-privileges",
"--cap-drop",
"ALL",
"--user",
CONTAINER_USER,
]
if self.cpu_limit:
cmd.extend(["--cpus", self.cpu_limit])
return cmd
def _render_entrypoint(
self,
servers_metadata: Sequence[Dict[str, object]],
discovered_servers: Dict[str, str],
) -> str:
metadata_json = json.dumps(servers_metadata, separators=(",", ":"))
discovered_json = json.dumps(discovered_servers, separators=(",", ":"))
template = textwrap.dedent(
"""
import asyncio
import inspect
import json
import sys
import traceback
import types
from contextlib import suppress
from pathlib import Path
AVAILABLE_SERVERS = json.loads(__METADATA_JSON__)
DISCOVERED_SERVERS = json.loads(__DISCOVERED_JSON__)
USER_TOOLS_PATH = Path("/projects/user_tools.py")
MEMORY_DIR = Path("/projects/memory")
_PENDING_RESPONSES = {}
_REQUEST_COUNTER = 0
_EXECUTION_QUEUE = asyncio.Queue()
def _send_message(message):
sys.__stdout__.write(json.dumps(message, separators=(",", ":")) + "\\n")
sys.__stdout__.flush()
class _StreamProxy:
def __init__(self, kind):
self._kind = kind
def write(self, data):
if not data:
return
_send_message({"type": self._kind, "data": data})
def flush(self):
pass
def isatty(self):
return False
sys.stdout = _StreamProxy("stdout")
sys.stderr = _StreamProxy("stderr")
async def _stdin_reader():
loop = asyncio.get_running_loop()
reader = asyncio.StreamReader()
protocol = asyncio.StreamReaderProtocol(reader)
await loop.connect_read_pipe(lambda: protocol, sys.stdin)
while True:
line = await reader.readline()
if not line:
sys.exit(0)
try:
message = json.loads(line.decode())
except Exception:
continue
msg_type = message.get("type")
if msg_type == "rpc_response":
request_id = message.get("id")
future = _PENDING_RESPONSES.pop(request_id, None)
if future and not future.done():
if message.get("success", True):
future.set_result(message.get("payload"))
else:
future.set_exception(RuntimeError(message.get("error", "RPC error")))
elif msg_type == "execute":
await _EXECUTION_QUEUE.put(message.get("code"))
# The original try/finally block for transport is removed as per instruction.
async def _rpc_call(payload):
loop = asyncio.get_running_loop()
global _REQUEST_COUNTER
_REQUEST_COUNTER += 1
request_id = _REQUEST_COUNTER
future = loop.create_future()
_PENDING_RESPONSES[request_id] = future
_send_message({"type": "rpc_request", "id": request_id, "payload": payload})
return await future
def _install_mcp_modules():
mcp_pkg = types.ModuleType("mcp")
mcp_pkg.__path__ = []
mcp_pkg.__all__ = ["runtime", "servers"]
sys.modules["mcp"] = mcp_pkg
runtime_module = types.ModuleType("mcp.runtime")
servers_module = types.ModuleType("mcp.servers")
servers_module.__path__ = []
sys.modules["mcp.runtime"] = runtime_module
sys.modules["mcp.servers"] = servers_module
mcp_pkg.runtime = runtime_module
mcp_pkg.servers = servers_module
# Load user tools if they exist
if USER_TOOLS_PATH.exists():
try:
import importlib.util
spec = importlib.util.spec_from_file_location("user_tools", USER_TOOLS_PATH)
if spec and spec.loader:
user_tools = importlib.util.module_from_spec(spec)
sys.modules["user_tools"] = user_tools
spec.loader.exec_module(user_tools)
# Export everything from user_tools to global namespace
for name, val in vars(user_tools).items():
if not name.startswith("_"):
globals()[name] = val
except Exception:
pass
def save_tool(func):
'''Saves a function as a persistent tool available in future sessions.'''
if not inspect.isfunction(func):
raise ValueError("save_tool expects a function")
source = inspect.getsource(func)
USER_TOOLS_PATH.parent.mkdir(parents=True, exist_ok=True)
with open(USER_TOOLS_PATH, "a") as f:
f.write("\\n\\n")
f.write(source)
return f"Tool '{func.__name__}' saved. It will be available in future sessions."
runtime_module.save_tool = save_tool
globals()["save_tool"] = save_tool
# --- Memory System ---
def _sanitize_memory_key(key):
'''Sanitize a memory key to be a valid filename.'''
import re
sanitized = re.sub(r'[^a-zA-Z0-9_-]', '_', str(key).strip())
if not sanitized:
raise ValueError("Memory key cannot be empty")
if len(sanitized) > 100:
sanitized = sanitized[:100]
return sanitized
def save_memory(key, value, *, metadata=None):
'''Save structured data to persistent memory.
Args:
key: A string identifier for this memory (e.g., "project_context", "user_preferences")
value: Any JSON-serializable data (dict, list, str, int, etc.)
metadata: Optional dict with additional info (e.g., {"tags": ["important"]})
Returns:
Confirmation message
Example:
save_memory("project_context", {"goal": "Build API", "progress": ["Step 1 done"]})
'''
import time
sanitized_key = _sanitize_memory_key(key)
MEMORY_DIR.mkdir(parents=True, exist_ok=True)
memory_file = MEMORY_DIR / f"{sanitized_key}.json"
memory_data = {
"key": key,
"value": value,
"metadata": metadata or {},
"created_at": time.time(),
"updated_at": time.time(),
}
# If file exists, preserve created_at
if memory_file.exists():
try:
existing = json.loads(memory_file.read_text())
memory_data["created_at"] = existing.get("created_at", memory_data["created_at"])
except Exception:
pass
memory_file.write_text(json.dumps(memory_data, indent=2, default=str))
return f"Memory '{key}' saved."