-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.mjs
More file actions
249 lines (226 loc) · 8.06 KB
/
Copy pathserver.mjs
File metadata and controls
249 lines (226 loc) · 8.06 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
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
import { execSync, execFileSync, spawn } from "node:child_process";
import { readFileSync, writeFileSync, existsSync, mkdirSync, readdirSync, statSync } from "node:fs";
import { join, resolve } from "node:path";
import { randomUUID } from "node:crypto";
// AgentFS-style audit log (SQLite-compatible JSON lines)
const AUDIT_DIR = "/agent/audit";
const WORKSPACE = "/agent/workspace";
if (!existsSync(AUDIT_DIR)) mkdirSync(AUDIT_DIR, { recursive: true });
if (!existsSync(WORKSPACE)) mkdirSync(WORKSPACE, { recursive: true });
const auditLog = join(AUDIT_DIR, "toolcalls.jsonl");
function recordToolCall(tool, input, output, status, durationMs) {
const entry = {
id: randomUUID(),
tool,
input,
output: output.slice(0, 4096), // cap output size
status,
duration_ms: durationMs,
timestamp: new Date().toISOString(),
};
writeFileSync(auditLog, JSON.stringify(entry) + "\n", { flag: "a" });
return entry;
}
// Command blocklist — prevent destructive or escape commands
const BLOCKED_PATTERNS = [
/rm\s+(-rf?|--recursive)\s+\//i, // rm -rf /
/mkfs/i,
/dd\s+if=/i,
/:(){ :|:& };:/, // fork bomb
/curl.*\|\s*(ba)?sh/i, // pipe to shell
/wget.*\|\s*(ba)?sh/i,
/chmod\s+[0-7]*s/i, // setuid
/chown\s+root/i,
/nsenter/i,
/mount\s/i,
/umount/i,
/shutdown/i,
/reboot/i,
/halt\b/i,
/docker\b/i, // no docker-in-docker
/kubectl/i,
];
function isBlocked(command) {
return BLOCKED_PATTERNS.some((pattern) => pattern.test(command));
}
// Create MCP server
const server = new McpServer({
name: "sandbox-bash",
version: "0.1.0",
});
// Tool: run_bash — execute a command in the sandboxed container
server.tool(
"run_bash",
"Execute a bash command in an isolated container. Working directory is /agent/workspace. No network access, no host filesystem access. Commands are audited.",
{
command: z.string().describe("The bash command to execute"),
timeout_ms: z
.number()
.optional()
.default(30000)
.describe("Timeout in milliseconds (default 30s, max 120s)"),
working_dir: z
.string()
.optional()
.default("/agent/workspace")
.describe("Working directory (must be under /agent/)"),
},
async ({ command, timeout_ms, working_dir }) => {
const start = Date.now();
// Security checks
if (isBlocked(command)) {
const entry = recordToolCall("run_bash", { command }, "BLOCKED: command matches security blocklist", "blocked", Date.now() - start);
return {
content: [
{
type: "text",
text: `BLOCKED: This command is not allowed in the sandbox.\nReason: matches security blocklist\nAudit ID: ${entry.id}`,
},
],
};
}
// Clamp timeout
const timeout = Math.min(timeout_ms || 30000, 120000);
// Ensure working_dir is under /agent/ (path traversal safe)
const resolvedDir = resolve(working_dir);
const safeDir = resolvedDir.startsWith("/agent/") ? resolvedDir : "/agent/workspace";
try {
const output = execSync(command, {
cwd: safeDir,
timeout,
maxBuffer: 1024 * 1024, // 1MB
encoding: "utf-8",
shell: "/bin/bash",
env: {
...process.env,
HOME: "/agent",
PATH: "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
},
});
const duration = Date.now() - start;
const entry = recordToolCall("run_bash", { command, working_dir: safeDir }, output, "success", duration);
return {
content: [
{
type: "text",
text: `$ ${command}\n${output}\n[exit: 0 | ${duration}ms | audit: ${entry.id}]`,
},
],
};
} catch (err) {
const duration = Date.now() - start;
const stderr = err.stderr || err.message || "unknown error";
const stdout = err.stdout || "";
const code = err.status ?? 1;
const entry = recordToolCall(
"run_bash",
{ command, working_dir: safeDir },
`exit:${code} stdout:${stdout} stderr:${stderr}`,
"error",
duration
);
return {
content: [
{
type: "text",
text: `$ ${command}\n${stdout}${stderr}\n[exit: ${code} | ${duration}ms | audit: ${entry.id}]`,
},
],
};
}
}
);
// Tool: read_file — read a file from the sandbox
server.tool(
"read_file",
"Read a file from the sandbox filesystem (under /agent/)",
{
path: z.string().describe("File path (must be under /agent/)"),
},
async ({ path: filePath }) => {
const start = Date.now();
const resolved = resolve(filePath);
const safePath = resolved.startsWith("/agent/") ? resolved : join("/agent/workspace", filePath);
try {
const content = readFileSync(safePath, "utf-8");
recordToolCall("read_file", { path: safePath }, content, "success", Date.now() - start);
return { content: [{ type: "text", text: content }] };
} catch (err) {
recordToolCall("read_file", { path: safePath }, err.message, "error", Date.now() - start);
return { content: [{ type: "text", text: `Error: ${err.message}` }] };
}
}
);
// Tool: write_file — write a file to the sandbox
server.tool(
"write_file",
"Write content to a file in the sandbox (under /agent/)",
{
path: z.string().describe("File path (must be under /agent/)"),
content: z.string().describe("File content to write"),
},
async ({ path: filePath, content }) => {
const start = Date.now();
const resolved = resolve(filePath);
const safePath = resolved.startsWith("/agent/") ? resolved : join("/agent/workspace", filePath);
try {
const dir = join(safePath, "..");
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
writeFileSync(safePath, content);
recordToolCall("write_file", { path: safePath, bytes: content.length }, "ok", "success", Date.now() - start);
return { content: [{ type: "text", text: `Written ${content.length} bytes to ${safePath}` }] };
} catch (err) {
recordToolCall("write_file", { path: safePath }, err.message, "error", Date.now() - start);
return { content: [{ type: "text", text: `Error: ${err.message}` }] };
}
}
);
// Tool: list_files — list files in a directory
server.tool(
"list_files",
"List files and directories under the given path in the sandbox",
{
path: z.string().optional().default("/agent/workspace").describe("Directory path"),
},
async ({ path: dirPath }) => {
const start = Date.now();
const resolved = resolve(dirPath);
const safePath = resolved.startsWith("/agent/") ? resolved : "/agent/workspace";
try {
const output = execFileSync("ls", ["-la", safePath], { encoding: "utf-8", timeout: 5000 });
recordToolCall("list_files", { path: safePath }, output, "success", Date.now() - start);
return { content: [{ type: "text", text: output }] };
} catch (err) {
return { content: [{ type: "text", text: `Error: ${err.message}` }] };
}
}
);
// Tool: audit_log — view the tool call audit trail
server.tool(
"audit_log",
"View the audit trail of all tool calls in this session",
{
last_n: z.number().optional().default(20).describe("Number of recent entries to show"),
},
async ({ last_n }) => {
try {
if (!existsSync(auditLog)) {
return { content: [{ type: "text", text: "No audit entries yet." }] };
}
const lines = readFileSync(auditLog, "utf-8").trim().split("\n");
const recent = lines.slice(-last_n).map((l) => {
const e = JSON.parse(l);
return `[${e.timestamp}] ${e.tool} → ${e.status} (${e.duration_ms}ms)`;
});
return { content: [{ type: "text", text: recent.join("\n") }] };
} catch (err) {
return { content: [{ type: "text", text: `Error: ${err.message}` }] };
}
}
);
// Start server on stdio
const transport = new StdioServerTransport();
await server.connect(transport);