code-executor-mcp 1.0.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.
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: code-executor-mcp
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: MCP server for code executor. Features execute code, run command, run tests. From MEOK AI Labs.
|
|
5
|
+
Project-URL: Homepage, https://meok.ai
|
|
6
|
+
Project-URL: Repository, https://github.com/CSOAI-ORG/code-executor-mcp
|
|
7
|
+
Author-email: MEOK AI Labs <nicholas@meok.ai>
|
|
8
|
+
License: MIT License
|
|
9
|
+
|
|
10
|
+
Copyright (c) 2026 MEOK AI Labs (meok.ai)
|
|
11
|
+
|
|
12
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
13
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
14
|
+
in the Software without restriction, including without limitation the rights
|
|
15
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
16
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
17
|
+
furnished to do so, subject to the following conditions:
|
|
18
|
+
|
|
19
|
+
The above copyright notice and this permission notice shall be included in all
|
|
20
|
+
copies or substantial portions of the Software.
|
|
21
|
+
|
|
22
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
23
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
24
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
25
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
26
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
27
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
28
|
+
SOFTWARE.
|
|
29
|
+
License-File: LICENSE
|
|
30
|
+
Keywords: ai,mcp,meok
|
|
31
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
32
|
+
Classifier: Operating System :: OS Independent
|
|
33
|
+
Classifier: Programming Language :: Python :: 3
|
|
34
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
35
|
+
Requires-Python: >=3.10
|
|
36
|
+
Requires-Dist: mcp>=1.0.0
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
server.py,sha256=c3pM_PtC-XJrp6KRzIfqHShFV376RTLQLodQO963fEY,17367
|
|
2
|
+
code_executor_mcp-1.0.0.dist-info/METADATA,sha256=Q5qeGzXP2mMp6zj_q8XZgrFIat1e6tW7vBkPu9FkgpU,1866
|
|
3
|
+
code_executor_mcp-1.0.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
|
4
|
+
code_executor_mcp-1.0.0.dist-info/entry_points.txt,sha256=pUFYUE2JvmA-z-5HGQzLUkTdw1Uc60MQh0gpeNg-XEA,50
|
|
5
|
+
code_executor_mcp-1.0.0.dist-info/licenses/LICENSE,sha256=h6iKken4HpG26z8rbGttTUuGglAS8HwFd92gr7fDQcw,1079
|
|
6
|
+
code_executor_mcp-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 MEOK AI Labs (meok.ai)
|
|
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.
|
server.py
ADDED
|
@@ -0,0 +1,495 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
Code Executor MCP Server
|
|
4
|
+
=========================
|
|
5
|
+
Sandboxed code execution and shell command runner for AI agents. Execute Python,
|
|
6
|
+
JavaScript, and shell commands with safety guards, output capture, timeout
|
|
7
|
+
protection, and file I/O restrictions.
|
|
8
|
+
|
|
9
|
+
Install: pip install mcp
|
|
10
|
+
Run: python server.py
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
import re
|
|
16
|
+
import shlex
|
|
17
|
+
import subprocess
|
|
18
|
+
import tempfile
|
|
19
|
+
import time
|
|
20
|
+
from datetime import datetime, timedelta
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
from typing import Optional
|
|
23
|
+
from collections import defaultdict
|
|
24
|
+
from mcp.server.fastmcp import FastMCP
|
|
25
|
+
import sys, os
|
|
26
|
+
sys.path.insert(0, os.path.expanduser('~/clawd/meok-labs-engine/shared'))
|
|
27
|
+
from auth_middleware import check_access
|
|
28
|
+
|
|
29
|
+
# ---------------------------------------------------------------------------
|
|
30
|
+
# Rate limiting
|
|
31
|
+
# ---------------------------------------------------------------------------
|
|
32
|
+
FREE_DAILY_LIMIT = 50
|
|
33
|
+
_usage: dict[str, list[datetime]] = defaultdict(list)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _check_rate_limit(caller: str = "anonymous") -> Optional[str]:
|
|
37
|
+
now = datetime.now()
|
|
38
|
+
cutoff = now - timedelta(days=1)
|
|
39
|
+
_usage[caller] = [t for t in _usage[caller] if t > cutoff]
|
|
40
|
+
if len(_usage[caller]) >= FREE_DAILY_LIMIT:
|
|
41
|
+
return f"Free tier limit reached ({FREE_DAILY_LIMIT}/day). Upgrade to Pro: https://mcpize.com/code-executor-mcp/pro"
|
|
42
|
+
_usage[caller].append(now)
|
|
43
|
+
return None
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
# ---------------------------------------------------------------------------
|
|
47
|
+
# Safety Configuration
|
|
48
|
+
# ---------------------------------------------------------------------------
|
|
49
|
+
# Blocked shell command patterns
|
|
50
|
+
BLOCKED_COMMANDS = [
|
|
51
|
+
r"rm\s+-rf\s+/",
|
|
52
|
+
r"mkfs\.",
|
|
53
|
+
r"dd\s+if=",
|
|
54
|
+
r">\s*/dev/sd",
|
|
55
|
+
r":\(\)\s*\{\s*:\s*\|\s*:", # Fork bomb
|
|
56
|
+
r"chmod\s+-R\s+777\s+/",
|
|
57
|
+
r"curl\s+.*\|\s*(?:ba)?sh", # Pipe to shell
|
|
58
|
+
r"wget\s+.*\|\s*(?:ba)?sh",
|
|
59
|
+
r"nc\s+-e", # Netcat reverse shell
|
|
60
|
+
r"python.*-c.*import\s+os.*system",
|
|
61
|
+
r"sudo\s+rm",
|
|
62
|
+
r">\s*/etc/",
|
|
63
|
+
r"mv\s+/",
|
|
64
|
+
r"cat\s+/etc/(?:passwd|shadow|sudoers)", # Read sensitive system files
|
|
65
|
+
r"curl\s+.*>\s*/tmp/.*&&", # Download-and-exec pattern
|
|
66
|
+
r"\benv\b.*(?:pass|secret|key|token)", # Environment variable leaks
|
|
67
|
+
r"\bhistory\b", # Shell history leak
|
|
68
|
+
r"base64\s+-d\s*\|", # Base64 decode pipe (obfuscation)
|
|
69
|
+
]
|
|
70
|
+
|
|
71
|
+
# Blocked Python code patterns
|
|
72
|
+
BLOCKED_PYTHON = [
|
|
73
|
+
r"os\s*\.\s*system\s*\(",
|
|
74
|
+
r"subprocess\.(?:call|run|Popen)\s*\(",
|
|
75
|
+
r"shutil\.rmtree\s*\(\s*['\"]\/",
|
|
76
|
+
r"__import__\s*\(", # Block ALL __import__ calls
|
|
77
|
+
r"open\s*\(\s*['\"]\/etc",
|
|
78
|
+
r"eval\s*\(", # Block all eval() calls
|
|
79
|
+
r"exec\s*\(", # Block all exec() calls
|
|
80
|
+
r"importlib\.import_module\s*\(",
|
|
81
|
+
r"ctypes\.",
|
|
82
|
+
r"socket\.\w+\s*\(", # No raw sockets
|
|
83
|
+
r"__builtins__", # No builtins access
|
|
84
|
+
r"globals\s*\(\s*\)", # No globals() access
|
|
85
|
+
r"locals\s*\(\s*\)", # No locals() access
|
|
86
|
+
r"getattr\s*\(", # No dynamic attribute access
|
|
87
|
+
r"compile\s*\(", # No compile() calls
|
|
88
|
+
r"from\s+os\s+import", # No 'from os import'
|
|
89
|
+
r"from\s+subprocess\s+import", # No 'from subprocess import'
|
|
90
|
+
r"from\s+shutil\s+import", # No 'from shutil import'
|
|
91
|
+
r"import\s+os\b", # No 'import os'
|
|
92
|
+
r"import\s+subprocess\b", # No 'import subprocess'
|
|
93
|
+
r"import\s+shutil\b", # No 'import shutil'
|
|
94
|
+
]
|
|
95
|
+
|
|
96
|
+
# Blocked JavaScript patterns
|
|
97
|
+
BLOCKED_JS = [
|
|
98
|
+
r"child_process",
|
|
99
|
+
r"require\s*\(\s*['\"]fs['\"]",
|
|
100
|
+
r"process\.exit",
|
|
101
|
+
r"eval\s*\(",
|
|
102
|
+
r"Function\s*\(",
|
|
103
|
+
]
|
|
104
|
+
|
|
105
|
+
# Allowed directories for file operations
|
|
106
|
+
ALLOWED_DIRS = [
|
|
107
|
+
str(Path.home() / "Desktop"),
|
|
108
|
+
str(Path.home() / "Documents"),
|
|
109
|
+
str(Path.home() / "Downloads"),
|
|
110
|
+
"/tmp",
|
|
111
|
+
]
|
|
112
|
+
|
|
113
|
+
# Sandbox working directory
|
|
114
|
+
SANDBOX_DIR = Path(tempfile.gettempdir()) / "mcp-code-sandbox"
|
|
115
|
+
SANDBOX_DIR.mkdir(exist_ok=True)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _check_command_safety(cmd: str) -> Optional[str]:
|
|
119
|
+
"""Returns error message if command is blocked, else None."""
|
|
120
|
+
for pattern in BLOCKED_COMMANDS:
|
|
121
|
+
if re.search(pattern, cmd, re.IGNORECASE):
|
|
122
|
+
return f"Command blocked by safety filter (matches: {pattern[:30]})"
|
|
123
|
+
return None
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _check_python_safety(code: str) -> Optional[str]:
|
|
127
|
+
"""Returns error message if Python code is blocked, else None."""
|
|
128
|
+
for pattern in BLOCKED_PYTHON:
|
|
129
|
+
if re.search(pattern, code, re.IGNORECASE):
|
|
130
|
+
return f"Code blocked by safety filter (matches: {pattern[:30]})"
|
|
131
|
+
return None
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _check_js_safety(code: str) -> Optional[str]:
|
|
135
|
+
"""Returns error message if JavaScript code is blocked, else None."""
|
|
136
|
+
for pattern in BLOCKED_JS:
|
|
137
|
+
if re.search(pattern, code, re.IGNORECASE):
|
|
138
|
+
return f"Code blocked by safety filter (matches: {pattern[:30]})"
|
|
139
|
+
return None
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _check_path_allowed(path: str) -> bool:
|
|
143
|
+
"""Check if a file path is within allowed directories."""
|
|
144
|
+
real = os.path.realpath(path)
|
|
145
|
+
sandbox = str(SANDBOX_DIR)
|
|
146
|
+
return any(real.startswith(d) for d in ALLOWED_DIRS + [sandbox])
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
# ---------------------------------------------------------------------------
|
|
150
|
+
# Execution Engines
|
|
151
|
+
# ---------------------------------------------------------------------------
|
|
152
|
+
def _run_python(code: str, timeout: int = 30) -> dict:
|
|
153
|
+
"""Execute Python code in a subprocess with safety checks."""
|
|
154
|
+
safety = _check_python_safety(code)
|
|
155
|
+
if safety:
|
|
156
|
+
return {"error": safety}
|
|
157
|
+
|
|
158
|
+
# Write to temp file for better error reporting
|
|
159
|
+
script_path = SANDBOX_DIR / f"exec_{int(time.time())}.py"
|
|
160
|
+
script_path.write_text(code)
|
|
161
|
+
|
|
162
|
+
try:
|
|
163
|
+
start = time.time()
|
|
164
|
+
result = subprocess.run(
|
|
165
|
+
["python3", str(script_path)],
|
|
166
|
+
capture_output=True,
|
|
167
|
+
text=True,
|
|
168
|
+
timeout=timeout,
|
|
169
|
+
cwd=str(SANDBOX_DIR),
|
|
170
|
+
env={**os.environ, "PYTHONDONTWRITEBYTECODE": "1"})
|
|
171
|
+
elapsed = round(time.time() - start, 3)
|
|
172
|
+
|
|
173
|
+
return {
|
|
174
|
+
"output": result.stdout[:10000],
|
|
175
|
+
"error": result.stderr[:3000] if result.stderr else None,
|
|
176
|
+
"exit_code": result.returncode,
|
|
177
|
+
"elapsed_seconds": elapsed,
|
|
178
|
+
"language": "python",
|
|
179
|
+
}
|
|
180
|
+
except subprocess.TimeoutExpired:
|
|
181
|
+
return {"error": f"Execution timed out after {timeout}s", "language": "python"}
|
|
182
|
+
except Exception as e:
|
|
183
|
+
return {"error": str(e), "language": "python"}
|
|
184
|
+
finally:
|
|
185
|
+
script_path.unlink(missing_ok=True)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _run_javascript(code: str, timeout: int = 30) -> dict:
|
|
189
|
+
"""Execute JavaScript code using Node.js."""
|
|
190
|
+
safety = _check_js_safety(code)
|
|
191
|
+
if safety:
|
|
192
|
+
return {"error": safety}
|
|
193
|
+
|
|
194
|
+
script_path = SANDBOX_DIR / f"exec_{int(time.time())}.js"
|
|
195
|
+
# Wrap in strict mode
|
|
196
|
+
wrapped = f'"use strict";\n{code}'
|
|
197
|
+
script_path.write_text(wrapped)
|
|
198
|
+
|
|
199
|
+
try:
|
|
200
|
+
start = time.time()
|
|
201
|
+
result = subprocess.run(
|
|
202
|
+
["node", str(script_path)],
|
|
203
|
+
capture_output=True,
|
|
204
|
+
text=True,
|
|
205
|
+
timeout=timeout,
|
|
206
|
+
cwd=str(SANDBOX_DIR))
|
|
207
|
+
elapsed = round(time.time() - start, 3)
|
|
208
|
+
|
|
209
|
+
return {
|
|
210
|
+
"output": result.stdout[:10000],
|
|
211
|
+
"error": result.stderr[:3000] if result.stderr else None,
|
|
212
|
+
"exit_code": result.returncode,
|
|
213
|
+
"elapsed_seconds": elapsed,
|
|
214
|
+
"language": "javascript",
|
|
215
|
+
}
|
|
216
|
+
except FileNotFoundError:
|
|
217
|
+
return {"error": "Node.js not installed. Install: brew install node", "language": "javascript"}
|
|
218
|
+
except subprocess.TimeoutExpired:
|
|
219
|
+
return {"error": f"Execution timed out after {timeout}s", "language": "javascript"}
|
|
220
|
+
except Exception as e:
|
|
221
|
+
return {"error": str(e), "language": "javascript"}
|
|
222
|
+
finally:
|
|
223
|
+
script_path.unlink(missing_ok=True)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _run_shell(command: str, timeout: int = 30) -> dict:
|
|
227
|
+
"""Execute a shell command with safety checks."""
|
|
228
|
+
safety = _check_command_safety(command)
|
|
229
|
+
if safety:
|
|
230
|
+
return {"error": safety}
|
|
231
|
+
|
|
232
|
+
cmd_parts = shlex.split(command)
|
|
233
|
+
if not cmd_parts:
|
|
234
|
+
return {"error": "No command provided"}
|
|
235
|
+
try:
|
|
236
|
+
start = time.time()
|
|
237
|
+
result = subprocess.run(
|
|
238
|
+
cmd_parts,
|
|
239
|
+
shell=False,
|
|
240
|
+
capture_output=True,
|
|
241
|
+
text=True,
|
|
242
|
+
timeout=min(timeout, 60), # Hard cap at 60s
|
|
243
|
+
cwd=str(SANDBOX_DIR))
|
|
244
|
+
elapsed = round(time.time() - start, 3)
|
|
245
|
+
|
|
246
|
+
return {
|
|
247
|
+
"output": result.stdout[:10000],
|
|
248
|
+
"error": result.stderr[:3000] if result.stderr else None,
|
|
249
|
+
"exit_code": result.returncode,
|
|
250
|
+
"elapsed_seconds": elapsed,
|
|
251
|
+
}
|
|
252
|
+
except subprocess.TimeoutExpired:
|
|
253
|
+
return {"error": f"Command timed out after {timeout}s"}
|
|
254
|
+
except Exception as e:
|
|
255
|
+
return {"error": str(e)}
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
# ---------------------------------------------------------------------------
|
|
259
|
+
# MCP Server
|
|
260
|
+
# ---------------------------------------------------------------------------
|
|
261
|
+
mcp = FastMCP(
|
|
262
|
+
"Code Executor MCP",
|
|
263
|
+
instructions="Sandboxed code execution: Python, JavaScript, and shell commands with safety guards, output capture, and timeout protection.")
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
@mcp.tool()
|
|
267
|
+
def execute_code(code: str, language: str = "python", timeout: int = 30, api_key: str = "") -> dict:
|
|
268
|
+
"""Execute code in a sandboxed environment with safety checks.
|
|
269
|
+
Supported languages: python, javascript.
|
|
270
|
+
Timeout: max 60 seconds (30 default).
|
|
271
|
+
Dangerous patterns (os.system, subprocess, eval(input), etc.) are blocked.
|
|
272
|
+
Output is captured and returned (stdout + stderr, truncated at 10KB)."""
|
|
273
|
+
allowed, msg, tier = check_access(api_key)
|
|
274
|
+
if not allowed:
|
|
275
|
+
return {"error": msg, "upgrade_url": "https://meok.ai/pricing"}
|
|
276
|
+
|
|
277
|
+
err = _check_rate_limit()
|
|
278
|
+
if err:
|
|
279
|
+
return {"error": err}
|
|
280
|
+
|
|
281
|
+
timeout = max(1, min(timeout, 60))
|
|
282
|
+
|
|
283
|
+
if language == "python":
|
|
284
|
+
return _run_python(code, timeout)
|
|
285
|
+
elif language in ("javascript", "js", "node"):
|
|
286
|
+
return _run_javascript(code, timeout)
|
|
287
|
+
else:
|
|
288
|
+
return {"error": f"Unsupported language: {language}. Supported: python, javascript"}
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
@mcp.tool()
|
|
292
|
+
def run_command(command: str, timeout: int = 30, api_key: str = "") -> dict:
|
|
293
|
+
"""Execute a shell command and return stdout/stderr/exit_code.
|
|
294
|
+
Timeout: max 60 seconds.
|
|
295
|
+
Destructive commands (rm -rf /, dd, fork bombs, pipe-to-shell) are blocked.
|
|
296
|
+
Commands run in a temporary sandbox directory."""
|
|
297
|
+
allowed, msg, tier = check_access(api_key)
|
|
298
|
+
if not allowed:
|
|
299
|
+
return {"error": msg, "upgrade_url": "https://meok.ai/pricing"}
|
|
300
|
+
|
|
301
|
+
err = _check_rate_limit()
|
|
302
|
+
if err:
|
|
303
|
+
return {"error": err}
|
|
304
|
+
|
|
305
|
+
if not command.strip():
|
|
306
|
+
return {"error": "No command provided"}
|
|
307
|
+
|
|
308
|
+
return _run_shell(command, min(timeout, 60))
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
@mcp.tool()
|
|
312
|
+
def run_tests(test_command: str = "python -m pytest", working_dir: str = "",
|
|
313
|
+
timeout: int = 60, api_key: str = "") -> dict:
|
|
314
|
+
"""Run a test suite and return results. Default: pytest.
|
|
315
|
+
Specify working_dir to run tests in a specific project directory.
|
|
316
|
+
Returns stdout, stderr, exit code, and pass/fail summary."""
|
|
317
|
+
allowed, msg, tier = check_access(api_key)
|
|
318
|
+
if not allowed:
|
|
319
|
+
return {"error": msg, "upgrade_url": "https://meok.ai/pricing"}
|
|
320
|
+
|
|
321
|
+
err = _check_rate_limit()
|
|
322
|
+
if err:
|
|
323
|
+
return {"error": err}
|
|
324
|
+
|
|
325
|
+
# Safety check on the test command (same as shell commands)
|
|
326
|
+
safety = _check_command_safety(test_command)
|
|
327
|
+
if safety:
|
|
328
|
+
return {"error": safety}
|
|
329
|
+
|
|
330
|
+
cwd = working_dir if working_dir and os.path.isdir(working_dir) else str(SANDBOX_DIR)
|
|
331
|
+
|
|
332
|
+
cmd_parts = shlex.split(test_command)
|
|
333
|
+
if not cmd_parts:
|
|
334
|
+
return {"error": "No test command provided"}
|
|
335
|
+
try:
|
|
336
|
+
start = time.time()
|
|
337
|
+
result = subprocess.run(
|
|
338
|
+
cmd_parts,
|
|
339
|
+
shell=False,
|
|
340
|
+
capture_output=True,
|
|
341
|
+
text=True,
|
|
342
|
+
timeout=min(timeout, 120),
|
|
343
|
+
cwd=cwd)
|
|
344
|
+
elapsed = round(time.time() - start, 3)
|
|
345
|
+
|
|
346
|
+
# Parse pytest output for summary
|
|
347
|
+
output = result.stdout
|
|
348
|
+
summary = ""
|
|
349
|
+
for line in output.split("\n"):
|
|
350
|
+
if "passed" in line or "failed" in line or "error" in line:
|
|
351
|
+
summary = line.strip()
|
|
352
|
+
break
|
|
353
|
+
|
|
354
|
+
return {
|
|
355
|
+
"output": output[:10000],
|
|
356
|
+
"error": result.stderr[:3000] if result.stderr else None,
|
|
357
|
+
"exit_code": result.returncode,
|
|
358
|
+
"elapsed_seconds": elapsed,
|
|
359
|
+
"summary": summary,
|
|
360
|
+
"passed": result.returncode == 0,
|
|
361
|
+
"working_dir": cwd,
|
|
362
|
+
}
|
|
363
|
+
except subprocess.TimeoutExpired:
|
|
364
|
+
return {"error": f"Tests timed out after {timeout}s"}
|
|
365
|
+
except Exception as e:
|
|
366
|
+
return {"error": str(e)}
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
@mcp.tool()
|
|
370
|
+
def read_file(path: str, limit: int = 200, api_key: str = "") -> dict:
|
|
371
|
+
"""Read contents of a file (restricted to allowed directories: Desktop,
|
|
372
|
+
Documents, Downloads, /tmp, and the sandbox). Returns file content with
|
|
373
|
+
line limit."""
|
|
374
|
+
allowed, msg, tier = check_access(api_key)
|
|
375
|
+
if not allowed:
|
|
376
|
+
return {"error": msg, "upgrade_url": "https://meok.ai/pricing"}
|
|
377
|
+
|
|
378
|
+
err = _check_rate_limit()
|
|
379
|
+
if err:
|
|
380
|
+
return {"error": err}
|
|
381
|
+
|
|
382
|
+
if not path:
|
|
383
|
+
return {"error": "No path provided"}
|
|
384
|
+
|
|
385
|
+
if not _check_path_allowed(path):
|
|
386
|
+
return {"error": "Access denied: path outside allowed directories"}
|
|
387
|
+
|
|
388
|
+
try:
|
|
389
|
+
with open(path, "r") as f:
|
|
390
|
+
lines = []
|
|
391
|
+
for i, line in enumerate(f):
|
|
392
|
+
if i >= limit:
|
|
393
|
+
break
|
|
394
|
+
lines.append(line)
|
|
395
|
+
content = "".join(lines)
|
|
396
|
+
return {
|
|
397
|
+
"content": content,
|
|
398
|
+
"lines": len(lines),
|
|
399
|
+
"truncated": len(lines) >= limit,
|
|
400
|
+
"path": path,
|
|
401
|
+
}
|
|
402
|
+
except Exception as e:
|
|
403
|
+
return {"error": str(e)}
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
@mcp.tool()
|
|
407
|
+
def list_sandbox_files(api_key: str = "") -> dict:
|
|
408
|
+
"""List files in the sandbox working directory. All code execution
|
|
409
|
+
artifacts are stored here temporarily."""
|
|
410
|
+
allowed, msg, tier = check_access(api_key)
|
|
411
|
+
if not allowed:
|
|
412
|
+
return {"error": msg, "upgrade_url": "https://meok.ai/pricing"}
|
|
413
|
+
|
|
414
|
+
files = []
|
|
415
|
+
for f in SANDBOX_DIR.iterdir():
|
|
416
|
+
if f.is_file():
|
|
417
|
+
stat = f.stat()
|
|
418
|
+
files.append({
|
|
419
|
+
"name": f.name,
|
|
420
|
+
"size": stat.st_size,
|
|
421
|
+
"modified": datetime.fromtimestamp(stat.st_mtime).isoformat(),
|
|
422
|
+
})
|
|
423
|
+
return {
|
|
424
|
+
"sandbox_dir": str(SANDBOX_DIR),
|
|
425
|
+
"files": sorted(files, key=lambda x: x["modified"], reverse=True),
|
|
426
|
+
"count": len(files),
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
@mcp.tool()
|
|
431
|
+
def get_safety_rules(api_key: str = "") -> dict:
|
|
432
|
+
"""Get the current safety rules and blocked patterns for code execution.
|
|
433
|
+
Useful for understanding what is and isn't allowed."""
|
|
434
|
+
allowed, msg, tier = check_access(api_key)
|
|
435
|
+
if not allowed:
|
|
436
|
+
return {"error": msg, "upgrade_url": "https://meok.ai/pricing"}
|
|
437
|
+
|
|
438
|
+
return {
|
|
439
|
+
"blocked_shell_patterns": BLOCKED_COMMANDS,
|
|
440
|
+
"blocked_python_patterns": BLOCKED_PYTHON,
|
|
441
|
+
"blocked_javascript_patterns": BLOCKED_JS,
|
|
442
|
+
"allowed_file_directories": ALLOWED_DIRS,
|
|
443
|
+
"sandbox_directory": str(SANDBOX_DIR),
|
|
444
|
+
"max_timeout_seconds": 60,
|
|
445
|
+
"max_output_bytes": 10000,
|
|
446
|
+
"supported_languages": ["python", "javascript"],
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
@mcp.tool(name="execute_code_docker")
|
|
452
|
+
async def execute_code_docker(code: str, language: str = "python", timeout_sec: int = 30, api_key: str = "") -> str:
|
|
453
|
+
"""Execute code inside a temporary Docker container for isolation."""
|
|
454
|
+
import subprocess, tempfile, os
|
|
455
|
+
allowed, msg, tier = check_access(api_key)
|
|
456
|
+
if not allowed:
|
|
457
|
+
return {"error": msg, "upgrade_url": "https://meok.ai/pricing"}
|
|
458
|
+
|
|
459
|
+
image_map = {"python": "python:3.11-alpine", "node": "node:20-alpine", "bash": "alpine:latest"}
|
|
460
|
+
image = image_map.get(language.lower(), "alpine:latest")
|
|
461
|
+
|
|
462
|
+
with tempfile.NamedTemporaryFile(mode='w', suffix=f'.{language}', delete=False) as f:
|
|
463
|
+
f.write(code)
|
|
464
|
+
tmp_path = f.name
|
|
465
|
+
|
|
466
|
+
try:
|
|
467
|
+
cmd = [
|
|
468
|
+
"docker", "run", "--rm", "-v", f"{tmp_path}:/code/file",
|
|
469
|
+
"--network", "none", "--memory", "128m", "--cpus", "0.5",
|
|
470
|
+
image
|
|
471
|
+
]
|
|
472
|
+
if language.lower() == "python":
|
|
473
|
+
cmd += ["python", "/code/file"]
|
|
474
|
+
elif language.lower() == "node":
|
|
475
|
+
cmd += ["node", "/code/file"]
|
|
476
|
+
else:
|
|
477
|
+
cmd += ["sh", "/code/file"]
|
|
478
|
+
|
|
479
|
+
result = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout_sec)
|
|
480
|
+
return {
|
|
481
|
+
"stdout": result.stdout,
|
|
482
|
+
"stderr": result.stderr,
|
|
483
|
+
"returncode": result.returncode,
|
|
484
|
+
"isolated": True,
|
|
485
|
+
"image": image
|
|
486
|
+
}
|
|
487
|
+
except FileNotFoundError:
|
|
488
|
+
return {"error": "Docker not installed or not in PATH", "isolated": False}
|
|
489
|
+
except subprocess.TimeoutExpired:
|
|
490
|
+
return {"error": f"Execution timed out after {timeout_sec}s", "isolated": True}
|
|
491
|
+
finally:
|
|
492
|
+
os.unlink(tmp_path)
|
|
493
|
+
|
|
494
|
+
if __name__ == "__main__":
|
|
495
|
+
mcp.run()
|