Skip to main content
Glama

Wireshark MCP Server

wireshark-mcp-server.cpython-310.pyc14.9 kB
o ��UhbN�@sdZddlZddlZddlZddlZddlZddlZddlZddlm Z ddl m Z ddl m Z mZmZmZmZzddlmZWneyQed�ed�Ynwejejd d �e�e�ZGd d �d �ZGd d�d�ZGdd�d�Zdd�Zedkr�e�dSdS)z� Wireshark MCP Server A Model Context Protocol server that provides AI assistants with access to Wireshark network analysis capabilities for network troubleshooting and analysis. Author: AI Assistant Date: 2025-06-20 �N)�ThreadPoolExecutor)�Path)�Dict�Any�List�Optional�Union)�FastMCPz8FastMCP not installed. Install with: pip install fastmcp�z4%(asctime)s - %(name)s - %(levelname)s - %(message)s)�level�formatc@sjeZdZdZgd�ZdZdZdZede de fdd ��Z ed e de fd d ��Z ed e de e fdd��ZdS)�SecurityValidatorz>Security validation utilities for network analysis operations.)z6^(eth|wlan|lo|en|enp|wlp|docker|br-)[a-zA-Z0-9]{1,15}$z^Ethernet \d+$z ^Wi-Fi \d*$z^Local Area Connection \d*$z^\d+$i,i'i@� interface�returncs,�rt��dkr dSt�fdd�tjD��S)z9Validate network interface name against allowed patterns.�2Fc3s�|] }t�|��VqdS�N)�re�match��.0�pattern�r��wireshark-mcp-server.py� <genexpr>;s � � �z7SecurityValidator.validate_interface.<locals>.<genexpr>)�len�anyr �INTERFACE_PATTERNSrrrr�validate_interface5s  �z$SecurityValidator.validate_interface� filter_exprcs6�sdSgd�}t�fdd�|D��rdSt��dkS)z'Validate BPF capture filter expression.T)�;�|�&z$(�`� � z..c3s�|]}|�vVqdSrrr�rrrrHs�z<SecurityValidator.validate_capture_filter.<locals>.<genexpr>Fi�)rr)r�dangerous_patternsrr&r�validate_capture_filter@s  z)SecurityValidator.validate_capture_filter�filepathcCsdz't|���}|��sWdS|j��dvrWdS|��jtjkr#WdSt |�WSt y1YdSw)z!Sanitize and validate file paths.N)z.pcapz.pcapng) r�resolve�exists�suffix�lower�stat�st_sizer � MAX_FILE_SIZE�str� Exception)r)� resolved_pathrrr�sanitize_filepathNs   �z#SecurityValidator.sanitize_filepathN)�__name__� __module__� __qualname__�__doc__r�MAX_CAPTURE_DURATION�MAX_PACKET_COUNTr0� staticmethodr1�boolrr(rr4rrrrr $s   r c @s�eZdZdZdd�Zdeefdd�Zdeefdd�Zdeefd d �Z de ee ffd d �Z d dede dede de ee ff dd�Z  d!dedede de ee ffdd�Zdede ee ffdd�Zdede ee ffdd�ZdS)"�WiresharkInterfacez8Interface to Wireshark CLI tools with security controls.cCs0|��|_|��|_|��|_|jstd��dS)Nz+TShark not found. Please install Wireshark.)� _find_tshark� tshark_path� _find_dumpcap� dumpcap_path�_find_capinfos� capinfos_path� RuntimeError��selfrrr�__init__gs   �zWiresharkInterface.__init__rc C�Zgd�}|D]$}ztj|dgddd�}|jdkr|WSWqtjtfy*YqwdS)zFind TShark executable.)�tsharkz tshark.exez%C:\Program Files\Wireshark\tshark.exez/usr/bin/tsharkz/usr/local/bin/tshark� --versionT���capture_output�timeoutrN�� subprocess�run� returncode�TimeoutExpired�FileNotFoundError�rF� common_paths�path�resultrrrr>o� �  ��zWiresharkInterface._find_tsharkc CrH)zFind dumpcap executable.)�dumpcapz dumpcap.exez&C:\Program Files\Wireshark\dumpcap.exez/usr/bin/dumpcapz/usr/local/bin/dumpcaprJTrKrLrNrOrUrrrr@�rYz WiresharkInterface._find_dumpcapc CrH)zFind capinfos executable.)�capinfosz capinfos.exez'C:\Program Files\Wireshark\capinfos.exez/usr/bin/capinfosz/usr/local/bin/capinfosrJTrKrLrNrOrUrrrrB�rYz!WiresharkInterface._find_capinfosc Cs�z7|jr2tj|jdgdddd�}|jdkr2g}|j���d�D] }|r(|�|�qd|t|�d�WSd d d �WSt yX}zt � d |���d t |�d �WYd }~Sd }~ww)z)Get list of available network interfaces.z-DT� �rM�textrNrr$�success)�status� interfaces�count�errorzUnable to list interfaces�r`�messagezError getting interfaces: N) r?rPrQrR�stdout�strip�split�appendrr2�loggerrcr1)rFrXra�line�errr�get_interfaces�s0�  �� ��z!WiresharkInterface.get_interfaces�d��rrbrrNc Cs>zo|jd|dt|�ddg}|r|�d|g�tj|dd|d�}|jdkr.d d |j��d �WSg}|j��r_z|j��� d �D]}|rLt � |�} |� | �q>Wnt j y^d |jig}Ynwd|t|�|dd�t|�d�WStjy~d dd �YSty�} zt�d| ���d t| �d �WYd} ~ Sd} ~ ww)z4Capture packets from network interface using TShark.z-i�-c�-T�jsonz-fTr]rrczCapture failed: rdr$� raw_outputr_N�)r`r� packet_count�packets�total_capturedzCapture timeoutzCapture error: )r?r1�extendrPrQrR�stderrrfrgrhrs�loadsri�JSONDecodeErrorrrSr2rjrc) rFrrbrrN�cmdrXrwrk�packetrlrrr�capture_packets�sN�  �   ��� ���z"WiresharkInterface.capture_packets��r)� max_packetsc Cs4zx|jd|ddg}|r|�d|g�|dkr|�dt|�g�tj|dddd �}|jdkr7d d |j��d �WSg}|j��rhz|j��� d �D]}|rUt � |�}|� |�qGWnt j ygd|jig}Ynwd|t|�|dd�t|�d�WSty�} zt�d| ���d t| �d �WYd} ~ Sd} ~ ww)zAnalyze PCAP file using TShark.�-rrrrsz-YrrqT�<r]rczAnalysis failed: rdr$rtr_Nr\)r`�filervrw�total_analyzedzAnalysis error: )r?ryr1rPrQrRrzrfrgrhrsr{rir|rr2rjrc) rFr)rr�r}rXrwrkr~rlrrr�analyze_pcap_file�sN�  �   ��� ���z$WiresharkInterface.analyze_pcap_filec Cs�z?|jd|dddg}tj|dddd�}|jd|dddg}tj|dddd�}d ||jd kr/|jnd |jd kr;|jd �WSd d �WSty`}zt�d|���dt|�d�WYd}~Sd}~ww)z,Generate protocol statistics from PCAP file.r�z-qz-zzio,phsTrpr]zconv,ipr_rzError generating hierarchyzError generating conversations)r`r��protocol_hierarchy�ip_conversationszStatistics error: rcrdN) r?rPrQrRrfr2rjrcr1)rFr)� cmd_hierarchy�hierarchy_result�cmd_conv� conv_resultrlrrr�get_protocol_statistics.s6������z*WiresharkInterface.get_protocol_statisticsc Cs�|jsddd�Sz#tj|j|gdddd�}|jdkr"d||jd �WSdd |j��d�WStyD}z dt|�d�WYd }~Sd }~ww) z4Get information about a capture file using capinfos.rczcapinfos not availablerdTr\r]rr_)r`r��infozcapinfos failed: N)rCrPrQrRrfrzr2r1)rFr)rXrlrrr� get_file_infoNs* � � ���z WiresharkInterface.get_file_infoN)rnrorp)ror�)r5r6r7r8rGrr1r>r@rBrrrm�intrr�r�r�rrrrr=ds2 ���  �3 ��  �0 r=c@s(eZdZdZdd�Zdd�Zdd�ZdS) �WiresharkMCPServerz7Main MCP server class providing Wireshark capabilities.cCs4td�|_t�|_tdd�|_|��t�d�dS)Nzwireshark-analyzer�)� max_workersz Wireshark MCP Server initialized) r �mcpr=� wiresharkr�executor�register_toolsrjr�rErrrrGms  zWiresharkMCPServer.__init__cs��jjdtttff�fdd� �}�jj   ddtdtd td tdtttff �fd d � �}�jj  ddtdtdtdtttff�fdd� �}�jjdtdtttff�fdd� �}�jjdtdtttff�fdd� �}�j�d�dtfdd��}dS)zRegister all MCP tools.rcs �j��S)z<Get list of available network interfaces for packet capture.)r�rmrrErr�get_network_interfacesws zAWiresharkMCPServer.register_tools.<locals>.get_network_interfacesrrorprrb�capture_filterrNc �s��t�|�s ddd�St�|�sddd�St|tj�}t|d�}zt��}|��j�j j ||||�IdH}|WSt yX}zt � d|���dt|�d�WYd}~Sd}~ww)a� Capture live network packets from a specified interface. Args: interface: Network interface name or number (e.g., "eth0", "1") count: Number of packets to capture (max 1000) capture_filter: BPF capture filter (e.g., "tcp port 80") timeout: Capture timeout in seconds (max 60) rczInvalid interface namerdzInvalid capture filterr�NzLive capture error: )r rr(�minr:�asyncio�get_event_loop�run_in_executorr�r�rr2rjrcr1)rrbr�rN�looprXrlrErr�capture_live_packets|s(�       ���z?WiresharkMCPServer.register_tools.<locals>.capture_live_packetsrnr)�display_filterr�c �s��t�|�}|s ddd�St|d�}zt��}|��j�jj|||�IdH}|WSt yI}zt � d|���dt |�d�WYd}~Sd}~ww)a' Analyze an existing PCAP/PCAPNG file. Args: filepath: Path to the PCAP/PCAPNG file display_filter: Wireshark display filter (e.g., "http.request") max_packets: Maximum number of packets to analyze rc�!Invalid or inaccessible file pathrdr�NzFile analysis error: ) r r4r�r�r�r�r�r�r�r2rjrcr1)r)r�r��sanitized_pathr�rXrlrErrr��s$�    ���z<WiresharkMCPServer.register_tools.<locals>.analyze_pcap_filec�$t�|�}|s ddd�S�j�|�S)z� Generate protocol hierarchy and conversation statistics from a PCAP file. Args: filepath: Path to the PCAP/PCAPNG file rcr�rd)r r4r�r��r)r�rErrr���   zBWiresharkMCPServer.register_tools.<locals>.get_protocol_statisticscr�)z� Get detailed information about a capture file. Args: filepath: Path to the PCAP/PCAPNG file rcr�rd)r r4r�r�r�rErr�get_capture_file_info�r�z@WiresharkMCPServer.register_tools.<locals>.get_capture_file_infoznetwork://helpcSsdS)z9Comprehensive help documentation for Wireshark MCP tools.ay # Wireshark MCP Server Help ## Available Tools ### get_network_interfaces() - Lists all available network interfaces for packet capture - No parameters required - Returns interface names and numbers ### capture_live_packets(interface, count, capture_filter, timeout) - Captures live network packets from specified interface - Parameters: - interface: Interface name (e.g., "eth0") or number (e.g., "1") - count: Number of packets to capture (default: 50, max: 1000) - capture_filter: BPF filter expression (optional) - timeout: Capture timeout in seconds (default: 30, max: 60) ### analyze_pcap_file(filepath, display_filter, max_packets) - Analyzes existing PCAP/PCAPNG files - Parameters: - filepath: Path to capture file - display_filter: Wireshark display filter (optional) - max_packets: Maximum packets to analyze (default: 100, max: 1000) ### get_protocol_statistics(filepath) - Generates protocol hierarchy and conversation statistics - Parameters: - filepath: Path to capture file ### get_capture_file_info(filepath) - Gets detailed information about capture file - Parameters: - filepath: Path to capture file ## Common Filters ### Capture Filters (BPF syntax): - "tcp port 80" - HTTP traffic - "host 192.168.1.1" - Traffic to/from specific host - "net 10.0.0.0/8" - Traffic on specific network ### Display Filters (Wireshark syntax): - "http.request" - HTTP requests - "tcp.flags.syn == 1" - TCP SYN packets - "dns.flags.response == 1" - DNS responses ## Security Notes - All inputs are validated for security - File paths are sanitized and checked - Capture limits are enforced - Only PCAP/PCAPNG files are accepted rrrrr�get_help_documentation�szAWiresharkMCPServer.register_tools.<locals>.get_help_documentationN)rrorp)rorn)r��toolrr1rr��resource)rFr�r�r�r�r�r�rrErr�tsF����� �&���� �!   z!WiresharkMCPServer.register_toolscCst�d�|j��dS)zRun the MCP server.z Starting Wireshark MCP Server...N)rjr�r�rQrErrrrQs zWiresharkMCPServer.runN)r5r6r7r8rGr�rQrrrrr�js  )r�c Cs\z t�}|��WdStyt�d�YdSty-}z t�d|����d}~ww)zMain entry point.zServer stopped by userzServer error: N)r�rQ�KeyboardInterruptrjr�r2rc)�serverrlrrr�main!s ��r��__main__) r8r�rs�logging�osrrP�time�concurrent.futuresr�pathlibr�typingrrrrr�fastmcpr � ImportError�print�exit� basicConfig�INFO� getLoggerr5rjr r=r�r�rrrr�<module>s@     �� @8 �

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/mixelpixx/Wireshark-MCP'

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