Skip to main content
Glama
DynamicEndpoints

PowerShell Exec MCP Server

generate_custom_script

Create PowerShell scripts from natural language descriptions for enterprise automation, system monitoring, and management tasks in Microsoft Intune and IBM BigFix environments.

Instructions

Generate a custom PowerShell script based on description.

Args:
    description: Natural language description of what the script should do
    script_type: Type of script to generate (file_ops, service_mgmt, etc.)
    parameters: List of parameters the script should accept
    include_logging: Whether to include logging functions
    include_error_handling: Whether to include error handling
    output_path: Where to save the generated script (optional)
    timeout: Command timeout in seconds (1-300, default 60)
    
Returns:
    Generated script content or path where script was saved

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
descriptionYes
script_typeYes
parametersNo
include_loggingNo
include_error_handlingNo
output_pathNo
timeoutNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The primary handler function for the 'generate_custom_script' tool. Decorated with @mcp.tool(), it generates a custom PowerShell script based on a natural language description, script type, parameters, and options for logging and error handling. Builds the script content programmatically and optionally saves it to a file.
    @mcp.tool()
    async def generate_custom_script(
        description: str,
        script_type: str,
        parameters: Optional[List[Dict[str, Any]]] = None,
        include_logging: bool = True,
        include_error_handling: bool = True,
        output_path: Optional[str] = None,
        timeout: Optional[int] = 60
    ) -> str:
        """Generate a custom PowerShell script based on description.
        
        Args:
            description: Natural language description of what the script should do
            script_type: Type of script to generate (file_ops, service_mgmt, etc.)
            parameters: List of parameters the script should accept
            include_logging: Whether to include logging functions
            include_error_handling: Whether to include error handling
            output_path: Where to save the generated script (optional)
            timeout: Command timeout in seconds (1-300, default 60)
            
        Returns:
            Generated script content or path where script was saved
        """
        script_content = []
        
        # Add help comment block
        script_content.extend([
            '<#',
            '.SYNOPSIS',
            f'    {description}',
            '.DESCRIPTION',
            f'    Dynamically generated PowerShell script for {script_type}',
            '.NOTES',
            '    Generated by PowerShell MCP Server',
            f'    Date: {datetime.now().strftime("%Y-%m-%d")}',
            '#>'
        ])
        
        # Add parameters
        if parameters:
            script_content.append('\nparam (')
            for param in parameters:
                param_str = f'    [Parameter(Mandatory=${param.get("mandatory", "false")})]'
                if param.get('type'):
                    param_str += f'\n    [{param["type"]}]'
                param_str += f'${param["name"]}'
                if param.get('default'):
                    param_str += f' = "{param["default"]}"'
                script_content.append(param_str + ',')
            script_content[-1] = script_content[-1].rstrip(',')  # Remove trailing comma
            script_content.append(')')
        
        # Add logging function
        if include_logging:
            script_content.extend([
                '\n# Function to write log messages',
                'function Write-Log {',
                '    param (',
                '        [Parameter(Mandatory=$true)]',
                '        [string]$Message,',
                '        [Parameter(Mandatory=$false)]',
                '        [ValidateSet("INFO", "WARNING", "ERROR")]',
                '        [string]$Level = "INFO"',
                '    )',
                '    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"',
                '    Write-Host "[$timestamp] [$Level] $Message"',
                '}'
            ])
        
        # Add error handling
        if include_error_handling:
            script_content.extend([
                '\n# Function to handle errors',
                'function Handle-Error {',
                '    param (',
                '        [Parameter(Mandatory=$true)]',
                '        [System.Management.Automation.ErrorRecord]$ErrorRecord',
                '    )',
                '    Write-Log -Level ERROR -Message "Error occurred: $($ErrorRecord.Exception.Message)"',
                '    Write-Log -Level ERROR -Message "Error details: $($ErrorRecord | Out-String)"',
                '}'
            ])
        
        # Add main script block
        script_content.extend([
            '\n# Main execution',
            'try {',
            '    Write-Log "Starting script execution..."',
            '    ',
            '    # TODO: Add script logic here based on description',
            '    # This is where you would add the specific PowerShell commands',
            '    Write-Log "Script completed successfully."',
            '}',
            'catch {',
            '    Handle-Error -ErrorRecord $_',
            '    exit 1',
            '}'
        ])
        
        final_content = '\n'.join(script_content)
        
        if output_path:
            with open(output_path, 'w') as f:
                f.write(final_content)
            return f"Script generated and saved to: {output_path}"
        
        return final_content
Behavior2/5

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

With no annotations provided, the description carries full burden but offers minimal behavioral insight. It mentions the tool 'generates' a script and optionally saves it, but doesn't disclose critical traits like whether it's read-only/destructive, authentication needs, rate limits, error behavior, or how it handles invalid inputs. For a generative tool with zero annotation coverage, this is inadequate.

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

Conciseness3/5

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

The description is structured with a purpose statement followed by parameter explanations, but it's verbose with repetitive formatting. Sentences like 'Args:' and 'Returns:' are redundant with the schema. While informative, it could be more streamlined by focusing on value-added details rather than restating obvious parameter names.

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 7 parameters, no annotations, and an output schema (which covers return values), the description is moderately complete. It explains parameters but misses behavioral context (e.g., generation limits, error handling). The output schema reduces the need to detail returns, but the description should still address usage scenarios and constraints for a generative tool.

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?

Schema description coverage is 0%, so the description must compensate. It lists all 7 parameters with brief explanations (e.g., 'Natural language description of what the script should do'), adding meaningful context beyond the bare schema. However, it lacks details on 'script_type' values (e.g., what 'file_ops' entails) or 'parameters' structure, preventing a perfect score.

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: 'Generate a custom PowerShell script based on description.' It specifies the verb ('generate'), resource ('custom PowerShell script'), and mechanism ('based on description'). However, it doesn't explicitly differentiate from sibling tools like 'generate_script_from_template' or 'run_powershell', which would require a 5.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention sibling tools like 'generate_script_from_template' (for template-based generation) or 'run_powershell' (for executing scripts), nor does it specify prerequisites or exclusions. This leaves the agent without context for tool selection.

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/DynamicEndpoints/PowerShell-Exec-MCP-Server'

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