Skip to content

Commit 9b8a955

Browse files
committed
also install dependencies
1 parent fe85395 commit 9b8a955

File tree

1 file changed

+46
-4
lines changed

1 file changed

+46
-4
lines changed

src/mcp_server_metatool/server.py

Lines changed: 46 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99
import os
1010
import re
1111
import tempfile
12+
import subprocess
13+
import ast
1214

1315

1416
def sanitize_name(name: str) -> str:
@@ -48,6 +50,34 @@ async def get_mcp_servers() -> list[StdioServerParameters]:
4850
return []
4951

5052

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+
5181
async def get_custom_mcp_servers() -> list[StdioServerParameters]:
5282
try:
5383
async with httpx.AsyncClient() as client:
@@ -58,23 +88,35 @@ async def get_custom_mcp_servers() -> list[StdioServerParameters]:
5888
response.raise_for_status()
5989
data = response.json()
6090
server_params = []
91+
6192
for params in data:
6293
if "code" not in params or "code_uuid" not in params:
6394
continue
95+
6496
code_uuid = params["code_uuid"]
97+
98+
# Create temp file for the script
6599
with tempfile.NamedTemporaryFile(
66100
mode="w", suffix=f"_{code_uuid}.py", delete=False
67101
) as temp_file:
68102
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+
69110
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+
73113
if "env" in params and not params["env"]:
74114
params["env"] = None
115+
75116
server_params.append(StdioServerParameters(**params))
76117
return server_params
77-
except Exception:
118+
except Exception as e:
119+
print(f"Error fetching MCP servers: {e}")
78120
return []
79121

80122

0 commit comments

Comments
 (0)