9
9
import os
10
10
import re
11
11
import tempfile
12
+ import subprocess
13
+ import ast
12
14
13
15
14
16
def sanitize_name (name : str ) -> str :
@@ -48,6 +50,34 @@ async def get_mcp_servers() -> list[StdioServerParameters]:
48
50
return []
49
51
50
52
53
+ def extract_imports (code : str ) -> list [str ]:
54
+ """Extract top-level import statements from the Python code."""
55
+ try :
56
+ tree = ast .parse (code )
57
+ imports = set ()
58
+
59
+ for node in ast .walk (tree ):
60
+ if isinstance (node , ast .Import ):
61
+ for alias in node .names :
62
+ imports .add (alias .name .split ("." )[0 ])
63
+ elif isinstance (node , ast .ImportFrom ) and node .module :
64
+ imports .add (node .module .split ("." )[0 ])
65
+
66
+ return list (imports )
67
+ except Exception as e :
68
+ print (f"Error parsing imports: { e } " )
69
+ return []
70
+
71
+
72
+ def install_dependencies (dependencies : list [str ]):
73
+ """Install required dependencies using uv pip."""
74
+ try :
75
+ print (f"Checking dependencies: { dependencies } " )
76
+ subprocess .run (["uv" , "pip" , "install" ] + dependencies , check = True )
77
+ except subprocess .CalledProcessError as e :
78
+ print (f"Failed to install dependencies: { e } " )
79
+
80
+
51
81
async def get_custom_mcp_servers () -> list [StdioServerParameters ]:
52
82
try :
53
83
async with httpx .AsyncClient () as client :
@@ -58,23 +88,35 @@ async def get_custom_mcp_servers() -> list[StdioServerParameters]:
58
88
response .raise_for_status ()
59
89
data = response .json ()
60
90
server_params = []
91
+
61
92
for params in data :
62
93
if "code" not in params or "code_uuid" not in params :
63
94
continue
95
+
64
96
code_uuid = params ["code_uuid" ]
97
+
98
+ # Create temp file for the script
65
99
with tempfile .NamedTemporaryFile (
66
100
mode = "w" , suffix = f"_{ code_uuid } .py" , delete = False
67
101
) as temp_file :
68
102
temp_file .write (params ["code" ])
103
+ script_path = temp_file .name
104
+
105
+ # Extract dependencies from the code
106
+ dependencies = extract_imports (params ["code" ])
107
+ if dependencies :
108
+ install_dependencies (dependencies )
109
+
69
110
params ["command" ] = "uv"
70
- params ["args" ] = ["run" , temp_file .name ] + params .get (
71
- "additionalArgs" , []
72
- )
111
+ params ["args" ] = ["run" , script_path ] + params .get ("additionalArgs" , [])
112
+
73
113
if "env" in params and not params ["env" ]:
74
114
params ["env" ] = None
115
+
75
116
server_params .append (StdioServerParameters (** params ))
76
117
return server_params
77
- except Exception :
118
+ except Exception as e :
119
+ print (f"Error fetching MCP servers: { e } " )
78
120
return []
79
121
80
122
0 commit comments