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 pathmain.ts
More file actions
482 lines (435 loc) · 13.6 KB
/
main.ts
File metadata and controls
482 lines (435 loc) · 13.6 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
// deno-lint-ignore-file no-explicit-any
/// <reference types="npm:@types/node@22.12.0" />
import './polyfill.ts'
import http from 'node:http'
import { randomUUID } from 'node:crypto'
import { parseArgs } from '@std/cli/parse-args'
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'
import { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js'
import { type LoggingLevel, SetLevelRequestSchema } from '@modelcontextprotocol/sdk/types.js'
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import { z } from 'zod'
import { asJson, asXml, RunCode } from './runCode.ts'
import { Buffer } from 'node:buffer'
const VERSION = '0.0.13'
// Tool injection support
const EMPTY_TOOLS_RESULT = { toolNames: [], toolSchemas: {} }
const ELICIT_RESPONSE_SCHEMA = z.object({
action: z.enum(['accept', 'decline', 'cancel']),
content: z.optional(z.record(z.string(), z.unknown())),
})
// Schema for tool discovery responses
const TOOL_DISCOVERY_RESPONSE_SCHEMA = {
type: 'object',
properties: {
action: {
type: 'string',
enum: ['accept', 'decline', 'cancel'],
description: 'Action to take with the tool discovery request',
},
content: {
type: 'object',
properties: {
data: {
type: 'string',
description: 'JSON string containing tool_names and tool_schemas',
},
},
description: 'Tool discovery result data',
},
},
required: ['action'],
}
// Schema for tool execution responses
const TOOL_EXECUTION_RESPONSE_SCHEMA = {
type: 'object',
properties: {
action: {
type: 'string',
enum: ['accept', 'decline', 'cancel'],
description: 'Action to take with the tool execution request',
},
content: {
type: 'object',
properties: {
result: {
type: 'string',
description: 'JSON string containing tool execution result',
},
error: {
type: 'string',
description: 'Error message if execution failed',
},
retry: {
type: 'string',
description: 'JSON string containing retry information if tool needs retry',
},
},
description: 'Tool execution result or error information',
},
},
required: ['action'],
}
function makeElicitationRequest(
server: McpServer,
message: string,
requestedSchema: Record<string, unknown>,
): Promise<z.infer<typeof ELICIT_RESPONSE_SCHEMA>> {
return server.server.request(
{
method: 'elicitation/create',
params: { message, requestedSchema },
},
ELICIT_RESPONSE_SCHEMA,
)
}
async function discoverAvailableTools(
server: McpServer,
): Promise<{ toolNames: string[]; toolSchemas: Record<string, Record<string, unknown>> }> {
try {
const result = await makeElicitationRequest(
server,
JSON.stringify({ action: 'discover_tools' }),
TOOL_DISCOVERY_RESPONSE_SCHEMA,
)
if (result.action === 'accept' && result.content?.data) {
const data = JSON.parse(result.content.data as string)
return {
toolNames: data.tool_names || [],
toolSchemas: data.tool_schemas || {},
}
}
} catch (error) {
console.warn('Tool discovery failed:', error)
}
return EMPTY_TOOLS_RESULT
}
function createToolExecutionCallback(
server: McpServer,
): (message: string) => Promise<z.infer<typeof ELICIT_RESPONSE_SCHEMA>> {
return async (message: string) => {
try {
return await makeElicitationRequest(
server,
message,
TOOL_EXECUTION_RESPONSE_SCHEMA,
)
} catch (error) {
console.error('Tool execution failed:', error)
return {
action: 'decline',
content: { error: `Tool execution failed: ${error}` },
}
}
}
}
export async function main() {
const { args } = Deno
const flags = parseArgs(Deno.args, {
string: ['deps', 'return-mode', 'port'],
default: { port: '3001', 'return-mode': 'xml' },
})
const deps = flags.deps?.split(',') ?? []
if (args.length >= 1) {
if (args[0] === 'stdio') {
await runStdio(deps, flags['return-mode'])
return
} else if (args[0] === 'streamable_http') {
const port = parseInt(flags.port)
runStreamableHttp(port, deps, flags['return-mode'])
return
} else if (args[0] === 'example') {
await example(deps)
return
} else if (args[0] === 'noop') {
await installDeps(deps)
return
}
}
console.error(
`\
Invalid arguments: ${args.join(' ')}
Usage: deno ... deno/main.ts [stdio|streamable_http|install_deps|noop]
options:
--port <port> Port to run the HTTP server on (default: 3001)
--deps <deps> Comma separated list of dependencies to install
--return-mode <xml/json> Return mode for output data (default: xml)`,
)
Deno.exit(1)
}
/*
* Create an MCP server with the `run_python_code` tool registered.
*/
function createServer(deps: string[], returnMode: string): McpServer {
const runCode = new RunCode()
const server = new McpServer(
{
name: 'MCP Run Python',
version: VERSION,
},
{
instructions: 'Call the "run_python_code" tool with the Python code to run.',
capabilities: {
logging: {},
},
},
)
const toolDescription = `Tool to execute Python code and return stdout, stderr, and return value.
The code may be async, and the value on the last line will be returned as the return value.
The code will be executed with Python 3.13.
`
let setLogLevel: LoggingLevel = 'emergency'
server.server.setRequestHandler(SetLevelRequestSchema, (request) => {
setLogLevel = request.params.level
return {}
})
server.registerTool(
'discover_available_tools',
{
title: 'Discover available tools',
description:
'Discover what tools are available for injection into Python code execution environment. Call this before writing Python code to know which tools you can use.',
inputSchema: {},
},
async () => {
// Discover available tools via elicitation
const { toolNames: availableTools, toolSchemas } = await discoverAvailableTools(server)
return {
content: [
{
type: 'text',
text: JSON.stringify(
{
available_tools: availableTools,
tool_schemas: toolSchemas,
usage_note:
"These tools will be available as Python functions when you run Python code. Tool names with hyphens become underscores (e.g., 'web-search' -> 'web_search').",
},
null,
2,
),
},
],
}
},
)
server.registerTool(
'run_python_code',
{
title: 'Run Python code',
description: toolDescription,
inputSchema: {
python_code: z.string().describe('Python code to run'),
global_variables: z.record(z.string(), z.any()).default({}).describe(
'Map of global variables in context when the code is executed',
),
},
},
async ({ python_code, global_variables }: { python_code: string; global_variables: Record<string, any> }) => {
const logPromises: Promise<void>[] = []
// Discover available tools via elicitation
const { toolNames: availableTools, toolSchemas } = await discoverAvailableTools(server)
// Create elicitation callback for tool execution if tools are available
let toolInjectionOptions
if (availableTools.length > 0) {
toolInjectionOptions = {
elicitationCallback: createToolExecutionCallback(server),
availableTools: availableTools,
toolSchemas: toolSchemas,
}
}
const result = await runCode.run(
deps,
(level, data) => {
if (LogLevels.indexOf(level) >= LogLevels.indexOf(setLogLevel)) {
logPromises.push(server.server.sendLoggingMessage({ level, data }))
}
},
{ name: 'main.py', content: python_code },
global_variables,
returnMode !== 'xml',
toolInjectionOptions,
)
await Promise.all(logPromises)
return {
content: [{ type: 'text', text: returnMode === 'xml' ? asXml(result) : asJson(result) }],
}
},
)
return server
}
/*
* Define some QOL functions for both the Streamable HTTP server implementation
*/
function httpGetUrl(req: http.IncomingMessage): URL {
return new URL(
req.url ?? '',
`http://${req.headers.host ?? 'unknown'}`,
)
}
function httpGetBody(req: http.IncomingMessage): Promise<JSON> {
// https://nodejs.org/en/learn/modules/anatomy-of-an-http-transaction#request-body
return new Promise((resolve) => {
const bodyParts: any[] = []
let body
req.on('data', (chunk) => {
bodyParts.push(chunk)
}).on('end', () => {
body = Buffer.concat(bodyParts).toString()
resolve(JSON.parse(body))
})
})
}
function httpSetTextResponse(res: http.ServerResponse, status: number, text: string) {
res.setHeader('Content-Type', 'text/plain')
res.statusCode = status
res.end(`${text}\n`)
}
function httpSetJsonResponse(res: http.ServerResponse, status: number, text: string, code: number) {
res.setHeader('Content-Type', 'application/json')
res.statusCode = status
res.write(JSON.stringify({
jsonrpc: '2.0',
error: {
code: code,
message: text,
},
id: null,
}))
res.end()
}
/*
* Run the MCP server using the Streamable HTTP transport
*/
function runStreamableHttp(port: number, deps: string[], returnMode: string) {
// https://github.com/modelcontextprotocol/typescript-sdk?tab=readme-ov-file#with-session-management
const mcpServer = createServer(deps, returnMode)
const transports: { [sessionId: string]: StreamableHTTPServerTransport } = {}
const server = http.createServer(async (req, res) => {
const url = httpGetUrl(req)
let pathMatch = false
function match(method: string, path: string): boolean {
if (url.pathname === path) {
pathMatch = true
return req.method === method
}
return false
}
// Reusable handler for GET and DELETE requests
async function handleSessionRequest() {
const sessionId = req.headers['mcp-session-id'] as string | undefined
if (!sessionId || !transports[sessionId]) {
httpSetTextResponse(res, 400, 'Invalid or missing session ID')
return
}
const transport = transports[sessionId]
await transport.handleRequest(req, res)
}
// Handle different request methods and paths
if (match('POST', '/mcp')) {
// Check for existing session ID
const sessionId = req.headers['mcp-session-id'] as string | undefined
let transport: StreamableHTTPServerTransport
const body = await httpGetBody(req)
if (sessionId && transports[sessionId]) {
// Reuse existing transport
transport = transports[sessionId]
} else if (!sessionId && isInitializeRequest(body)) {
// New initialization request
transport = new StreamableHTTPServerTransport({
sessionIdGenerator: () => randomUUID(),
onsessioninitialized: (sessionId) => {
// Store the transport by session ID
transports[sessionId] = transport
},
})
// Clean up transport when closed
transport.onclose = () => {
if (transport.sessionId) {
delete transports[transport.sessionId]
}
}
await mcpServer.connect(transport)
} else {
httpSetJsonResponse(res, 400, 'Bad Request: No valid session ID provided', -32000)
return
}
// Handle the request
await transport.handleRequest(req, res, body)
} else if (match('GET', '/mcp')) {
// Handle server-to-client notifications
await handleSessionRequest()
} else if (match('DELETE', '/mcp')) {
// Handle requests for session termination
await handleSessionRequest()
} else if (pathMatch) {
httpSetTextResponse(res, 405, 'Method not allowed')
} else {
httpSetTextResponse(res, 404, 'Page not found')
}
})
server.listen(port, () => {
console.log(`Listening on port ${port}`)
})
}
/*
* Run the MCP server using the Stdio transport.
*/
async function runStdio(deps: string[], returnMode: string) {
const mcpServer = createServer(deps, returnMode)
const transport = new StdioServerTransport()
await mcpServer.connect(transport)
}
/*
* Run pyodide to download and install dependencies.
*/
async function installDeps(deps: string[]) {
const runCode = new RunCode()
const result = await runCode.run(
deps,
(level, data) => console.error(`${level}|${data}`),
)
if (result.status !== 'success') {
console.error('error|Failed to install dependencies')
Deno.exit(1)
}
}
/*
* Run a short example script that requires numpy.
*/
async function example(deps: string[]) {
console.error(
`Running example script for MCP Run Python version ${VERSION}...`,
)
const code = `
import numpy
a = numpy.array([1, 2, 3])
print('numpy array:', a)
a
`
const runCode = new RunCode()
const result = await runCode.run(
deps,
// use warn to avoid recursion since console.log is patched in runCode
(level, data) => console.warn(`${level}: ${data}`),
{ name: 'example.py', content: code },
)
console.log('Tool return value:')
console.log(asXml(result))
if (result.status !== 'success') {
Deno.exit(1)
}
}
// list of log levels to use for level comparison
const LogLevels: LoggingLevel[] = [
'debug',
'info',
'notice',
'warning',
'error',
'critical',
'alert',
'emergency',
]
await main()