Skip to main content
Glama

run_script

Execute Python scripts for data analytics tasks, including data processing, visualization with matplotlib/plotly, and saving results for further analysis.

Instructions

Python Script Execution Tool

Purpose: Execute Python scripts for specific data analytics tasks.

Allowed Actions 1. Print Results: Output will be displayed as the script’s stdout. 2. [Optional] Save DataFrames: Store DataFrames in memory for future use by specifying a save_to_memory name. 3. Create Charts: You can use matplotlib.pyplot or plotly.graph_objects to create and save charts to an absolute path.

Prohibited Actions 1. Overwriting Original DataFrames: Do not modify existing DataFrames to preserve their integrity for future tasks.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
scriptYes
save_to_memoryNo

Implementation Reference

  • Core handler function that safely executes the provided Python script using exec(), with access to data analysis libraries (pandas, numpy, etc.), loaded dataframes, and plotting libraries. Captures stdout output and handles errors, optionally saving results to memory.
    def safe_eval(self, script: str, save_to_memory: Optional[List[str]] = None):
        """safely run a script, return the result if valid, otherwise return the error message"""
        # first extract dataframes from the self.data
        local_dict = {
            **{df_name: df for df_name, df in self.data.items()},
            'plt': plt, # Add matplotlib
            'go': go,   # Add plotly graph_objects
            'os': os    # Add os for path manipulation
        }
        # execute the script and return the result and if there is error, return the error message
        stdout_capture = StringIO()
        old_stdout = sys.stdout # Store the original stdout
    
        try:
            sys.stdout = stdout_capture # Redirect stdout
            self.notes.append(f"Running script: \n{script}")
            # pylint: disable=exec-used
            exec(script, \
                {'pd': pd, 'np': np, 'scipy': scipy, 'sklearn': sklearn, 'statsmodels': sm}, \
                local_dict)
            std_out_script = stdout_capture.getvalue()
        except Exception as e:
            error_message = f"Error running script: {str(e)}"
            self.notes.append(f"ERROR: {error_message}")
            return [
                TextContent(type="text", text=f"Error: {error_message}")
            ]
        finally:
            sys.stdout = old_stdout # Restore original stdout
    
        # check if the result is a dataframe
        if save_to_memory:
            for df_name in save_to_memory:
                self.notes.append(f"Saving dataframe '{df_name}' to memory")
                self.data[df_name] = local_dict.get(df_name)
    
        output = std_out_script if std_out_script else "No output"
        self.notes.append(f"Result: {output}")
        return [
            TextContent(type="text", text=f"print out result: {output}")
        ]
  • Pydantic schema for run_script tool input: required 'script' (the Python code to execute) and optional 'save_to_memory' list of DataFrame names to persist in memory.
    class RunScript(BaseModel):
        script: str
        save_to_memory: Optional[List[str]] = None
  • Registration of the 'run_script' tool in the MCP server's list_tools handler, specifying name, description, and input schema.
    Tool(name=DataExplorationTools.RUN_SCRIPT, description=RUN_SCRIPT_TOOL_DESCRIPTION, inputSchema=RunScript.model_json_schema()),
  • Dispatch handler in the MCP call_tool method that invokes the safe_eval function for the 'run_script' tool.
    elif name == DataExplorationTools.RUN_SCRIPT:
        return script_runner.safe_eval(arguments.get("script"), arguments.get("save_to_memory"))
  • Enum defining the tool name constant RUN_SCRIPT = 'run_script' used throughout the code.
    class DataExplorationTools(str, Enum):
        LOAD_FILE = "load_file"
        RUN_SCRIPT = "run_script"
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It effectively describes key behavioral traits: it executes Python scripts, outputs results via stdout, allows saving DataFrames in memory and creating charts, and prohibits overwriting original DataFrames. This covers core functionality, constraints, and output methods, though it lacks details on error handling, execution environment, or resource limits.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is well-structured with clear sections (Purpose, Allowed Actions, Prohibited Actions) and uses bullet points for readability. It's appropriately sized with no redundant sentences, though the 'Purpose' section could be more front-loaded with critical details.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity (executing arbitrary Python scripts), no annotations, no output schema, and low schema coverage, the description is moderately complete. It covers basic behavior and constraints but lacks details on return values, error cases, execution context, or integration with sibling tools, leaving gaps for an AI agent to infer.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema has 0% description coverage, so the description must compensate. It mentions 'save_to_memory' in the allowed actions, providing some semantic context for that parameter, but doesn't explain the 'script' parameter beyond implying it's for Python code. This leaves key parameter details undocumented, failing to fully compensate for the schema gap.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose as 'Execute Python scripts for specific data analytics tasks,' which is a specific verb+resource combination. However, it doesn't explicitly differentiate from the sibling tool 'load_file' (which likely loads files rather than executing scripts), so it misses full sibling differentiation.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides implied usage through 'Allowed Actions' and 'Prohibited Actions' sections, which suggest when to use this tool (for data analytics tasks with specific allowed outputs) and some constraints (not overwriting DataFrames). However, it doesn't explicitly state when to use this vs. alternatives like 'load_file' or other potential tools, nor does it provide clear exclusions or prerequisites.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/OuchiniKaeru/mcp-data-analyzer'

If you have feedback or need assistance with the MCP directory API, please join our Discord server