MCPcopy Create free account
hub / github.com/Roy3838/Observer / executePython

Function executePython

app/src/utils/handlers/python.ts:7–86  ·  view source on GitHub ↗
(
  response: string,
  agentId: string,
  code: string
)

Source from the content-addressed store, hash-verified

5 * Execute Python code using a Jupyter kernel
6 */
7export async function executePython(
8 response: string,
9 agentId: string,
10 code: string
11): Promise<boolean> {
12 Logger.debug(agentId, 'Executing Python code');
13 const { host, port, token } = getJupyterConfig();
14
15 try {
16 // Lazy load Jupyter services - only loads when Python execution is used!
17 const { KernelManager, ServerConnection } = await import('@jupyterlab/services');
18
19 // Create server settings with token and CORS handling
20 const serverSettings = ServerConnection.makeSettings({
21 baseUrl: `http://${host}:${port}`,
22 wsUrl: `ws://${host}:${port}`,
23 token: token,
24 init: {
25 mode: 'cors',
26 headers: {
27 'Accept': 'application/json',
28 'Content-Type': 'application/json'
29 }
30 }
31 });
32
33 // Skip connection test - we'll rely on the kernel API
34
35 // Create kernel manager with settings
36 const kernelManager = new KernelManager({ serverSettings });
37
38 // Start a new kernel directly instead of trying to list kernels first
39 Logger.debug(agentId, 'Starting new kernel');
40 const kernel = await kernelManager.startNew({ name: 'python3' });
41 Logger.debug(agentId, `Started new kernel: ${kernel.id}`);
42
43 // We already have a kernel from above
44
45 // Prepare code with variables
46 const fullCode = `
47response = """${response.replace(/"""/g, '\\"\\"\\"')}"""
48agentId = "${agentId}"
49# User code begins here
50${code}
51`;
52
53 // Execute the code
54 Logger.debug(agentId, 'Executing code');
55 let hasError = false;
56 const future = kernel.requestExecute({ code: fullCode });
57
58 // Handle messages with proper type casting
59 future.onIOPub = (msg: any) => {
60 const msgType = msg.header.msg_type;
61
62 if (msgType === 'error') {
63 hasError = true;
64 const errorContent = msg.content;

Callers 1

postProcessFunction · 0.85

Calls 5

getJupyterConfigFunction · 0.90
errorMethod · 0.80
warnMethod · 0.80
infoMethod · 0.80
debugMethod · 0.45

Tested by

no test coverage detected