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
359 lines (320 loc) · 10.6 KB
/
main.ts
File metadata and controls
359 lines (320 loc) · 10.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
// 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'
export async function main() {
const { args } = Deno
const flags = parseArgs(Deno.args, {
string: ['deps', 'return-mode', 'port', 'host'],
default: { port: '3001', 'return-mode': 'xml', host: '127.0.0.1' },
})
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)
const host = flags.host
runStreamableHttp(port, host, deps, flags['return-mode'], false)
return
} else if (args[0] === 'streamable_http_stateless') {
const port = parseInt(flags.port)
const host = flags.host
runStreamableHttp(port, host, deps, flags['return-mode'], true)
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|streamable_http_stateless|example|noop]
options:
--port <port> Port to run the HTTP server on (default: 3001)
--host <host> Host to run the HTTP server on (default: 127.0.0.1)
--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(
'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>[] = []
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',
)
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, host: string, deps: string[], returnMode: string, stateless: boolean): void {
const server = (stateless ? createStatelessHttpServer : createStatefulHttpServer)(deps, returnMode)
server.listen(port, host, () => {
console.log(`Listening on port ${port}`)
})
}
function createStatelessHttpServer(deps: string[], returnMode: string): http.Server {
return http.createServer(async (req, res) => {
const url = httpGetUrl(req)
if (url.pathname !== '/mcp') {
httpSetTextResponse(res, 404, 'Page not found')
return
}
try {
const mcpServer = createServer(deps, returnMode)
const transport: StreamableHTTPServerTransport = new StreamableHTTPServerTransport({
sessionIdGenerator: undefined,
})
res.on('close', () => {
transport.close()
mcpServer.close()
})
await mcpServer.connect(transport)
const body = req.method === 'POST' ? await httpGetBody(req) : undefined
await transport.handleRequest(req, res, body)
} catch (error) {
console.error('Error handling MCP request:', error)
if (!res.headersSent) {
httpSetJsonResponse(res, 500, 'Internal server error', -32603)
}
}
})
}
function createStatefulHttpServer(deps: string[], returnMode: string): http.Server {
// Stateful mode with session management
// https://github.com/modelcontextprotocol/typescript-sdk?tab=readme-ov-file#with-session-management
const mcpServer = createServer(deps, returnMode)
const transports: { [sessionId: string]: StreamableHTTPServerTransport } = {}
return 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')
}
})
}
/*
* 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()