Spaces:
Sleeping
Sleeping
File size: 12,213 Bytes
ba6de18 | 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 | """MCP protocol handler - maps MCP tool calls to actual operations."""
from __future__ import annotations
import logging
from typing import Any
from app.environment import configure_environment, get_environment_config
from app.executor import get_executor
from app.file_manager import FileManager
from app.models import MCPToolResult
from app.package_manager import get_package_manager
logger = logging.getLogger(__name__)
# Tool definitions for MCP list_tools
TOOL_DEFINITIONS = [
{
"name": "execute_code",
"description": "Executes Python code in the configured environment. Best for short code snippets.",
"inputSchema": {
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "Python code to execute",
},
"filename": {
"type": "string",
"description": "Optional filename (without extension)",
},
},
"required": ["code"],
},
},
{
"name": "install_dependencies",
"description": "Installs Python packages in the environment.",
"inputSchema": {
"type": "object",
"properties": {
"packages": {
"type": "array",
"items": {"type": "string"},
"description": "List of package names to install",
},
},
"required": ["packages"],
},
},
{
"name": "check_installed_packages",
"description": "Checks if packages are already installed in the environment.",
"inputSchema": {
"type": "object",
"properties": {
"packages": {
"type": "array",
"items": {"type": "string"},
"description": "List of package names to check",
},
},
"required": ["packages"],
},
},
{
"name": "configure_environment",
"description": "Dynamically changes the environment configuration.",
"inputSchema": {
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": ["conda", "venv", "venv-uv"],
"description": "Environment type",
},
"conda_name": {
"type": "string",
"description": "Conda environment name (required for conda type)",
},
"venv_path": {
"type": "string",
"description": "Virtualenv path (required for venv type)",
},
"uv_venv_path": {
"type": "string",
"description": "UV virtualenv path (required for venv-uv type)",
},
},
"required": ["type"],
},
},
{
"name": "get_environment_config",
"description": "Gets the current environment configuration.",
"inputSchema": {
"type": "object",
"properties": {},
},
},
{
"name": "initialize_code_file",
"description": "Creates a new Python file with initial content. Use this as the first step for longer code that may exceed token limits.",
"inputSchema": {
"type": "object",
"properties": {
"content": {
"type": "string",
"description": "Initial file content",
},
"filename": {
"type": "string",
"description": "Optional filename (without extension)",
},
},
"required": ["content"],
},
},
{
"name": "append_to_code_file",
"description": "Appends content to an existing Python code file.",
"inputSchema": {
"type": "object",
"properties": {
"file_path": {
"type": "string",
"description": "Path to the existing code file",
},
"content": {
"type": "string",
"description": "Content to append",
},
},
"required": ["file_path", "content"],
},
},
{
"name": "execute_code_file",
"description": "Executes an existing Python file.",
"inputSchema": {
"type": "object",
"properties": {
"file_path": {
"type": "string",
"description": "Path to the code file to execute",
},
},
"required": ["file_path"],
},
},
{
"name": "read_code_file",
"description": "Reads the content of an existing Python code file.",
"inputSchema": {
"type": "object",
"properties": {
"file_path": {
"type": "string",
"description": "Path to the code file to read",
},
},
"required": ["file_path"],
},
},
]
async def handle_tool_call(name: str, arguments: dict[str, Any]) -> MCPToolResult:
"""Route an MCP tool call to the appropriate handler."""
try:
if name == "execute_code":
return await _handle_execute_code(arguments)
elif name == "install_dependencies":
return await _handle_install_dependencies(arguments)
elif name == "check_installed_packages":
return await _handle_check_packages(arguments)
elif name == "configure_environment":
return _handle_configure_environment(arguments)
elif name == "get_environment_config":
return _handle_get_environment_config()
elif name == "initialize_code_file":
return _handle_initialize_code_file(arguments)
elif name == "append_to_code_file":
return _handle_append_to_code_file(arguments)
elif name == "execute_code_file":
return await _handle_execute_code_file(arguments)
elif name == "read_code_file":
return _handle_read_code_file(arguments)
else:
return MCPToolResult(
content=[{"type": "text", "text": f"Unknown tool: {name}"}],
isError=True,
)
except Exception as e:
logger.exception("Error handling tool call: %s", name)
return MCPToolResult(
content=[{"type": "text", "text": f"Error: {str(e)}"}],
isError=True,
)
async def _handle_execute_code(args: dict) -> MCPToolResult:
executor = get_executor()
result = await executor.execute_code(args["code"], args.get("filename"))
output_parts = []
if result.stdout:
output_parts.append(f"STDOUT:\n{result.stdout}")
if result.stderr:
output_parts.append(f"STDERR:\n{result.stderr}")
output_parts.append(f"Return code: {result.return_code}")
output_parts.append(f"Execution time: {result.execution_time:.2f}s")
output_parts.append(f"File: {result.file_path}")
return MCPToolResult(
content=[{"type": "text", "text": "\n".join(output_parts)}],
isError=not result.success,
)
async def _handle_install_dependencies(args: dict) -> MCPToolResult:
pm = get_package_manager()
result = await pm.install_packages(args["packages"])
text = f"Installation {'succeeded' if result['success'] else 'failed'}\n"
if result.get("stdout"):
text += f"Output:\n{result['stdout']}\n"
if result.get("stderr"):
text += f"Errors:\n{result['stderr']}\n"
return MCPToolResult(
content=[{"type": "text", "text": text}],
isError=not result["success"],
)
async def _handle_check_packages(args: dict) -> MCPToolResult:
pm = get_package_manager()
results = await pm.check_packages(args["packages"])
lines = []
for r in results:
status = "✓ installed" if r.installed else "✗ not installed"
version = f" (v{r.version})" if r.version and r.version != "unknown" else ""
lines.append(f" {r.package}: {status}{version}")
return MCPToolResult(
content=[{"type": "text", "text": "Package status:\n" + "\n".join(lines)}],
isError=False,
)
def _handle_configure_environment(args: dict) -> MCPToolResult:
try:
config = configure_environment(
env_type=args["type"],
conda_name=args.get("conda_name"),
venv_path=args.get("venv_path"),
uv_venv_path=args.get("uv_venv_path"),
)
return MCPToolResult(
content=[
{
"type": "text",
"text": f"Environment configured:\n"
f" Type: {config.env_type}\n"
f" Python: {config.python_executable}\n"
f" Storage: {config.code_storage_dir}",
}
],
isError=False,
)
except ValueError as e:
return MCPToolResult(
content=[{"type": "text", "text": f"Configuration error: {str(e)}"}],
isError=True,
)
def _handle_get_environment_config() -> MCPToolResult:
config = get_environment_config()
return MCPToolResult(
content=[
{
"type": "text",
"text": f"Current environment:\n"
f" Type: {config.env_type}\n"
f" Python: {config.python_executable}\n"
f" Storage: {config.code_storage_dir}\n"
f" Conda env: {config.conda_env_name or 'N/A'}\n"
f" Venv path: {config.venv_path or 'N/A'}\n"
f" UV venv path: {config.uv_venv_path or 'N/A'}",
}
],
isError=False,
)
def _handle_initialize_code_file(args: dict) -> MCPToolResult:
fm = FileManager()
result = fm.create_file(args["content"], args.get("filename"))
if result.success:
return MCPToolResult(
content=[
{
"type": "text",
"text": f"File created: {result.file_path}\n{result.message}",
}
],
isError=False,
)
return MCPToolResult(
content=[{"type": "text", "text": f"Error: {result.message}"}],
isError=True,
)
def _handle_append_to_code_file(args: dict) -> MCPToolResult:
fm = FileManager()
result = fm.append_to_file(args["file_path"], args["content"])
return MCPToolResult(
content=[
{
"type": "text",
"text": result.message + (f"\nFile: {result.file_path}" if result.success else ""),
}
],
isError=not result.success,
)
async def _handle_execute_code_file(args: dict) -> MCPToolResult:
executor = get_executor()
result = await executor.execute_file(args["file_path"])
output_parts = []
if result.stdout:
output_parts.append(f"STDOUT:\n{result.stdout}")
if result.stderr:
output_parts.append(f"STDERR:\n{result.stderr}")
output_parts.append(f"Return code: {result.return_code}")
output_parts.append(f"Execution time: {result.execution_time:.2f}s")
return MCPToolResult(
content=[{"type": "text", "text": "\n".join(output_parts)}],
isError=not result.success,
)
def _handle_read_code_file(args: dict) -> MCPToolResult:
fm = FileManager()
result = fm.read_file(args["file_path"])
if result.success:
return MCPToolResult(
content=[
{
"type": "text",
"text": f"File: {result.file_path}\n\n{result.content}",
}
],
isError=False,
)
return MCPToolResult(
content=[{"type": "text", "text": f"Error: {result.message}"}],
isError=True,
) |