Skip to main content
Glama
server.cpython-313.pyc58 kB
� /�Th����@�SSKr\R"\RSS9 SSKrSSKrSSKrSSKrSSKJr SSK J r J r SSK r SSK r SSKJr SSKJrJrJrJrJr SSKJr SS KJr \ "S S S S /SSSSS.S9r\ R0R3\ R0R5\5S5rS\S\4SjrS\S\4Sjr \RC5SKS\S\\"S\\ S\4Sjj5r#\RC5SLS\\\S\\"S\4Sjj5r$\RC5SMS\\S\\S\\"S\4Sjj5r%\RC5SNS\\S\\"S\\S\\"S\4 S jj5r&\RC5SOS!\S"\\"S#\\"S\\"S\4 S$jj5r'\RC5SLS%\S&\\\4S'\\S\\"S\4 S(jj5r(\RC5SPS)\S*\S&\\\\\4S+\S,\S'\\S\\"S\4S-jj5r)S.\S\4S/jr*\RC5S.\S\4S0j5r+SLS)\S1\S'\\S\\"S\4 S2jjr,\RC5SLS)\S3\S'\\S\\"S\4 S4jj5r-\RC5SLS)\S1\S3\S5\\S\\"S\\\44 S6jj5r.\RC5SLS)\S7\S'\\S\\"S\4 S8jj5r/\RC5SLS)\S9\S'\\S\\"S\4 S:jj5r0\RC5SLS)\S7\S9\S5\\S\\"S\\\44 S;jj5r1SKS\S\\"S\\ S\4S<jjr2\RC5SKS\S\\"S\\ S\4S=jj5r3S>r4\RkS?5S%\S\4S@j5r6\RkSA5S\4SBj5r7\RkSC5S\4SDj5r8\Rs5SE\S\4SFj5r:\Rs5SQSG\SH\S\4SIjj5r;\<SJ:Xa\4"5 \R{5 gg)R�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�t�UR5R5RS5(dUS3nU$)z6Add JSON formatting to PowerShell code if not present.z| convertto-jsonz | ConvertTo-Json)�strip�lower�endswith)rs � server.py�format_json_outputr(s5�� �:�:�<� � � � (� (�);� <� <���(�)�� �K�c�@^�/SQn[U4SjU55(+$)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�p># �UH+n[R"UT[R5v� M- g7f)N)�re�search� IGNORECASE)�.0�patternrs �r� <genexpr>�+validate_powershell_code.<locals>.<genexpr>Fs'����]�J\�w�2�9�9�W�d�B�M�M�:�:�J\�s�36)�any)r�dangerous_patternss` r�validate_powershell_coder-.s"��� ���]�J\�]�]� ]�]r �timeout�ctxc��# �U(aURSUS35IShv�N [XU5IShv�N $NN7f)��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_powershellr4Hs?��� ��h�h�@�� ��L�M�M�M�#�D�3�7� 7�7� N� 7�s� ?�;�?�=�?�?� propertiesc��# �SnU(aSRU5nUSU3n[[U5U5IShv�N $N7f)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)�joinr3r)r5r.r�properties_strs r�get_system_infor:XsG��� �D�����*�-����{�>�"2�3��#�$6�t�$<�g�F� F�F� F�s�:A�A�A�name�statusc��# �Sn/nU(aURSUS35 U(aURSUS35 U(aUSSRU5S3nUS3n[[U5U5IS hv�N $N7f) 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)�appendr8r3r)r;r<r.r�filterss r�get_running_servicesrBfs���� �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�A8B�:A?�;B�top�sort_byc��# �SnU(aUSUS3nU(aUSUS3nU(aUSU3nUS3n[[U5U5IShv�N $N7f) z�Get 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�r3r)r;rCrDr.rs r� get_processesrGzsq��� �D� ���x��v�Q�'�����0�� ��F�� ���/��u�5���V�H� I�D�#�$6�t�$<�g�F� F�F� F�s�A A�A�A�logname�newestrc��# �SUSU3nU(aUSUS3nUS3n[[U5U5IShv�N $N7f)a;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) zGet-EventLog -LogName z -Newest z# | Where-Object { $_.EntryType -eq r?z: | Select-Object TimeGenerated, EntryType, Source, MessageNrF)rHrIrr.rs r�get_event_logsrK�sU���$�G�9�I�f�X� >�D� ���;�E�7�#�F���V�M� N�D�#�$6�t�$<�g�F� F�F� F�s �5>�<�>� template_name� parameters� output_pathc��v# �[RR[US35n[RR U5(d[ SUS35e[ US5nUR5nSSS5 Wn[R"5RS5US'UR5H$up�URSUS 3[U 55nM& U(a+[ US 5nURU5 SSS5 S U3$U$!,(df  N�=f!,(df  N&=f7f) 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�pathr8� TEMPLATES_DIR�exists� ValueError�open�readr�now�strftime�items�replace�str�write) rLrMrNr.� template_path�f�template_content�script_content�key�values r�generate_script_from_templateri�s���$�G�G�L�L��=�/��0F�G�M� �7�7�>�>�-� (� (��9�]�O�:�>�?�?� �m�S� !�Q��6�6�8�� "�&�N�!����0�0��<�J�v�� �&�&�(� ��'�/�/�$�s�e�4�0@�#�e�*�M��)�� �+�s� #�q� �G�G�N� #�$�0�� �>�>� �� "� !��$� #�s7�A'D9�)D�:A<D9�6D(�D9� D%�!D9�( D6�2D9r� script_type�include_logging�include_error_handlingc ��V# �/nURSSSU3SSU3SSS[R"5RS 53S / 5 U(a�UR S 5 UH|nS UR S S5S3n UR S5(a U SUSS3- n U SUS3- n UR S5(a U SUSS3- n UR U S-5 M~ USR S5US'UR S5 U(aUR/SQ5 U(aUR/SQ5 UR/SQ5 SRU5n U(a+[US5n U RU 5 S S S 5 S!U3$U $!,(df  N=f7f)"aPGenerate 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: rRz#>z param (z [Parameter(Mandatory=$� mandatory�falsez)]�typez [�]�$r;�defaultz = "�"r7������)) 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 {ryrzz> [System.Management.Automation.ErrorRecord]$ErrorRecordr{zW 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..."roz6 # 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|� rTNrU) �extendrr]r^r@�get�rstripr8r[rb) rrjrMrkrlrNr.rf�param� param_str� final_contentrds 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�E5F)�7F� F)� F&�"F)rWc�H�U(d [S5eURS5(aUSSn[RR U5(d3[RR [R "5U5n[RRU5$)zCConvert relative paths to absolute using current working directory.zPath cannot be empty)z./z.\�N)rZ� startswithrVrW�isabsr8�getcwd�abspath)rWs r�normalize_pathr�2sk�� ��/�0�0� ���|�$�$��A�B�x�� �7�7�=�=�� � ��w�w�|�|�B�I�I�K��.�� �7�7�?�?�4� � r c���[U5n[RRU5S(a [RR U5nOUn[R "USS9 U$)z1Ensure directory exists and return absolute path.�T��exist_ok)r�rVrW�splitext�dirname�makedirs)rW�abs_path�dir_paths r�ensure_directoryr�<sO���d�#�H� �w�w����!�!�$��7�7�?�?�8�,�����K�K��4�(� �Or �detection_logicc��# �SU3U[R"5RS5US.nU(a [U5n[ SXBU5IShv�N $N7f)u1 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 - rR)�SYNOPSIS� DESCRIPTIONrS�DETECTION_LOGIC�intune_detectionN�rr]r^r�ri)rr�rNr.�paramss r� generate_intune_detection_scriptr�GsY���z1�� �>�"�� � ��'�'� �3�*� �F��&�{�3� �.�/A�6�X_�`� `�`� `���AA�A�A�remediation_logicc��# �SU3U[R"5RS5US.nU(a [U5n[ SXBU5IShv�N $N7f)u7 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 - rR)r�r�rS�REMEDIATION_LOGIC�intune_remediationNr�)rr�rNr.r�s r�"generate_intune_remediation_scriptr��sY���t3�;�-�@�Xc�� � ��'�'� �3�.��F� �&�{�3� �.�/C�V�Za�b� b�b� b�r�� output_dirc��# �U(a�[U5n[RRUS5n[RRUS5n[R"USS9 [ UUUUS9IShv�N n[ UUUUS9IShv�N n O&[ UUUS9IShv�N n[ UUUS 9IShv�N n UU S .$NDN2N N7f) 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�rNr.N)rr�rNr.)rr�r.)rr�r.)�detection_script�remediation_script)r�rVrWr8r�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�9B>�:C� C�C�!C�"C�4C�5 C�C�C�C�relevance_logicc��# �SU3U[R"5RS5US.nU(a [U5n[ SXBU5IShv�N $N7f)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 - rR)r�r�rS�RELEVANCE_LOGIC�bigfix_relevanceNr�)rr�rNr.r�s r� generate_bigfix_relevance_scriptr�JsY���|1�� �>�"�� � ��'�'� �3�*� �F��&�{�3� �.�/A�6�X_�`� `�`� `�r�� action_logicc��# �SU3U[R"5RS5US.nU(a [U5n[ SXBU5IShv�N $N7f)u3 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 - rR)r�r�rS� ACTION_LOGIC� bigfix_actionNr�)rr�rNr.r�s r�generate_bigfix_action_scriptr��sX���F.�k�]�;�"�� � ��'�'� �3�$� �F��&�{�3� �.���U\�]� ]�]� ]�r�c��# �U(a�[U5n[RRUS5n[RRUS5n[R"USS9 [ UUUUS9IShv�N n[ UUUUS9IShv�N n O&[ UUUS9IShv�N n[ UUUS 9IShv�N n UU S .$NDN2N N7f) 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�rNr.N)rr�rNr.)rr�r.)rr�r.)�relevance_script� action_script)r�rVrWr8r�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 ��F# �[U[5(a US:dUS:�a [S5e[U5(d [S5eU(aUR S5IShv�N U(aUR S5IShv�N [ R "SS S S U[R[RS 9IShv�N nU(aUR S 5IShv�N [ R"UR5US9IShv�N upEURS:waGU(aUR5OSnU(aURSU35IShv�N [!U5eU(aUR5OSnU(a&UR S[#U5S35IShv�N U$GNPGN3N�N�N�![ RaE UR5 U(aURSUS35IShv�N [SUS35ef=fN�Np7f)r1r��,�)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�intrZr-r2r�create_subprocess_exec� subprocess�PIPE�wait_for� communicate� TimeoutError�kill�error� returncode�decode� RuntimeError�len)rr.r/�processr�r�� error_msg�results rr3r3[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��A#H!�%F5�&H!�F8�=H!�F;�H!� G�$F=�%*G�F?�G�AH!�H�AH!�.H�/H!�8H!�;H!�=G�?G�AH�H�H�H!�H!c ��# �U(d[X5IShv�N $[R"5nURS5IShv�N [ U[ 5(a US:dUS:�a$UR S5IShv�N [S5e[U5(d$UR S5IShv�N [S5eURS 5IShv�N URS 5IShv�N URS S S 5IShv�N [R"SSSSU[R[RS9IShv�N nURSS S5IShv�N [R"UR5US9IShv�N upVURSS S5IShv�N UR$S :wa@U(aUR'5OSnUR SU35IShv�N [)U5eU(aUR'5OSn[R"5n X�- R+5n URS S S5IShv�N URSU SS35IShv�N URS [-U5S!35IShv�N U [-U5UR$U R/5S".n UR15(aS#US$[2R4"U S%S&93$S'[2R4"U S%S&93$GN�GN�GN�GNgGNFGN0GNGN�GN�GN�GN�![R a> UR#5 UR SUS35IShv�N [!SUS35ef=fGN�GN2GNN�![6a,n UR S([9U 535IShv�N eSn A ff=f7f))aExecute 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: )r3rr]r2r�r�r�rZr-�report_progressrr�r�r�r�r�r�r�r�r�r�� total_secondsr�� isoformatr�json�dumps� Exceptionra) rr.r/� start_timer�r�r�r�r��end_time�execution_time�metadata�es r�run_powershell_with_progressr��s���� �'��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��%�%�a��,I�J� J� J� � � �� "�+1�� � ��7\�I��)�)�=�i�[�I�J� J� J��y�)� )�$*��������<�<�>��"�/�>�>�@���!�!�!�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�:�:�:� ���sg�O �L�O �N�L�9N�L�3N�5L�6#N�L�N�2L"�3N� L%�=N� L(� N�&L+�'N�,&L4�L.�L4�/L1�0L4�4AN�4N �5A%N�N �N�8N�9%N�N�AN�:O �;N�O �N�N�N�N�"N�%N�(N�+N�.L4�1L4�4<N�0M3�1N�N� N�N�N� O � O�>O�?O�O � O c���[S5 [S5 [S5 [S5 [S5 [S5 [S5 [S5 [S 5 [S5 [S 5 [S5 [S 5 [S 5 [S5 [S 5 [S5 [S5 [S5 [S5 [S5 [S5 [S5 [S5 [S5 [S5 [S5 [S5 [S5 [S5 [S5 [S5 [S5 g)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�"�[RR[US35n[RR U5(d[ SUS35e[ USSS9nUR5sSSS5 $!,(df  g=f)z)Get a PowerShell script template by name.rPz Template 'z ' not foundrQ�utf-8��encodingN)rVrWr8rXrYrZr[r\)rLrcrds r�get_powershell_templater#si���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 �&B� Bztemplates://listc �:�[RR[5(d[R "/SS.5$/n[R "[5GHRnURS5(dMUSSn[RR[U5n[USSS9nUR5SS nS nUH�nUR5RS 5(dM)XURU5S -SHvnUR5(dMUR5RS 5(aM@UR5RS5(aMfUR5n O O URUU=(d SU3SU3S.5 SSS5 GMU [R "SU0SS9$!,(df  GM~=f![a1n URUS[!U 5S3SU3S.5 Sn A GM�Sn A ff=f)z(List all available PowerShell templates.zTemplates directory not found)r�messagerPN�����rQr�r�� r�rnr��#�.zPowerShell template: z template://)r;rrWzTemplate file (error reading: rxrr�r�)rVrWrYrXr�r��listdirrr8r[� readlinesrr��indexr@r�ra) r�filerLrcrd� 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�#4�Y�_�_�=N�=Y�=Y�Z]�=^�=^�gp�gv�gv�gx�hD�hD�EH�hI�hI�2;�/�/�2C�K�$)�.U�"�!,��$�$� -�'2�']�8M�m�_�6]�"-�m�_� =�&��@�?� *�: �:�:�{�I�.�q� 9�9�1@�?��"� �� � �)�%C�C��F�8�1�#M�)�-��9�"���� �sN�$ G�/=G �0,G � "G �"G �,<G �(G� G �G�G� H�)%H�Hz system://infoc�*�SSKnSSKnUR5UR5UR 5UR 5UR 5UR5S.[UR5RS- S5[UR5RS- S5UR5RS.[RS:wa([URS5RS- S5O'[URS 5RS- S5[RS:wa([URS5R S- S5O'[URS 5R S- S5S .UR#5UR%S S 9S .[&R("5R+5S.n[,R."USS9$![0a� UR5UR5UR 5UR 5UR 5UR5S.[&R("5R+5SS.n[,R."USS9s$f=f)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)r r��note)r �psutilrrrrrr�round�virtual_memory�total� availablerrVr;� disk_usage�free� cpu_count� cpu_percentrr]r�r�r�� ImportError)r r%� system_infos r�get_system_info_resourcer0Ssx���)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'G.�.B!J�J�script_purposec��SUSUS3$)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�)r1s r�powershell_best_practicesr3�s,��0�0>�/?�&@�L)�)� *�O4 �4r � error_message�script_contextc�.�U(aSU3OSnSUUS3$)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�)r4r5�context_sections r�troubleshoot_powershell_errorr8�s9��CQ�-�n�-=�>�VX�O����� �!�  �r �__main__)�<N)Nr:)NNr:)NNNr:)rNr:)NTTNr:)r�)>�logging� basicConfig�INFOr$�sysrr��typingr�mcp.server.fastmcprrrVr�rr r r r � contextlibr �collections.abcr�mcprWr8r��__file__rXrar�boolr-�toolr�r4r:rBrGrKrir�r�r�r�r�r�r�r�r�r3r�r��resourcerrr0�promptr3r8�__name__�runr�r r�<module>rKsq������ �,�,� 4��� � ����/� � ��3�3�*�)��#�^��_�-���!�� � ����� � �R�W�W�_�_�X�6� �D� ��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����"&�� Ac��Ac��Ac��#��Ac��c�]� Ac�  � Ac� �Ac�F���� !%�� 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����@ �z�� �K��G�G�I�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