# -*- coding: utf-8 -*-"""@author:XuMing(xuming624@qq.com)@description:RunPythonCode MCP Server implementation.This module provides Python code execution tools via MCP (Model Context Protocol)."""from typing import Optionalfrom mcp.server.fastmcp import FastMCPimport tempfileimport syssys.path.append('..')from run_python_code.code import RunPythonCode# Create MCP server instancemcp = FastMCP(name="RunPythonCodeServer",instructions="Execute Python code, install python packages, and run Python files",)# Initialize the RunPythonCode toolpython_runner = RunPythonCode(base_dir=tempfile.mkdtemp())@mcp.tool()def run_python_code(code: str, variable_to_return: Optional[str] = None) -> str:"""Run Python code in the current environment.Parameters:code: The Python code to executevariable_to_return: Optional variable name to return its valueReturns:str: The value of variable_to_return if provided, otherwise success message or error"""return python_runner.run_python_code(code, variable_to_return)@mcp.tool()def save_to_file_and_run(file_name: str,code: str,variable_to_return: Optional[str] = None,overwrite: bool = True) -> str:"""Save Python code to a file and run it.Parameters:file_name: Name of the file to save (e.g., "script.py")code: Python code to save and executevariable_to_return: Optional variable name to return its valueoverwrite: Whether to overwrite existing fileReturns:str: The value of variable_to_return if provided, otherwise success message or error"""return python_runner.save_to_file_and_run(file_name, code, variable_to_return, overwrite)@mcp.tool()def pip_install_package(package_name: str) -> str:"""Install a Python package using pip.Parameters:package_name: Name of the package to installReturns:str: Success message or error information"""return python_runner.pip_install_package(package_name)@mcp.tool()def run_python_file(file_name: str, variable_to_return: Optional[str] = None) -> str:"""Run an existing Python file.Parameters:file_name: Name of the Python file to runvariable_to_return: Optional variable name to return its valueReturns:str: The value of variable_to_return if provided, otherwise success message or error"""return python_runner.run_python_file_return_variable(file_name, variable_to_return)def run_mcp_server():"""Run the MCP server with the specified transport."""mcp.run(transport='stdio')
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。