Skip to main content
Glama
server.cpython-312.pyc59.1 kB
� ���h������ddlZejejd�� ddlZddlZddlZddlZddlmZddl m Z m Z ddl Z ddl Z ddlmZddlmZmZmZmZmZddlmZdd lmZe d d d d gddddd���Ze j0j3e j0j5e j0j5e��d�Zdedefd�Zdedefd�Z ejC�dJdedee"dee defd��Z#ejC�dKdeeedee"defd��Z$ejC�dLdeedeedee"defd��Z%ejC�dMdeedee"deedee"def d ��Z&ejC�dNd!ed"ee"d#ee"dee"def d$��Z'ejC� dKd%ed&eeefd'eedee"def d(��Z(ejC� dOd)ed*ed&eeeeefd+ed,ed'eedee"defd-��Z)d.edefd/�Z*ejC�d.edefd0��Z+ dKd)ed1ed'eedee"def d2�Z,ejC� dKd)ed3ed'eedee"def d4��Z-ejC� dKd)ed1ed3ed5eedee"deeeff d6��Z.ejC� dKd)ed7ed'eedee"def d8��Z/ejC� dKd)ed9ed'eedee"def d:��Z0ejC� dKd)ed7ed9ed5eedee"deeeff d;��Z1dJdedee"dee defd<�Z2ejC� dJdedee"dee defd=��Z3d>�Z4ejkd?�d%edefd@��Z6ejkdA�defdB��Z7ejkdC�defdD��Z8ejs�dEedefdF��Z:ejs�dPdGedHedefdI��Z;y)Q�Nz'%(asctime)s [%(levelname)s] %(message)s)�level�format)�Optional)�FastMCP�Context)�datetime)�Dict�Any�Listr�Union)�asynccontextmanager)� AsyncIteratorzPowerShell Integration Serverz�Secure PowerShell command execution and script generation for Windows system administration, including Intune and BigFix deployment scripts�asyncioz psutil>=5.9.0T)�tools� resources�resourceTemplates�prompts)� description� dependencies� capabilities� templates�code�returnc�j�|j�j�jd�s|�d�}|S)z6Add JSON formatting to PowerShell code if not present.z| convertto-jsonz | ConvertTo-Json)�strip�lower�endswith)rs �/C:\MCP\PowerShell-Exec-MCP-Server\src\server.py�format_json_outputr(s2�� �:�:�<� � � � (� (�);� <���(�)�� �K�c�6��gd�}t�fd�|D�� S)z� Validate PowerShell code for potentially harmful commands. Args: code: The PowerShell code to validate Returns: bool: True if code passes validation ) zrm\s+(-r|-f|/s)*\s*/zformat\s+[a-z]:z Stop-ComputerzRestart-ComputerzRemove-Item.*-RecursezInvoke-Expression�iexz Start-Processz New-Servicez Set-Servicez net\s+userc3�h�K�|])}tj|�tj����+y�w)N)�re�search� IGNORECASE)�.0�patternrs �r� <genexpr>z+validate_powershell_code.<locals>.<genexpr>Fs%�����]�J\�w�2�9�9�W�d�B�M�M�:�J\�s�/2)�any)r�dangerous_patternss` r�validate_powershell_coder,.s"��� ���]�J\�]�]� ]�]r �timeout�ctxc��zK�|r|jd|�d���d{���t|||��d{���S7�7��w)�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 z'Executing PowerShell command (timeout: zs)N)�info�execute_powershell)rr-r.s r�run_powershellr3HsC���� ��h�h�@�� ��L�M�M�M�#�D�'�3�7� 7�7� N�� 7�s�;�7�;�9�;�;� propertiesc��K�d}|rdj|�}|�d|��}tt|�|��d{���S7��w)z�Get system information. Args: properties: List of ComputerInfo properties to retrieve (optional) timeout: Command timeout in seconds (1-300, default 60) zGet-ComputerInfo�,z -Property N)�joinr2r)r4r-r�properties_strs r�get_system_infor9XsH���� �D�����*�-����{�>�"2�3��#�$6�t�$<�g�F� F�F� F�s �5>�<�>�name�statusc���K�d}g}|r|jd|�d��|r|jd|�d��|r|�ddj|��d�}|�d�}tt|�|��d {���S7��w) z�Get information about running services. Args: name: Filter services by name (supports wildcards) status: Filter by status (Running, Stopped, etc.) timeout: Command timeout in seconds (1-300, default 60) z Get-Servicez Name -like '�'z Status -eq 'z | Where-Object { z -and � }z5 | Select-Object Name, DisplayName, Status, StartTypeN)�appendr7r2r)r:r;r-r�filterss r�get_running_servicesrAfs����� �D��G� �����d�V�1�-�.� �����f�X�Q�/�0����*�8�=�=��+A�*B�#�F���V�H� I�D�#�$6�t�$<�g�F� F�F� F�s�A)A2�+A0�,A2�top�sort_byc��K�d}|r|�d|�d�}|r|�d|�d�}|r|�d|��}|�d�}tt|�|��d{���S7��w) aGet information about running processes. Args: name: Filter processes by name (supports wildcards) top: Limit to top N processes sort_by: Property to sort by (e.g., CPU, WorkingSet) timeout: Command timeout in seconds (1-300, default 60) z Get-Processz -Name 'r=z | Sort-Object -Property z -Descendingz | Select-Object -First z5 | Select-Object Name, Id, CPU, WorkingSet, StartTimeN�r2r)r:rBrCr-rs r� get_processesrFzsr���� �D� ���x��v�Q�'�����0�� ��F�� ���/��u�5���V�H� I�D�#�$6�t�$<�g�F� F�F� F�s�=A�A�A�logname�newestrc��vK�d|�d|��}|r|�d|�d�}|�d�}tt|�|��d{���S7��w)aWGet 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) zGet-EventLog -LogName z -Newest z# | Where-Object { $_.EntryType -eq r>z: | Select-Object TimeGenerated, EntryType, Source, MessageNrE)rGrHrr-rs r�get_event_logsrJ�sV����$�G�9�I�f�X� >�D� ���;�E�7�#�F���V�M� N�D�#�$6�t�$<�g�F� F�F� F�s �09�7�9� template_name� parameters� output_pathc��JK�tjjt|�d��}tjj |�st d|�d���t |d�5}|j�}ddd�}tj�jd�|d<|j�D]$\}} |jd|�d �t| ��}�&|r+t |d �5}|j|�ddd�d |��S|S#1swY��xYw#1swY�xYw�w) a�Generate a PowerShell script from a template. Args: template_name: Name of the template to use (without .ps1 extension) parameters: Dictionary of parameters to replace in the template 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 �.ps1z Template z not found�rN�%Y-%m-%d�DATEz{{z}}�w�Script generated and saved to: )�os�pathr7� TEMPLATES_DIR�exists� ValueError�open�readr�now�strftime�items�replace�str�write) rKrLrMr-� template_path�f�template_content�script_content�key�values r�generate_script_from_templaterh�s����$�G�G�L�L��=�/��0F�G�M� �7�7�>�>�-� (��9�]�O�:�>�?�?� �m�S� !�Q��6�6�8�� "�&�N�!����0�0��<�J�v�� �&�&�(� ��U�'�/�/�$�s�e�4�0@�#�e�*�M��)�� �+�s� #�q� �G�G�N� #�$�0�� �>�>� �� "� !��$� #�s7�A"D#�$D �5A5D#�*D�<D#� D�D#�D �D#r� script_type�include_logging�include_error_handlingc �� K�g}|jddd|��dd|��dddtj�jd ���d g �|r�|j d �|D]q}d |j d d��d�} |j d�r | d|d�d�z } | d|d��z } |j d�r | d|d�d�z } |j | dz��s|dj d�|d<|j d�|r|jgd��|r|jgd��|jgd��dj|�} |r+t|d�5} | j| �d d d �d!|��S| S#1swY�xYw�w)"a�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 z<#� .SYNOPSIS� z .DESCRIPTIONz0 Dynamically generated PowerShell script for z.NOTESz& Generated by PowerShell MCP Serverz Date: rQz#>z param (z [Parameter(Mandatory=$� mandatory�falsez)]�typez [�]�$r:�defaultz = "�"r6������)) z! # Function to write log messageszfunction Write-Log {� param (�$ [Parameter(Mandatory=$true)]z [string]$Message,z% [Parameter(Mandatory=$false)]z1 [ValidateSet("INFO", "WARNING", "ERROR")]z [string]$Level = "INFO"� )z7 $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"z/ Write-Host "[$timestamp] [$Level] $Message"�}) z # Function to handle errorszfunction Handle-Error {rxryz> [System.Management.Automation.ErrorRecord]$ErrorRecordrzzW Write-Log -Level ERROR -Message "Error occurred: $($ErrorRecord.Exception.Message)"zQ Write-Log -Level ERROR -Message "Error details: $($ErrorRecord | Out-String)"r{) z # Main executionztry {z, Write-Log "Starting script execution..."rnz6 # TODO: Add script logic here based on descriptionzB # This is where you would add the specific PowerShell commandsz. Write-Log "Script completed successfully."r{zcatch {z Handle-Error -ErrorRecord $_z exit 1r{� rSNrT) �extendrr\r]r?�get�rstripr7rZra) rrirLrjrkrMr-re�param� param_str� final_contentrcs r�generate_custom_scriptr��s�����0�N���� �� �{�m��� :�;�-�H��0� �X�\�\�^�,�,�Z�8�9�:� � � �����k�*��E�4�U�Y�Y�{�G�5T�4U�UW�X�I��y�y�� ��w�u�V�}�o�Q�7�7� � �1�U�6�]�O�,� ,�I��y�y��#��t�E�)�$4�#5�Q�7�7� � � !� !�)�c�/� 2� �,�B�/�6�6�s�;��r�����c�"�����  � � ����  � ���� � ��I�I�n�-�M�� �+�s� #�q� �G�G�M� "�$�0�� �>�>� �� $� #�s�EF�E7�(F�7F�<FrVc�(�|s td��|jd�r|dd}tjj |�s2tjj tj �|�}tjj|�S)zCConvert relative paths to absolute using current working directory.zPath cannot be empty)z./z.\�N)rY� startswithrUrV�isabsr7�getcwd�abspath)rVs r�normalize_pathr�2se�� ��/�0�0� ���|�$��A�B�x�� �7�7�=�=�� ��w�w�|�|�B�I�I�K��.�� �7�7�?�?�4� � r c���t|�}tjj|�dr tjj |�}n|}tj |d��|S)z1Ensure directory exists and return absolute path.�T��exist_ok)r�rUrV�splitext�dirname�makedirs)rV�abs_path�dir_paths r�ensure_directoryr�<sO���d�#�H� �w�w����!�!�$��7�7�?�?�8�,�����K�K��4�(� �Or �detection_logicc��K�d|��|tj�jd�|d�}|r t|�}t d|||��d{���S7��w)u Generate a Microsoft Intune detection script with enterprise-grade compliance checking. Creates a PowerShell detection script that follows Microsoft Intune best practices: - Proper exit codes (0=compliant, 1=non-compliant, 2=error) - Event log integration for monitoring and troubleshooting - Fast execution optimized for frequent compliance checks - Comprehensive error handling and logging - No user interaction (required for Intune deployment) 💡 TIP: For complete Intune compliance, you need BOTH detection and remediation scripts. Consider using 'generate_intune_script_pair' to create both scripts together with matching logic. Microsoft References: - Intune Detection Scripts: https://docs.microsoft.com/en-us/mem/intune/fundamentals/remediations - Best Practices: https://docs.microsoft.com/en-us/mem/intune/fundamentals/remediations-script-samples - PowerShell Requirements: https://docs.microsoft.com/en-us/mem/intune/apps/intune-management-extension - Exit Code Standards: https://docs.microsoft.com/en-us/mem/intune/apps/troubleshoot-mam-app-deployment Args: description: Clear description of what the script should detect (e.g., 'Check if Chrome is installed with correct version', 'Verify Windows firewall is enabled') detection_logic: PowerShell code that performs the compliance check. Use 'Complete-Detection -Compliant $true/$false -Message "status"' to indicate result output_path: Optional file path where the script will be saved. If not provided, returns script content timeout: Command timeout in seconds (1-300, default 60) Returns: Generated script content or path where script was saved Example: Generate a script to detect Chrome installation: ``` result = await generate_intune_detection_script( description="Check if Chrome browser is installed with version 100.0.0.0 or higher", detection_logic=''' try { $app = Get-ItemProperty "HKLM:\Software\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe" -ErrorAction Stop $version = (Get-Item $app.'(Default)').VersionInfo.FileVersion $compliant = [version]$version -ge [version]"100.0.0.0" Complete-Detection -Compliant $compliant -Message "Chrome version: $version (Required: 100.0.0.0+)" } catch { Complete-Detection -Compliant $false -Message "Chrome not found or inaccessible" } ''', output_path="detect_chrome.ps1" ) ``` Tips: - Keep detection logic fast and efficient (runs frequently) - Always use Complete-Detection function to set proper exit codes - Use try-catch blocks for robust error handling - Test detection logic thoroughly in different environments - Use Write-IntuneLog for detailed progress tracking - Avoid making changes in detection scripts (read-only operations) zIntune Detection Script - rQ)�SYNOPSIS� DESCRIPTIONrR�DETECTION_LOGIC�intune_detectionN�rr\r]r�rh)rr�rMr-�paramss r� generate_intune_detection_scriptr�Gs\����z1�� �>�"�� � ��'�'� �3�*� �F��&�{�3� �.�/A�6�;�X_�`� `�`� `���A A� A� A�remediation_logicc��K�d|��|tj�jd�|d�}|r t|�}t d|||��d{���S7��w)u� Generate a Microsoft Intune remediation script with enterprise-grade features. Creates a PowerShell remediation script that follows Microsoft Intune best practices: - Proper exit codes (0=success, 1=failure, 2=error) - Event log integration for monitoring and troubleshooting - System restore point creation before making changes - Comprehensive error handling and logging - No user interaction (required for Intune deployment) ⚠️ IMPORTANT: For complete Intune compliance, you need BOTH detection and remediation scripts. Consider using 'generate_intune_script_pair' instead to create both scripts together. Microsoft References: - Intune Remediation Scripts: https://docs.microsoft.com/en-us/mem/intune/fundamentals/remediations - Best Practices: https://docs.microsoft.com/en-us/mem/intune/fundamentals/remediations-script-samples - PowerShell Script Requirements: https://docs.microsoft.com/en-us/mem/intune/apps/intune-management-extension - Exit Code Standards: https://docs.microsoft.com/en-us/mem/intune/apps/troubleshoot-mam-app-installation#exit-codes Args: description: Clear description of what the script should remediate (e.g., 'Install Chrome browser', 'Configure Windows firewall') remediation_logic: PowerShell code that performs the remediation. Use 'Complete-Remediation -Success $true -Message "description"' to indicate completion output_path: Optional file path where the script will be saved. If not provided, returns script content timeout: Command timeout in seconds (1-300, default 60) Returns: Generated script content or path where script was saved Example: Generate a script to install Chrome: ``` result = await generate_intune_remediation_script( description="Install Chrome browser to latest version", remediation_logic=''' $installer = "$env:TEMP\ChromeSetup.exe" Invoke-WebRequest -Uri "https://dl.google.com/chrome/install/latest/chrome_installer.exe" -OutFile $installer Start-Process -FilePath $installer -Args "/silent /install" -Wait Remove-Item $installer -Force Complete-Remediation -Success $true -Message "Chrome installation completed successfully" ''', output_path="remediate_chrome.ps1" ) ``` Tips: - Always use Complete-Remediation function to set proper exit codes - Test your remediation_logic in a safe environment first - Consider creating a system restore point for major changes - Use Write-IntuneLog for detailed logging and troubleshooting - Ensure no user interaction is required (scripts run silently) zIntune Remediation Script - rQ)r�r�rR�REMEDIATION_LOGIC�intune_remediationNr�)rr�rMr-r�s r�"generate_intune_remediation_scriptr��s\����t3�;�-�@�"�� � ��'�'� �3�.� �F��&�{�3� �.�/C�V�[�Za�b� b�b� b�r�� output_dirc��K�|r�t|�}tjj|d�}tjj|d�}tj|d��t ||||���d{���}t ||||���d{���} n,t |||���d{���}t |||� ��d{���} || d �S7�M7�87�#7��w) a�Generate a complete pair of Microsoft Intune detection and remediation scripts. This is the RECOMMENDED tool for Intune compliance as it creates both required scripts: - Detection script: Checks current system state and determines compliance - Remediation script: Fixes non-compliant conditions with proper safeguards Both scripts follow Microsoft Intune best practices: - Proper exit codes (Detection: 0=compliant, 1=non-compliant, 2=error; Remediation: 0=success, 1=failure, 2=error) - Event log integration for centralized monitoring - System restore points before changes (remediation only) - Comprehensive error handling and logging - No user interaction (silent execution required) Microsoft References: - Intune Remediation Scripts Overview: https://docs.microsoft.com/en-us/mem/intune/fundamentals/remediations - Script Deployment Best Practices: https://docs.microsoft.com/en-us/mem/intune/fundamentals/remediations-script-samples - PowerShell Requirements: https://docs.microsoft.com/en-us/mem/intune/apps/intune-management-extension - Exit Code Standards: https://docs.microsoft.com/en-us/mem/intune/apps/troubleshoot-mam-app-deployment - Monitoring and Reporting: https://docs.microsoft.com/en-us/mem/intune/fundamentals/remediations-monitor Args: description: Clear description of what the scripts should detect and remediate (e.g., 'Ensure Chrome browser is installed with latest version') detection_logic: PowerShell code that performs the compliance check. Use 'Complete-Detection -Compliant $true/$false -Message "status"' to indicate result remediation_logic: PowerShell code that fixes non-compliant conditions. Use 'Complete-Remediation -Success $true/$false -Message "result"' to indicate completion output_dir: Optional directory to save both scripts. If not provided, returns script content in response timeout: Command timeout in seconds (1-300, default 60) Returns: Dictionary containing both scripts: {"detection_script": "content/path", "remediation_script": "content/path"} Example: Generate scripts to manage Chrome browser installation: ``` result = await generate_intune_script_pair( description="Ensure Chrome browser is installed with version 100.0.0.0 or higher", detection_logic=''' try { $app = Get-ItemProperty "HKLM:\Software\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe" -ErrorAction Stop $version = (Get-Item $app.'(Default)').VersionInfo.FileVersion $compliant = [version]$version -ge [version]"100.0.0.0" Complete-Detection -Compliant $compliant -Message "Chrome version: $version (Required: 100.0.0.0+)" } catch { Complete-Detection -Compliant $false -Message "Chrome not found or inaccessible" } ''', remediation_logic=''' try { $installer = "$env:TEMP\ChromeSetup.exe" Write-IntuneLog "Downloading Chrome installer..." Invoke-WebRequest -Uri "https://dl.google.com/chrome/install/latest/chrome_installer.exe" -OutFile $installer -UseBasicParsing Write-IntuneLog "Installing Chrome silently..." Start-Process -FilePath $installer -Args "/silent /install" -Wait Remove-Item $installer -Force Complete-Remediation -Success $true -Message "Chrome installation completed successfully" } catch { Complete-Remediation -Success $false -Message "Chrome installation failed: $($_.Exception.Message)" } ''', output_dir="chrome_intune_scripts" ) ``` Tips: - Always test both scripts in a controlled environment first - Use descriptive logging messages for easier troubleshooting - Consider the impact of remediation actions (e.g., system restarts, user disruption) - Use Write-IntuneLog for detailed progress tracking - Ensure detection logic is fast and efficient (runs frequently) - Make remediation logic idempotent (safe to run multiple times) z detect.ps1z remedy.ps1Tr�)rr�rMr-N)rr�rMr-)rr�r-)rr�r-)�detection_script�remediation_script)r�rUrVr7r�r�r�) rr�r�r�r-�abs_output_dir� detect_path� remedy_path� detect_result� remedy_results r�generate_intune_script_pairr��s�����\�)�*�5���g�g�l�l�>�<�@� ��g�g�l�l�>�<�@� � � � �N�T�2�>�#�+�#��  � � � A�#�/�#��  � � �?�#�+�� � � � A�#�/�� � � �*�+� ��3 ��  �� ��  ��H�A7C�9C�:C�C �C�'C �(C�=C �> C� C� C� C�relevance_logicc��K�d|��|tj�jd�|d�}|r t|�}t d|||��d{���S7��w)u Generate a BigFix relevance script to determine if computers need action. Creates a PowerShell relevance script that follows IBM BigFix best practices: - Proper output format (TRUE/FALSE for BigFix consumption) - BigFix client log integration for monitoring - Event log integration for troubleshooting - Comprehensive error handling and logging - Fast execution optimized for frequent evaluations 💡 TIP: For complete BigFix deployments, you need BOTH relevance and action scripts. Consider using 'generate_bigfix_script_pair' to create both scripts together with matching logic. IBM BigFix References: - Relevance Language Guide: https://help.hcltechsw.com/bigfix/11.0/relevance/Relevance/c_relevance_language.html - Action Scripts: https://help.hcltechsw.com/bigfix/11.0/platform/Platform/Console/c_creating_action_scripts.html - Best Practices: https://help.hcltechsw.com/bigfix/11.0/platform/Platform/Console/c_best_practices_for_creating_fixlets.html - Client Logging: https://help.hcltechsw.com/bigfix/11.0/platform/Platform/Installation/c_bes_client_logging.html Args: description: Clear description of what the script should check (e.g., 'Check if Chrome needs updating', 'Verify Windows patches are current') relevance_logic: PowerShell code that determines relevance. Use 'Complete-Relevance -Relevant $true/$false -Message "status"' to indicate result output_path: Optional file path where the script will be saved. If not provided, returns script content timeout: Command timeout in seconds (1-300, default 60) Returns: Generated script content or path where script was saved Example: Generate a script to check if Chrome needs updating: ``` result = await generate_bigfix_relevance_script( description="Check if Chrome browser needs updating to version 100.0.0.0 or higher", relevance_logic=''', try { $app = Get-ItemProperty "HKLM:\Software\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe" -ErrorAction Stop $version = (Get-Item $app.'(Default)').VersionInfo.FileVersion $needsUpdate = [version]$version -lt [version]"100.0.0.0" Complete-Relevance -Relevant $needsUpdate -Message "Chrome version: $version (Target: 100.0.0.0+)" } catch { Complete-Relevance -Relevant $true -Message "Chrome not found or inaccessible - installation needed" } ''', output_path="chrome_relevance.ps1" ) ``` Tips: - Keep relevance logic fast and efficient (evaluated frequently) - Return TRUE when action is needed, FALSE when compliant - Always use Complete-Relevance function for proper BigFix output format - Use try-catch blocks for robust error handling - Test relevance logic thoroughly across different environments - Use Write-BigFixLog for detailed progress tracking zBigFix Relevance Script - rQ)r�r�rR�RELEVANCE_LOGIC�bigfix_relevanceNr�)rr�rMr-r�s r� generate_bigfix_relevance_scriptr�Ks\����|1�� �>�"�� � ��'�'� �3�*� �F��&�{�3� �.�/A�6�;�X_�`� `�`� `�r�� action_logicc��K�d|��|tj�jd�|d�}|r t|�}t d|||��d{���S7��w)u Generate a BigFix action script to perform remediation or configuration changes. Creates a PowerShell action script that follows IBM BigFix best practices: - Proper exit codes (0=success, 1=retryable failure, 2=non-retryable failure) - BigFix client log integration for monitoring - System restore point creation before changes - Comprehensive error handling and logging - Event log integration for troubleshooting ⚠️ IMPORTANT: For complete BigFix deployments, you need BOTH relevance and action scripts. Consider using 'generate_bigfix_script_pair' instead to create both scripts together. IBM BigFix References: - Action Scripts: https://help.hcltechsw.com/bigfix/11.0/platform/Platform/Console/c_creating_action_scripts.html - Exit Codes: https://help.hcltechsw.com/bigfix/11.0/platform/Platform/Console/c_action_script_exit_codes.html - Best Practices: https://help.hcltechsw.com/bigfix/11.0/platform/Platform/Console/c_best_practices_for_creating_fixlets.html - Client Logging: https://help.hcltechsw.com/bigfix/11.0/platform/Platform/Installation/c_bes_client_logging.html Args: description: Clear description of what the script should accomplish (e.g., 'Install Chrome browser', 'Configure Windows firewall') action_logic: PowerShell code that performs the action. Use 'Complete-Action -Result "Success/RetryableFailure/NonRetryableFailure" -Message "details"' to indicate completion output_path: Optional file path where the script will be saved. If not provided, returns script content timeout: Command timeout in seconds (1-300, default 60) Returns: Generated script content or path where script was saved Example: Generate a script to install Chrome: ``` result = await generate_bigfix_action_script( description="Install Chrome browser to latest version", action_logic=''' try { $installer = "$env:TEMP\ChromeSetup.exe" Write-BigFixLog "Downloading Chrome installer..." Invoke-WebRequest -Uri "https://dl.google.com/chrome/install/latest/chrome_installer.exe" -OutFile $installer -UseBasicParsing Write-BigFixLog "Installing Chrome silently..." Start-Process -FilePath $installer -Args "/silent /install" -Wait Remove-Item $installer -Force Complete-Action -Result "Success" -Message "Chrome installation completed successfully" } catch { Complete-Action -Result "RetryableFailure" -Message "Chrome installation failed: $($_.Exception.Message)" } ''', output_path="chrome_action.ps1" ) ``` Tips: - Always use Complete-Action function to set proper exit codes - Use "Success" for completed actions - Use "RetryableFailure" for temporary issues (network, locks, etc.) - Use "NonRetryableFailure" for permanent issues (unsupported OS, etc.) - Test action logic in safe environments first - Consider creating system restore points for major changes - Use Write-BigFixLog for detailed logging and troubleshooting - Make actions idempotent (safe to run multiple times) zBigFix Action Script - rQ)r�r�rR� ACTION_LOGIC� bigfix_actionNr�)rr�rMr-r�s r�generate_bigfix_action_scriptr��s[����F.�k�]�;�"�� � ��'�'� �3�$� �F��&�{�3� �.��� �U\�]� ]�]� ]�r�c��K�|r�t|�}tjj|d�}tjj|d�}tj|d��t ||||���d{���}t ||||���d{���} n,t |||���d{���}t |||� ��d{���} || d �S7�M7�87�#7��w) a\Generate a complete pair of BigFix relevance and action scripts for deployment. This is the RECOMMENDED tool for BigFix fixlet creation as it creates both required scripts: - Relevance script: Determines which computers need the action (TRUE/FALSE output) - Action script: Performs the necessary changes with proper error handling Both scripts follow IBM BigFix best practices: - Proper BigFix output formats and exit codes - BigFix client log integration for centralized monitoring - System restore points before changes (action only) - Comprehensive error handling and logging - Event log integration for troubleshooting - No user interaction (silent execution required) IBM BigFix References: - Fixlet Development: https://help.hcltechsw.com/bigfix/11.0/platform/Platform/Console/c_creating_fixlets.html - Relevance Language: https://help.hcltechsw.com/bigfix/11.0/relevance/Relevance/c_relevance_language.html - Action Scripts: https://help.hcltechsw.com/bigfix/11.0/platform/Platform/Console/c_creating_action_scripts.html - Best Practices: https://help.hcltechsw.com/bigfix/11.0/platform/Platform/Console/c_best_practices_for_creating_fixlets.html - Testing Guidelines: https://help.hcltechsw.com/bigfix/11.0/platform/Platform/Console/c_testing_fixlets.html Args: description: Clear description of what the scripts should accomplish (e.g., 'Manage Chrome browser installation and updates') relevance_logic: PowerShell code that determines if action is needed. Use 'Complete-Relevance -Relevant $true/$false -Message "status"' to indicate result action_logic: PowerShell code that performs the remediation. Use 'Complete-Action -Result "Success/RetryableFailure/NonRetryableFailure" -Message "details"' to indicate completion output_dir: Optional directory to save both scripts. If not provided, returns script content in response timeout: Command timeout in seconds (1-300, default 60) Returns: Dictionary containing both scripts: {"relevance_script": "content/path", "action_script": "content/path"} Example: Generate scripts to manage Chrome browser installation: ``` result = await generate_bigfix_script_pair( description="Manage Chrome browser installation with version 100.0.0.0 or higher", relevance_logic=''', try { $app = Get-ItemProperty "HKLM:\Software\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe" -ErrorAction Stop $version = (Get-Item $app.'(Default)').VersionInfo.FileVersion $needsAction = [version]$version -lt [version]"100.0.0.0" Complete-Relevance -Relevant $needsAction -Message "Chrome version: $version (Target: 100.0.0.0+)" } catch { Complete-Relevance -Relevant $true -Message "Chrome not found - installation needed" } ''', action_logic=''', try { $installer = "$env:TEMP\ChromeSetup.exe" Write-BigFixLog "Downloading Chrome installer..." Invoke-WebRequest -Uri "https://dl.google.com/chrome/install/latest/chrome_installer.exe" -OutFile $installer -UseBasicParsing Write-BigFixLog "Installing Chrome silently..." Start-Process -FilePath $installer -Args "/silent /install" -Wait Remove-Item $installer -Force Complete-Action -Result "Success" -Message "Chrome installation completed successfully" } catch { Complete-Action -Result "RetryableFailure" -Message "Chrome installation failed: $($_.Exception.Message)" } ''', output_dir="chrome_bigfix_scripts" ) ``` Tips: - Always test both scripts in a controlled environment first - Ensure relevance logic matches the conditions that action script addresses - Use descriptive logging messages for easier troubleshooting - Consider the scope and impact of actions (test groups first) - Make sure relevance logic is efficient (evaluated frequently) - Ensure action logic is idempotent (safe to run multiple times) - Use Write-BigFixLog for detailed progress tracking - Test across different OS versions and configurations z relevance.ps1z action.ps1Tr�)rr�rMr-N)rr�rMr-)rr�r-)rr�r-)�relevance_script� action_script)r�rUrVr7r�r�r�) rr�r�r�r-r��relevance_path� action_path�relevance_result� action_results r�generate_bigfix_script_pairr��s�����b�)�*�5�������n�o�F���g�g�l�l�>�<�@� � � � �N�T�2�!A�#�+�&�� " � �� <�#�%�#��  � � �"B�#�+��" � �� <�#�%�� � � �-�&� ��3 ��  �� ��  �r�c ���K�t|t�r |dks|dkDr td��t|�s td��|r|j d��d{���|r|j d��d{���t j dd d d |tjtj� ��d{���} |r|j d ��d{���t j|j�|���d{���\}}|jdk7r=|r|j�nd}|r|jd|����d{���t!|��|r|j�nd}|r&|j dt#|��d���d{���|S7��67��7��7��7��#t j$r@|j�|r|jd|�d���d{���7td|�d���wxYw7��7�j�w)r0r��,�)timeout must be between 1 and 300 seconds�7PowerShell code contains potentially dangerous commandszValidating PowerShell code...NzStarting PowerShell process...� powershell� -NoProfile�-NonInteractive�-Command��stdout�stderrzExecuting command...�r-�Command timed out after � secondsr�#Command failed with no error outputzPowerShell command failed: �z)Command completed successfully, returned � characters)� isinstance�intrYr,r1r�create_subprocess_exec� subprocess�PIPE�wait_for� communicate� TimeoutError�kill�error� returncode�decode� RuntimeError�len)rr-r.�processr�r�� error_msg�results rr2r2\s����� �g�s� #�w��{�g��m��D�E�E� $�D� )��R�S�S� ��h�h�6�7�7�7� ��h�h�7�8�8�8��2�2����� ���������G� I� ��(�(�1�2� 2� 2�&�/�/� � � � !�� � �������Q��'-�F�M�M�O�3X� � ��)�)�9�)��E�F� F� F��9�%�%� &�V�]�]�_�B�F� ��h�h�B�3�v�;�-�{�[�\�\�\� �M�O 8�� 9���� 3�� �� � � �I�� � �� ��)�)�6�w�i�x�H�I� I� I��5�g�Y�h�G�H�H� I�� G�� ]�s��AG0�F �G0�/F �0?G0�/F�0G0�5F� F� ,F�8F�9F�<G0�<G,�=AG0�G.�G0� G0�G0�F�F�=G)�G�G)�)G0�.G0c ��jK�|st||��d{���Stj�} |jd��d{���t |t �r |dks|dkDr$|j d��d{���td��t|�s$|j d��d{���td��|jd ��d{���|jd ��d{���|jd d d ��d{���tjdddd|tjtj���d{���}|jdd d��d{��� tj|j�|���d{���\}}|jdd d��d{���|j$d k7r;|r|j'�nd}|j d|����d{���t)|��|r|j'�nd}tj�} | |z j+�} |jd d d��d{���|jd| d�d���d{���|jd t-|��d!���d{���| t-|�|j$| j/�d"�} |j1�rd#|�d$t3j4| d%�&���Sd't3j4| d%�&���S7���7���7���7��`7��?7��)7��7���7���7���7��v#tj $r>|j#�|j d|�d���d{���7t!d|�d���wxYw7���7��07��7��#t6$r,} |j d(t9| �����d{���7�d} ~ wwxYw�w))a@Execute PowerShell commands with detailed progress reporting. 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 with execution details Nu"🔍 Validating PowerShell code...r�r�u❌ Invalid timeout valuer�u;❌ PowerShell code contains potentially dangerous commandsr�u✅ Code validation passedu%🚀 Starting PowerShell execution...r�zInitializing PowerShell processr�r�r�r�r�z"Process created, executing commandr��zCommand execution completedu⏰ Command timed out after r�r�r�u❌ PowerShell command failed: r�zProcessing resultsu&✅ Command completed successfully in z.2fu📊 Output size: r�)�execution_time_seconds� output_length� exit_code� timestampz--- PowerShell Output --- z --- Execution Metadata --- r���indentz6--- No Output Produced --- --- Execution Metadata --- u❌ Execution failed: )r2rr\r1r�r�r�rYr,�report_progressrr�r�r�r�r�r�r�r�r�r�� total_secondsr�� isoformatr�json�dumps� Exceptionr`) rr-r.� start_timer�r�r�r�r��end_time�execution_time�metadata�es r�run_powershell_with_progressr��s����� �'��g�6�6�6�����J�I��h�h�;�<�<�<��'�3�'�7�Q�;�'�C�-��)�)�7�8� 8� 8��H�I� I�(��-��)�)�Y�Z� Z� Z��V�W� W��h�h�3�4�4�4��h�h�>�?�?�?��!�!�!�Q�(I�J�J�J� �6�6� � � � � ��?�?��?�?� � ���!�!�!�Q�(L�M�M�M� M�#*�#3�#3��#�#�%��$��N�F�F��%�%�a��,I�J� J� J� � � �� "�+1�� � ��7\�I��)�)�=�i�[�I�J� J� J��y�)� )�$*��������<�<�>��"�Z�/�>�>�@���!�!�!�Q�(<�=�=�=��h�h�?��s�?S�S[�\�]�]�]��h�h�+�C��K�=� �D�E�E�E�'5� ��[� �+�+�!�+�+�-�  �� �<�<�>�0���8V�W[�Wa�Wa�bj�st�Wu�Vv�w� w�M�d�j�j�Ya�jk�Nl�Mm�n� n�S7�� =�� 9�� [�� 5��?�� K�� �� N���� K���#�#� M� �L�L�N��)�)�:�7�)�8�L�M� M� M��!9�'��(�K�L� L� M�� K�� >��]��E�� ���i�i�0��Q���9�:�:�:� ���sf�N3�K;�N3�M;�K>�2M;�5L�6.M;�$L�%#M;�L� M;�!L �"M;�<L �=?M;�<L�=M;�L�M;�(L�L�L�#L�$L�(:M;�"M0�#A M;�M3�M;�!M6�"%M;�M9�AM;� N3�!M;�:N3�>M;�M;�M;�M;� M;� M;�M;�M;�L�L�;M-�M�M-�-M;�3M;�6M;�9M;�; N0� N+�$N'�%N+�+N0�0N3c���td�td�td�td�td�td�td�td�td �td�td �td�td �td �td�td �td�td�td�td�td�td�td�td�td�td�td�td�td�td�td�td�td�y)z+Log available tools and their descriptions.z Available PowerShell Tools:z---------------------------zrun_powershell:z3 Description: Execute PowerShell commands securelyz Parameters:z/ - code (string): PowerShell code to executezM - timeout (int, optional): Command timeout in seconds (1-300, default 60)z get_system_info:z< Description: Get system information using Get-ComputerInfozA - properties (list, optional): List of properties to retrievez get_running_services:z5 Description: Get information about Windows serviceszL - name (string, optional): Filter services by name (wildcards supported)z1 - status (string, optional): Filter by statusz get_processes:z( Description: Monitor running processesz7 - name (string, optional): Filter processes by namez3 - top (int, optional): Limit to top N processesz5 - sort_by (string, optional): Property to sort byz get_event_logs:z( Description: Access Windows event logsz7 - logname (string): Name of the event log to accesszA - newest (int, optional): Number of recent events to retrievez/ - level (int, optional): Event level filterz--------------------------- N)�print�r r� log_toolsr��s&�� � )�*� � '�(� � �� � ?�@� �/�� � ;�<� � Y�Z� � �� � H�I� �/�� � M�N� � Y�Z� � #�$� � A�B� �/�� � X�Y� � =�>� � Y�Z� � �� � 4�5� �/�� � C�D� � ?�@� � A�B� � Y�Z� � �� � 4�5� �/�� � C�D� � M�N� � ;�<� � Y�Z� � )�*r ztemplate://{template_name}c��tjjt|�d��}tjj |�st d|�d���t |dd��5}|j�cddd�S#1swYyxYw)z)Get a PowerShell script template by name.rOz Template 'z ' not foundrP�utf-8��encodingN)rUrVr7rWrXrYrZr[)rKrbrcs r�get_powershell_templater$sf���G�G�L�L��=�/��0F�G�M� �7�7�>�>�-� (��:�m�_�K�@�A�A� �m�S�7� 3�q��v�v�x� 4� 3� 3�s �$A>�>Bztemplates://listc ���tjjt�st j gdd��Sg}tj t�D�]0}|jd�s�|dd}tjjt|�} t|dd��5}|j�dd }d }|D]�}|j�jd �s�#||j|�d zdD]d}|j�s�|j�jd �r�4|j�jd�r�T|j�}nn|j||xsd|��d|��d��ddd���3t j d|id��S#1swY�%xYw#t$r0} |j|dt!| ��d�d|��d��Yd} ~ ���d} ~ wwxYw)z(List all available PowerShell templates.zTemplates directory not found)r�messagerON�����rPr�r�� r�rmr��#�.zPowerShell template: z template://)r:rrVzTemplate file (error reading: rwrr�r�)rUrVrXrWr�r��listdirrr7rZ� readlinesrr��indexr?r�r`) r�filerKrbrc� first_linesr�line� desc_liner�s r�list_templatesr.s��� �7�7�>�>�-� (��z�z��7V�W�X�X��I�� � �=�)�� �=�=�� � ��"�I�M��G�G�L�L���=�M� ��-��w�?�1�"#�+�+�-���"4�K�"$�K� +���:�:�<�2�2�;�?�-8��9J�9J�4�9P�QR�9R�9S�-T� �#,�?�?�#4�Y�_�_�=N�=Y�=Y�Z]�=^�gp�gv�gv�gx�hD�hD�EH�hI�2;�/�/�2C�K�$)�.U�"�!,��$�$� -�'2�']�8M�m�_�6]�"-�m�_� =�&��@�� *�: �:�:�{�I�.�q� 9�9�1@�?��"� �� � �)�%C�C��F�8�1�#M�)�-��9�"���� �sH�F0�%:F$� *F$� F$�+F$� 5F$�F0�$F- �)F0�0 G)�9%G$�$G)z system://infoc�.�ddl} ddl}|j�|j�|j �|j �|j �|j�d�t|j�jdz d�t|j�jdz d�|j�jd�tjdk7r(t|jd�jdz d�n't|jd �jdz d�tjdk7r(t|jd�j dz d�n't|jd �j dz d�d �|j#�|j%d � �d �t'j(�j+�d�}t-j.|d��S#t0$r�|j�|j�|j �|j �|j �|j�d�t'j(�j+�dd�}t-j.|d��cYSwxYw)z+Get basic system information as a resource.rN)�system�release�version�machine� processor�nodei@r�)�total_gb� available_gb� percent_used�nt�/zC:\)r�free_gbr�)�interval)�cores�percent)�platform�memory�disk�cpur�r�z*Install psutil for detailed system metrics)rr��note)r�psutilrrrrrr�round�virtual_memory�total� availablerrUr:� disk_usage�free� cpu_count� cpu_percentrr\r�r�r�� ImportError)rr$� system_infos r�get_system_info_resourcer/Tsx���)1��#�/�/�+�#�+�+�-�#�+�+�-�#�+�+�-�%�/�/�1� � � �� �"�&�"7�"7�"9�"?�"?�7�"K�Q�O� %�f�&;�&;�&=�&G�&G�7�&S�UV� W� &� 5� 5� 7� ?� ?�� SU�RY�RY�]a�Ra�E�&�"3�"3�C�"8�">�">�'�"J�A�N�gl�ms�m~�m~�@F�nG�nM�nM�QX�nY�[\�h]�PR�PW�PW�[_�P_�5��!2�!2�3�!7�!<�!<��!H�!�L�ej�kq�k|�k|�~D�lE�lJ�lJ�NU�lV�XY�fZ��  �)�)�+�!�-�-�q�-�9��"����1�1�3�- � �0�z�z�+�a�0�0�� �1�#�/�/�+�#�+�+�-�#�+�+�-�#�+�+�-�%�/�/�1� � � �� �"����1�1�3�@�  � ��z�z�+�a�0�0�1�s�G)G0�0B!J�J�script_purposec��d|�d|�d�S)z7Generate a prompt for PowerShell script best practices.z0 Please help me create a PowerShell script for: a� Please ensure the script follows these best practices: 1. **Error Handling**: Include proper try-catch blocks and error handling 2. **Parameter Validation**: Use proper parameter validation and help text 3. **Logging**: Include informative Write-Host or Write-Output statements 4. **Security**: Avoid dangerous commands and validate inputs 5. **Documentation**: Include proper comment-based help with .SYNOPSIS, .DESCRIPTION, .PARAMETER, and .EXAMPLE 6. **Performance**: Use efficient PowerShell cmdlets and avoid unnecessary loops 7. **Compatibility**: Consider Windows PowerShell vs PowerShell Core compatibility Template structure: ```powershell <# .SYNOPSIS Brief description .DESCRIPTION Detailed description .PARAMETER ParameterName Description of parameter .EXAMPLE Example usage .NOTES Additional notes #> param( [Parameter(Mandatory=$true)] [string]$RequiredParam ) try { # Main script logic here Write-Host "Starting a!..." # Your implementation Write-Host "Completed successfully" } catch { Write-Error "Error occurred: $($_.Exception.Message)" exit 1 } ``` Please provide a complete PowerShell script that implements the requested functionality while following these guidelines. r�)r0s r�powershell_best_practicesr2�s,��0�0>�/?�&@�L)�)� *�O4 �4r � error_message�script_contextc�$�|rd|��nd}d|�|�d�S)z8Generate a prompt for troubleshooting PowerShell errors.z Script context: r�zW I'm encountering a PowerShell error and need help troubleshooting it. Error message: a� Please help me: 1. **Identify the root cause** of this error 2. **Provide specific solutions** to fix the issue 3. **Suggest preventive measures** to avoid similar errors in the future 4. **Recommend best practices** for the type of operation that's failing Please provide: - Clear explanation of what's causing the error - Step-by-step solution with corrected PowerShell code - Alternative approaches if applicable - Testing steps to verify the fix works If you need more information to provide a complete solution, please ask specific questions about: - PowerShell version being used - Operating system and version - Security context (admin privileges, execution policy) - Input data or parameters being used - Expected vs actual behavior r�)r3r4�context_sections r�troubleshoot_powershell_errorr7�s9��CQ�-�n�-=�>�VX�O����� �!�  �r )�<N)Nr8)NNr8)NNNr8)rNr8)NTTNr8)r�)<�logging� basicConfig�INFOr$�sysrr��typingr�mcp.server.fastmcprrrUr�rr r r r � contextlibr �collections.abcr�mcprVr7r��__file__rWr`r�boolr,�toolr�r3r9rArFrJrhr�r�r�r�r�r�r�r�r�r2r�r��resourcerrr/�promptr2r7r�r r�<module>rGsb������� �,�,� 4��� � ����/� � ��3�3�*�)��#�^��_�-���!�� � ����� � �R�W�W�_�_�R�W�W�_�_�X�-F�G��U� ��S��S�� ^�3�^�4�^�4���� 8�s� 8�X�c�]� 8�h�w�FW� 8�cf� 8� � 8����� G�h�t�C�y�&9� G�8�TW�=� G�be� G� � G�����G�X�c�]�G�8�C�=�G�bj�kn�bo�G�y|�G� �G�&����G�h�s�m�G��#��G�X`�ad�Xe�G�w�AD�xE�G�OR�G� �G�&���� G�#� G�x��}� G�(�SV�-� G�iq�ru�iv� G�AD� G� � G�����"&�� $��$��S�#�X��$��#��$��c�]� $�  � $� �$�L����26� �#'�!%��j��j��j���d�3��8�n�-�.�j�� j� !� j� �#�� j��c�]�j� �j� �j�X!��!��!������3��3�� ��"&�� Fa��Fa��Fa��#��Fa��c�]� Fa�  � Fa�P����"&�� Bc��Bc��Bc��#��Bc��c�]� Bc�  � Bc� �Bc�H���� !%�� t��t��t��t��� � t� �c�]� t�  �#�s�(�^� t� �t�l����"&�� Fa��Fa��Fa��#��Fa��c�]� Fa�  � Fa� �Fa�P����"&�� K^��K^��K^��#��K^��c�]� K^�  � K^� �K^�Z���� !%�� w��w��w��w��� � w� �c�]� w�  �#�s�(�^� w� �w�r;�3�;��#��;�(�SZ�J[�;�gj�;�z���� �!�^� �^� �c�]�^� �'� �^� � ^� �^�@'+�T���*�+��3��3��,����� �!�#:��#:�"�#:�J���o��-1�#�-1��-1�`����6�c�6�c�6��6�p�������c��SV���r

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