Skip to main content
Glama
DynamicEndpoints

PowerShell Exec MCP Server

get_event_logs

Retrieve Windows event logs from System, Application, or Security sources with filtering by level and recency for monitoring and troubleshooting.

Instructions

Get Windows event logs.

Args:
    logname: Name of the event log (System, Application, Security, etc.)
    newest: Number of most recent events to retrieve (default 10)
    level: Filter by event level (1: Critical, 2: Error, 3: Warning, 4: Information)
    timeout: Command timeout in seconds (1-300, default 60)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
lognameYes
newestNo
levelNo
timeoutNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The handler function for the 'get_event_logs' MCP tool. It constructs a PowerShell command using Get-EventLog with optional filtering by newest events and level, selects key fields, formats output as JSON, and executes it securely with timeout.
    @mcp.tool()
    async def get_event_logs(logname: str, newest: Optional[int] = 10, level: Optional[int] = None, timeout: Optional[int] = 60) -> str:
        """Get Windows event logs.
        
        Args:
            logname: Name of the event log (System, Application, Security, etc.)
            newest: Number of most recent events to retrieve (default 10)
            level: Filter by event level (1: Critical, 2: Error, 3: Warning, 4: Information)
            timeout: Command timeout in seconds (1-300, default 60)
        """
        code = f"Get-EventLog -LogName {logname} -Newest {newest}"
        if level:
            code = f"{code} | Where-Object {{ $_.EntryType -eq {level} }}"
        code = f"{code} | Select-Object TimeGenerated, EntryType, Source, Message"
        return await execute_powershell(format_json_output(code), timeout)
  • src/server.py:132-132 (registration)
    The @mcp.tool() decorator registers the get_event_logs function as an MCP tool in the FastMCP server instance.
    @mcp.tool()
  • Helper function to ensure PowerShell output is formatted as JSON by appending '| ConvertTo-Json' if missing.
    def format_json_output(code: str) -> str:
        """Add JSON formatting to PowerShell code if not present."""
        if not code.strip().lower().endswith('| convertto-json'):
            code = f"{code} | ConvertTo-Json"
        return code
  • Core helper function that executes the constructed PowerShell code securely, with code validation against dangerous patterns, timeout enforcement, and proper error handling.
    async def execute_powershell(code: str, timeout: Optional[int] = 60, ctx: Optional[Context] = None) -> str:
        """Execute PowerShell commands securely.
        
        Args:
            code: PowerShell code to execute
            timeout: Command timeout in seconds (1-300, default 60)
            ctx: MCP context for logging and progress reporting
        
        Returns:
            Command output as string
        """
        # Validate timeout
        if not isinstance(timeout, int) or timeout < 1 or timeout > 300:
            raise ValueError("timeout must be between 1 and 300 seconds")
            
        # Validate code
        if not validate_powershell_code(code):
            raise ValueError("PowerShell code contains potentially dangerous commands")
    
        if ctx:
            await ctx.info("Validating PowerShell code...")
    
        # Create and run process
        if ctx:
            await ctx.info("Starting PowerShell process...")
        
        process = await asyncio.create_subprocess_exec(
            "powershell",
            "-NoProfile",      # Don't load profiles
            "-NonInteractive", # No interactive prompts
            "-Command",
            code,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE
        )
    
        try:
            if ctx:
                await ctx.info("Executing command...")
            stdout, stderr = await asyncio.wait_for(
                process.communicate(),
                timeout=timeout
            )
        except asyncio.TimeoutError:
            process.kill()
            if ctx:
                await ctx.error(f"Command timed out after {timeout} seconds")
            raise TimeoutError(f"Command timed out after {timeout} seconds")
    
        if process.returncode != 0:
            error_msg = stderr.decode() if stderr else "Command failed with no error output"
            if ctx:
                await ctx.error(f"PowerShell command failed: {error_msg}")
            raise RuntimeError(error_msg)
        
        result = stdout.decode() if stdout else ""
        if ctx:
            await ctx.info(f"Command completed successfully, returned {len(result)} characters")
            
        return result
Behavior2/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 mentions a timeout parameter which hints at potential execution constraints, but doesn't describe what happens on timeout, error conditions, permission requirements, rate limits, or the format/structure of returned logs. The description states it 'gets' logs but doesn't clarify if this is a read-only operation or has any side effects.

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 efficiently structured with a clear purpose statement followed by well-organized parameter documentation. Each parameter explanation is concise yet informative. The formatting with 'Args:' header and bullet-like parameter explanations makes it scannable, though it could be slightly more polished in presentation.

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 that there's an output schema (though not shown), the description doesn't need to explain return values. However, for a tool with 4 parameters, no annotations, and system-level access to event logs, the description should provide more behavioral context about permissions, error handling, and typical use cases. The parameter documentation is excellent, but overall context about the tool's operation is minimal.

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

Parameters5/5

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

The description adds significant value beyond the input schema, which has 0% description coverage. It provides clear explanations for all 4 parameters: logname examples (System, Application, Security), newest default and meaning, level mapping (1: Critical, etc.), and timeout range with default. This fully compensates for the schema's lack of descriptions and provides essential semantic context.

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: 'Get Windows event logs' specifies the verb (get) and resource (Windows event logs). It distinguishes from siblings like get_processes or get_system_info by focusing specifically on event logs. However, it doesn't explicitly differentiate from potential similar logging tools that might exist in other contexts.

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?

No guidance is provided on when to use this tool versus alternatives. The description doesn't mention any prerequisites, dependencies, or specific use cases. While the sibling tools are mostly script generation or system monitoring tools, there's no explicit comparison or context for choosing this tool over others.

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