This repository was archived by the owner on Jan 30, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathrunCode.ts
More file actions
273 lines (244 loc) · 8.18 KB
/
runCode.ts
File metadata and controls
273 lines (244 loc) · 8.18 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
// deno-lint-ignore-file no-explicit-any
import { loadPyodide, type PyodideInterface } from 'pyodide'
import { preparePythonCode, toolInjectionCode } from './prepareEnvCode.ts'
import type { LoggingLevel } from '@modelcontextprotocol/sdk/types.js'
export interface CodeFile {
name: string
content: string
}
interface ElicitationResponse {
action: 'accept' | 'decline' | 'cancel'
content?: Record<string, unknown>
}
export interface ToolInjectionOptions {
elicitationCallback?: (message: string) => Promise<ElicitationResponse>
availableTools?: string[]
toolSchemas?: Record<string, Record<string, unknown>>
}
interface PrepResult {
pyodide: PyodideInterface
preparePyEnv: PreparePyEnv
sys: any
prepareStatus: PrepareSuccess | PrepareError
}
export class RunCode {
private output: string[] = []
private pyodide?: PyodideInterface
private preparePyEnv?: PreparePyEnv
private prepPromise?: Promise<PrepResult>
async run(
dependencies: string[],
log: (level: LoggingLevel, data: string) => void,
file?: CodeFile,
globals?: Record<string, any>,
alwaysReturnJson: boolean = false,
toolInjectionOptions?: ToolInjectionOptions,
): Promise<RunSuccess | RunError> {
let pyodide: PyodideInterface
let sys: any
let prepareStatus: PrepareSuccess | PrepareError | undefined
let preparePyEnv: PreparePyEnv
if (this.pyodide && this.preparePyEnv) {
pyodide = this.pyodide
preparePyEnv = this.preparePyEnv
sys = pyodide.pyimport('sys')
} else {
if (!this.prepPromise) {
this.prepPromise = this.prepEnv(dependencies, log)
}
// TODO is this safe if the promise has already been accessed? it seems to work fine
const prep = await this.prepPromise
pyodide = prep.pyodide
preparePyEnv = prep.preparePyEnv
sys = prep.sys
prepareStatus = prep.prepareStatus
}
if (prepareStatus && prepareStatus.kind == 'error') {
return {
status: 'install-error',
output: this.takeOutput(sys),
error: prepareStatus.message,
}
} else if (file) {
try {
// Create globals for python execution, starting with user's global_variables
const globalVars = { ...(globals || {}), __name__: '__main__' }
const globalsProxy = pyodide.toPy(globalVars)
// Setup tool injection if elicitation callback is provided
if (toolInjectionOptions?.elicitationCallback && toolInjectionOptions?.availableTools?.length) {
const dirPath = '/tmp/mcp_run_python'
const pathlib = pyodide.pyimport('pathlib')
const toolModuleName = '_tool_injection'
pathlib
.Path(`${dirPath}/${toolModuleName}.py`)
.write_text(toolInjectionCode)
const toolInjectionModule = pyodide.pyimport(toolModuleName)
// Create Javascript callback wrapper that handles promises
const jsElicitationCallback = async (message: string): Promise<ElicitationResponse> => {
try {
const result = await toolInjectionOptions.elicitationCallback!(message)
return result
} catch (error) {
log('error', `Elicitation callback error: ${error}`)
return {
action: 'decline',
content: { error: `Elicitation failed: ${error}` },
}
}
}
// Convert to Python and inject tools
const pyCallback = pyodide.toPy(jsElicitationCallback)
const pyTools = pyodide.toPy(toolInjectionOptions.availableTools)
const pyToolSchemas = pyodide.toPy(toolInjectionOptions.toolSchemas || {})
toolInjectionModule.inject_tool_functions(globalsProxy, pyTools, pyCallback, pyToolSchemas)
log(
'info',
`Tool injection enabled for: ${toolInjectionOptions.availableTools.join(', ')}`,
)
}
const rawValue = await pyodide.runPythonAsync(file.content, {
globals: globalsProxy,
filename: file.name,
})
return {
status: 'success',
output: this.takeOutput(sys),
returnValueJson: preparePyEnv.dump_json(rawValue, alwaysReturnJson),
}
} catch (err) {
return {
status: 'run-error',
output: this.takeOutput(sys),
error: formatError(err),
}
}
} else {
return {
status: 'success',
output: this.takeOutput(sys),
returnValueJson: null,
}
}
}
async prepEnv(
dependencies: string[],
log: (level: LoggingLevel, data: string) => void,
): Promise<PrepResult> {
const pyodide = await loadPyodide({
stdout: (msg) => {
log('info', msg)
this.output.push(msg)
},
stderr: (msg) => {
log('warning', msg)
this.output.push(msg)
},
})
// see https://github.com/pyodide/pyodide/discussions/5512
const origLoadPackage = pyodide.loadPackage
pyodide.loadPackage = (pkgs, options) =>
origLoadPackage(pkgs, {
// stop pyodide printing to stdout/stderr
messageCallback: (msg: string) => log('debug', msg),
errorCallback: (msg: string) => {
log('error', msg)
this.output.push(`install error: ${msg}`)
},
...options,
})
await pyodide.loadPackage(['micropip', 'pydantic'])
const sys = pyodide.pyimport('sys')
const dirPath = '/tmp/mcp_run_python'
sys.path.append(dirPath)
const pathlib = pyodide.pyimport('pathlib')
pathlib.Path(dirPath).mkdir()
const moduleName = '_prepare_env'
pathlib.Path(`${dirPath}/${moduleName}.py`).write_text(preparePythonCode)
const preparePyEnv: PreparePyEnv = pyodide.pyimport(moduleName)
const prepareStatus = await preparePyEnv.prepare_env(pyodide.toPy(dependencies))
return {
pyodide,
preparePyEnv,
sys,
prepareStatus,
}
}
private takeOutput(sys: any): string[] {
sys.stdout.flush()
sys.stderr.flush()
const output = this.output
this.output = []
return output
}
}
interface RunSuccess {
status: 'success'
// we could record stdout and stderr separately, but I suspect simplicity is more important
output: string[]
returnValueJson: string | null
}
interface RunError {
status: 'install-error' | 'run-error'
output: string[]
error: string
}
export function asXml(runResult: RunSuccess | RunError): string {
const xml = [`<status>${runResult.status}</status>`]
if (runResult.output.length) {
xml.push('<output>')
const escapeXml = escapeClosing('output')
xml.push(...runResult.output.map(escapeXml))
xml.push('</output>')
}
if (runResult.status == 'success') {
if (runResult.returnValueJson) {
xml.push('<return_value>')
xml.push(escapeClosing('return_value')(runResult.returnValueJson))
xml.push('</return_value>')
}
} else {
xml.push('<error>')
xml.push(escapeClosing('error')(runResult.error))
xml.push('</error>')
}
return xml.join('\n')
}
export function asJson(runResult: RunSuccess | RunError): string {
const { status, output } = runResult
const json: Record<string, any> = { status, output }
if (runResult.status == 'success') {
json.return_value = JSON.parse(runResult.returnValueJson || 'null')
} else {
json.error = runResult.error
}
return JSON.stringify(json)
}
function escapeClosing(closingTag: string): (str: string) => string {
const regex = new RegExp(`</?\\s*${closingTag}(?:.*?>)?`, 'gi')
const onMatch = (match: string) => {
return match.replace(/</g, '<').replace(/>/g, '>')
}
return (str) => str.replace(regex, onMatch)
}
function formatError(err: any): string {
let errStr = err.toString()
errStr = errStr.replace(/^PythonError: +/, '')
// remove frames from inside pyodide
errStr = errStr.replace(
/ {2}File "\/lib\/python\d+\.zip\/_pyodide\/.*\n {4}.*\n(?: {4}.*\n)*/g,
'',
)
return errStr
}
interface PrepareSuccess {
kind: 'success'
dependencies?: string[]
}
interface PrepareError {
kind: 'error'
message: string
}
interface PreparePyEnv {
prepare_env: (files: CodeFile[]) => Promise<PrepareSuccess | PrepareError>
dump_json: (value: any, always_return_json: boolean) => string | null
}