toolscript-mcp 0.0.0-stage → 1.0.1

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,329 @@
1
+ // Sandbox runner for code-mode. Runs one script the model wrote.
2
+ //
3
+ // argv: runner.mjs <exchange dir>
4
+ // stdin: {"code": "...", "lib": {"<name>": "<async function expression>"}, "timeoutMs": 60000,
5
+ // "deadline": <Date.now() at the launch + timeoutMs>}
6
+ // stdout: one line per message, each "\u0001cm " + JSON:
7
+ // {"t":"call","id":1,"tool":"mcp__x__y","args":{...}}
8
+ // {"t":"recall","id":2,"ref":4}
9
+ // {"t":"save","id":3,"name":"issues.csv","data":<json>}
10
+ // {"t":"read","id":4,"path":"ids.txt"}
11
+ // {"t":"resources","id":5,"server":"docs"}
12
+ // {"t":"resource","id":6,"server":"docs","uri":"file:///a.md"}
13
+ // {"t":"done","value":"<json>","logs":[...]}
14
+ // {"t":"error","message":"...","logs":[...]} ("timedOut":true when the time limit ended it)
15
+ // The host answers each message with an <id> by writing <exchange dir>/r<id>.json:
16
+ // {"ok":true,"value":...} or {"ok":false,"error":"..."}
17
+ // sleep(ms) never reaches the host: this process answers it with its own timer.
18
+ //
19
+ // The script runs in a vm context with no require, process, fetch or timers.
20
+ // Only strings cross between host and context, so no host object (and no host
21
+ // Function constructor) is reachable from the script. The host process is
22
+ // also started with --permission (read-only access to this file and the
23
+ // exchange dir), with no environment variables and, on macOS, under
24
+ // sandbox-exec with no network.
25
+
26
+ import fs from 'node:fs'
27
+ import path from 'node:path'
28
+ import vm from 'node:vm'
29
+
30
+ const MARK = '\u0001cm '
31
+ const POLL_MS = 5
32
+ const xdir = process.argv[2]
33
+ const input = JSON.parse(fs.readFileSync(0, 'utf8'))
34
+ const timeoutMs = Number(input.timeoutMs) || 60_000
35
+ // With no deadline in the input, the limit counts from here.
36
+ const deadline = Number.isFinite(input.deadline) ? input.deadline : Date.now() + timeoutMs
37
+
38
+ let finished = false
39
+ const lineOf = msg => MARK + JSON.stringify(msg) + '\n'
40
+ // A message after finish (a late call) is dropped. The result line is the last
41
+ // line this process writes, so a later write cannot cut it.
42
+ const emit = msg => {
43
+ if (finished) return
44
+ process.stdout.write(lineOf(msg))
45
+ }
46
+
47
+ // A pipe takes the line in the background. process.exit drops a write that is
48
+ // still queued, so a line larger than the pipe buffer never reaches the host.
49
+ const finish = msg => {
50
+ if (finished) return
51
+ finished = true
52
+ process.stdout.write(lineOf(msg), () => process.exit(0))
53
+ }
54
+
55
+ // The console lines from their JSON text. A program that changes
56
+ // Array.prototype.toJSON can make that text hold some other value: then the
57
+ // lines are lost, and the result still goes.
58
+ const linesOf = text => {
59
+ try {
60
+ const lines = JSON.parse(text)
61
+ return Array.isArray(lines) ? lines.map(String) : []
62
+ } catch {
63
+ return []
64
+ }
65
+ }
66
+
67
+ // Host side of the bridge: the context calls post(kind, a, b, c) with strings.
68
+ // `deliver` is the context's answer function, set after the bootstrap runs.
69
+ const waiting = new Set()
70
+ let deliver
71
+ const post = (kind, a, b, c) => {
72
+ try {
73
+ if (kind === 'call') {
74
+ const id = Number(a)
75
+ emit({ t: 'call', id, tool: String(b), args: JSON.parse(String(c)) })
76
+ waiting.add(id)
77
+ } else if (kind === 'recall') {
78
+ const id = Number(a)
79
+ emit({ t: 'recall', id, ref: Number(b) })
80
+ waiting.add(id)
81
+ } else if (kind === 'save') {
82
+ const id = Number(a)
83
+ emit({ t: 'save', id, name: String(b), data: JSON.parse(String(c)) })
84
+ waiting.add(id)
85
+ } else if (kind === 'read') {
86
+ const id = Number(a)
87
+ emit({ t: 'read', id, path: String(b) })
88
+ waiting.add(id)
89
+ } else if (kind === 'resources') {
90
+ const id = Number(a)
91
+ emit({ t: 'resources', id, ...(b === '' ? {} : { server: String(b) }) })
92
+ waiting.add(id)
93
+ } else if (kind === 'resource') {
94
+ const id = Number(a)
95
+ emit({ t: 'resource', id, server: String(b), uri: String(c) })
96
+ waiting.add(id)
97
+ } else if (kind === 'sleep') {
98
+ // No longer than the run can last: the wall-clock timer ends it first.
99
+ const id = Number(a)
100
+ setTimeout(() => deliver(id, '{"ok":true,"value":null}'), Math.min(Number(b), timeoutMs))
101
+ } else if (kind === 'done') {
102
+ finish({ t: 'done', value: String(a), logs: linesOf(String(b)) })
103
+ } else if (kind === 'error') {
104
+ finish({ t: 'error', message: String(a), logs: linesOf(String(b)) })
105
+ }
106
+ } catch (err) {
107
+ finish({ t: 'error', message: `bridge: ${err?.message ?? err}`, logs: [] })
108
+ }
109
+ return undefined
110
+ }
111
+
112
+ // A null-prototype sandbox: with a plain object, globalThis.constructor would
113
+ // be the host's Object, and its constructor the host's Function.
114
+ const sandbox = Object.create(null)
115
+ sandbox.__post = post
116
+ const context = vm.createContext(sandbox, {
117
+ codeGeneration: { strings: false, wasm: false },
118
+ })
119
+
120
+ // Context side of the bridge, compiled inside the context so every object
121
+ // the script can reach (promises, errors, functions) is the context's own.
122
+ const BOOTSTRAP = String.raw`
123
+ (() => {
124
+ const post = globalThis.__post
125
+ delete globalThis.__post
126
+ // The program can replace JSON.stringify, but not this copy.
127
+ const stringify = JSON.stringify
128
+ const waiting = new Map()
129
+ let nextId = 0
130
+ const logs = []
131
+ // A toJSON of the program can throw here: the result still goes, with no lines.
132
+ const logsText = () => {
133
+ try { return stringify(logs) } catch { return '[]' }
134
+ }
135
+ globalThis.__logs = logsText
136
+ const fmt = v => {
137
+ if (typeof v === 'string') return v
138
+ try { return JSON.stringify(v) } catch { return String(v) }
139
+ }
140
+ const log = (...a) => { logs.push(a.map(fmt).join(' ')) }
141
+ globalThis.console = { log, info: log, warn: log, error: log, debug: log }
142
+
143
+ // A program can start a call and await it later. If the call fails first,
144
+ // its rejection has no handler yet, and Node ends the process. The no-op
145
+ // catch marks it handled; the program still gets the error when it awaits.
146
+ const handled = p => {
147
+ p.catch(() => {})
148
+ return p
149
+ }
150
+
151
+ const call = (tool, args) => handled(new Promise((resolve, reject) => {
152
+ if (typeof tool !== 'string') throw new TypeError('call(tool, args): tool must be a string')
153
+ if (args != null && (typeof args !== 'object' || Array.isArray(args)))
154
+ throw new TypeError('call(tool, args): args must be an object, such as { id: "x" }')
155
+ const id = ++nextId
156
+ waiting.set(id, { resolve, reject })
157
+ post('call', String(id), tool, JSON.stringify(args ?? {}))
158
+ }))
159
+ // tools.<server>.<tool>(args) is call("mcp__<server>__<tool>", args)
160
+ const tools = new Proxy({}, {
161
+ get: (_, server) => typeof server !== 'string' ? undefined : new Proxy({}, {
162
+ get: (_, tool) => typeof tool !== 'string' ? undefined
163
+ : args => call('mcp__' + server + '__' + tool, args),
164
+ }),
165
+ })
166
+ // recall(n): the result of call #n from this session again, with no new call
167
+ const recall = ref => handled(new Promise((resolve, reject) => {
168
+ if (!Number.isInteger(ref)) throw new TypeError('recall(n): n must be the number of a result')
169
+ const id = ++nextId
170
+ waiting.set(id, { resolve, reject })
171
+ post('recall', String(id), String(ref))
172
+ }))
173
+ // sleep(ms): waits, for programs that poll; no timers reach the context
174
+ const sleep = ms => handled(new Promise((resolve, reject) => {
175
+ if (typeof ms !== 'number' || !(ms >= 0)) throw new TypeError('sleep(ms): ms must be a number of milliseconds, 0 or more')
176
+ const id = ++nextId
177
+ waiting.set(id, { resolve, reject })
178
+ post('sleep', String(id), String(ms))
179
+ }))
180
+ // saveFile(name, data) and readFile(path): the host writes and reads the
181
+ // files; this process has no file system access of its own
182
+ const ask = (kind, a, b) => handled(new Promise((resolve, reject) => {
183
+ const id = ++nextId
184
+ waiting.set(id, { resolve, reject })
185
+ post(kind, String(id), a, b)
186
+ }))
187
+ const saveFile = (name, data) => {
188
+ if (typeof name !== 'string') throw new TypeError('saveFile(name, data): name must be a string')
189
+ const json = JSON.stringify(data)
190
+ if (json === undefined) throw new TypeError('saveFile(name, data): data must be text or JSON')
191
+ return ask('save', name, json)
192
+ }
193
+ const readFile = path => {
194
+ if (typeof path !== 'string') throw new TypeError('readFile(path): path must be a string')
195
+ return ask('read', path)
196
+ }
197
+ // resources(server?) and readResource(server, uri): the MCP resources
198
+ const resources = server => {
199
+ if (server !== undefined && typeof server !== 'string') throw new TypeError('resources(server): server must be a string')
200
+ return ask('resources', server ?? '')
201
+ }
202
+ const readResource = (server, uri) => {
203
+ if (typeof server !== 'string' || typeof uri !== 'string') throw new TypeError('readResource(server, uri): server and uri must be strings')
204
+ return ask('resource', server, uri)
205
+ }
206
+ // lib.<name>(args): the saved functions the host loads below. A name that
207
+ // is not there throws at once, with the place to look.
208
+ const saved = Object.create(null)
209
+ const lib = new Proxy(saved, {
210
+ get: (target, name) => {
211
+ if (typeof name !== 'string' || name === 'then' || name === 'toJSON' || name in target) return target[name]
212
+ throw new TypeError('lib.' + name + ' is not a saved function: search_tools lists them')
213
+ },
214
+ set: () => false,
215
+ defineProperty: () => false,
216
+ deleteProperty: () => false,
217
+ })
218
+ globalThis.__lib = saved
219
+ globalThis.call = call
220
+ globalThis.recall = recall
221
+ globalThis.sleep = sleep
222
+ globalThis.saveFile = saveFile
223
+ globalThis.readFile = readFile
224
+ globalThis.resources = resources
225
+ globalThis.readResource = readResource
226
+ globalThis.lib = lib
227
+ globalThis.tools = tools
228
+
229
+ globalThis.__deliver = (id, text) => {
230
+ const w = waiting.get(id)
231
+ if (!w) return
232
+ waiting.delete(id)
233
+ const r = JSON.parse(text)
234
+ if (r.ok) w.resolve(r.value)
235
+ else w.reject(new Error(r.error))
236
+ }
237
+
238
+ // The error and the script's own frames, not the bridge's.
239
+ const describe = e => {
240
+ if (!(e instanceof Error)) return String(e)
241
+ const frames = String(e.stack || '').split('\n').filter(l => l.includes('code.js') || l.includes('lib/'))
242
+ return [e.name + ': ' + e.message, ...frames].join('\n')
243
+ }
244
+
245
+ globalThis.__start = main => {
246
+ Promise.resolve().then(main).then(
247
+ v => {
248
+ let out
249
+ try {
250
+ out = v === undefined ? 'null' : stringify(v)
251
+ } catch (e) {
252
+ // A cycle, a BigInt or a toJSON that throws. String(v) would give "[object Object]" as a result.
253
+ const why = e instanceof Error ? e.message : 'a toJSON method threw'
254
+ return post('error', 'TypeError: the return value cannot be sent as JSON: ' + why, logsText())
255
+ }
256
+ post('done', out ?? 'null', logsText())
257
+ },
258
+ e => post('error', describe(e), logsText()),
259
+ )
260
+ }
261
+ })()
262
+ `
263
+
264
+ const runSync = (src, filename) => new vm.Script(src, { filename }).runInContext(context, { timeout: timeoutMs })
265
+
266
+ try {
267
+ runSync(BOOTSTRAP, 'code-mode-bootstrap.js')
268
+ // Keep the bootstrap's helpers away from the script.
269
+ const toContext = runSync('globalThis.__deliver', 'x.js')
270
+ // After finish, no answer reaches the program: a callback of the program
271
+ // that loops would block the drain of the result line and the exit.
272
+ deliver = (id, text) => {
273
+ if (!finished) toContext(id, text)
274
+ }
275
+ const start = runSync('globalThis.__start', 'x.js')
276
+ const logsOf = runSync('globalThis.__logs', 'x.js')
277
+ runSync('delete globalThis.__deliver; delete globalThis.__start; delete globalThis.__logs', 'x.js')
278
+
279
+ // The saved functions, each compiled in the context as its own file. One
280
+ // that does not compile throws its error when the program calls it, and its
281
+ // toString still gives its code, so the model can read the code to fix it.
282
+ for (const [name, src] of Object.entries(input.lib ?? {})) {
283
+ if (!/^[A-Za-z_$][\w$]{0,39}$/.test(name)) continue
284
+ const key = JSON.stringify(name)
285
+ try {
286
+ runSync(`globalThis.__lib[${key}] = (${src}\n)`, `lib/${name}.js`)
287
+ } catch (err) {
288
+ const message = JSON.stringify(`lib.${name} does not compile: ${err?.message ?? err}`)
289
+ const code = JSON.stringify(String(src))
290
+ runSync(
291
+ `globalThis.__lib[${key}] = Object.defineProperty(async () => { throw new SyntaxError(${message}) }, 'toString', { value: () => ${code} })`,
292
+ 'x.js',
293
+ )
294
+ }
295
+ }
296
+ runSync('delete globalThis.__lib', 'x.js')
297
+
298
+ const main = runSync(`(async () => {\n${input.code}\n})`, 'code.js')
299
+ start(main)
300
+
301
+ // Answer delivery: poll the exchange dir for the host's result files.
302
+ const timer = setInterval(() => {
303
+ for (const id of waiting) {
304
+ const file = path.join(xdir, `r${id}.json`)
305
+ let text
306
+ try {
307
+ text = fs.readFileSync(file, 'utf8')
308
+ } catch {
309
+ continue
310
+ }
311
+ try {
312
+ JSON.parse(text)
313
+ } catch {
314
+ continue
315
+ } // still being written
316
+ waiting.delete(id)
317
+ deliver(id, text)
318
+ }
319
+ if (finished) clearInterval(timer)
320
+ }, POLL_MS)
321
+
322
+ setTimeout(
323
+ () =>
324
+ finish({ t: 'error', message: `timeout after ${timeoutMs} ms`, logs: linesOf(String(logsOf())), timedOut: true }),
325
+ Math.max(0, deadline - Date.now()),
326
+ )
327
+ } catch (err) {
328
+ finish({ t: 'error', message: String(err?.stack ?? err), logs: [] })
329
+ }