Skip to main content
Glama

run_applescript

Execute AppleScript commands to control macOS applications and automate tasks. Supports multi-line scripts, returns plain text output.

Instructions

Execute AppleScript commands on macOS. Use 'tell application "AppName"' to control apps. Multi-line scripts supported. Returns plain text output, truncated to 10,000 chars for large results.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
scriptYesAppleScript code to execute.

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The async handler function for the run_applescript tool. It validates the script using validate_script(), executes it via osascript subprocess, and returns stdout with truncation support.
    @mcp.tool()
    async def run_applescript(
        script: str = Field(description="AppleScript code to execute."),
    ) -> str:
        """
        Execute AppleScript commands on macOS.
        Use 'tell application "AppName"' to control apps. Multi-line scripts supported.
        Returns plain text output, truncated to 10,000 chars for large results.
        """
        timeout = int(os.getenv("TIMEOUT", "30"))
        max_output = int(os.getenv("MAX_OUTPUT", "10000"))
    
        is_safe, error_message, _ = validate_script(script)
        if not is_safe:
            raise RuntimeError(error_message)
    
        try:
            result = subprocess.run(
                ["osascript", "-e", script],
                capture_output=True,
                text=True,
                timeout=timeout,
            )
    
            if result.returncode == 0:
                output = result.stdout.strip()
    
                if not output:
                    return "Script executed successfully (no output)"
    
                # Truncate if output exceeds limit
                if len(output) > max_output:
                    truncated = output[:max_output]
                    return (
                        f"{truncated}\n\n"
                        f"[Output truncated: {len(output):,} characters total, showing first {max_output:,}]"
                    )
    
                return output
            else:
                raise RuntimeError(f"AppleScript execution failed: {result.stderr.strip()}")
    
        except subprocess.TimeoutExpired as e:
            raise RuntimeError(f"Script execution timed out after {timeout} seconds") from e
        except Exception as e:
            if isinstance(e, RuntimeError):
                raise
            raise RuntimeError(f"Failed to execute AppleScript: {str(e)}") from e
  • The tool is registered via the @mcp.tool() decorator on the FastMCP instance named 'mcp' (line 10).
    @mcp.tool()
  • Input schema using Pydantic Field: takes a single 'script' parameter of type str.
        script: str = Field(description="AppleScript code to execute."),
    ) -> str:
  • Security validation helper called by the handler. Extracts applications from the script, checks against an allowlist (ALLOWED_APPS env var), and detects dangerous patterns (BLOCK_DANGEROUS env var).
    def validate_script(script: str) -> tuple[bool, str, dict]:
        """
        Validate AppleScript for security concerns and allowed apps.
        """
        metadata = {
            "applications": [],
            "dangerous_patterns": [],
            "blocked_by": None,
        }
    
        # Extract applications
        apps = extract_applications(script)
        metadata["applications"] = apps
    
        # Check allowlist
        allowed_apps = get_allowed_apps()
        is_allowed, allowlist_error = check_allowed_apps(apps, allowed_apps)
    
        if not is_allowed:
            metadata["blocked_by"] = "allowlist"
            return False, allowlist_error, metadata
    
        # Check dangerous patterns (if enabled)
        if is_dangerous_blocking_enabled():
            dangerous = detect_dangerous_patterns(script)
            metadata["dangerous_patterns"] = dangerous
    
            if dangerous:
                metadata["blocked_by"] = "dangerous_patterns"
                patterns_list = "\n".join(f"  - {pattern}" for pattern in dangerous)
                error = (
                    f"AppleScript blocked: Dangerous pattern(s) detected:\n"
                    f"{patterns_list}\n\n"
                    "To override, set: BLOCK_DANGEROUS=false"
                )
                return False, error, metadata
    
        return True, "", metadata
  • Helper used by validate_script to extract application names from 'tell application "X"' patterns in the script.
    def extract_applications(script: str) -> list[str]:
        """
        Extract application names from AppleScript.
        """
        pattern = r'tell\s+(?:application|app)\s+"([^"]+)"'
        matches = re.findall(pattern, script, re.IGNORECASE)
        return list(set(app.title() for app in matches))
Behavior3/5

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

Discloses that output is plain text and truncated to 10,000 characters. However, it lacks warnings about potential destructive side effects of executing arbitrary AppleScript commands, which is a significant oversight given no annotations.

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

Conciseness5/5

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

Three concise sentences, front-loaded with the core purpose, and every sentence provides useful information without redundancy.

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

Completeness4/5

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

For a tool with a single parameter and an output schema, the description sufficiently covers usage and output behavior. Missing error handling context, but overall adequate.

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

Parameters4/5

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

The input schema covers the 'script' parameter with a description. The description adds value by providing usage tips for typical AppleScript patterns, going beyond the schema's basic definition.

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

Purpose5/5

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

The description uses a specific verb 'Execute' and resource 'AppleScript commands on macOS', clearly defining the tool's purpose. With only one sibling tool ('status'), there is no ambiguity.

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

Usage Guidelines4/5

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

Provides clear guidance on usage patterns, such as using 'tell application' and support for multi-line scripts. However, it does not specify when not to use the tool or mention alternatives.

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/pietz/mcp-applescript'

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