Skip to main content
Glama
wireshark-gui-mcp

wireshark-gui-mcp

by Erlangga235
README.md
# wireshark-gui-mcp

Local Windows Model Context Protocol (MCP) server for Wireshark. Combines headless packet capture and analysis (`dumpcap.exe`, `tshark.exe`, `capinfos.exe`) with desktop `Wireshark.exe` GUI control and native Win32 window screenshot capture over `stdio`.

Most Wireshark MCP servers are CLI-only `tshark` wrappers. `wireshark-gui-mcp` bridges both modes:

- **Headless analysis + desktop GUI handoff:** Triage a capture with `dumpcap` and `tshark`, jump `Wireshark.exe` directly to a display filter (`-Y`), packet number (`-g`), or jump filter (`-J`), and capture a clean PNG of the GUI window via Win32 `PrintWindow`.
- **Context-budget protection:** `wireshark_read_packets` defaults to `-n` (no reverse-DNS stalls), `fields` projection, paginated `limit`/`offset`, and early-stop `-c` so large `.pcapng` files do not stall or overflow model context. Live captures require bounded stop conditions (`duration_seconds` 1-300 or `packet_count` 1-100,000).
- **Single-call composite workflows:** `wireshark_triage_pcap` runs packet count, protocol hierarchy, TCP conversations, and packet preview in parallel (`asyncio.gather`), while `wireshark_open_and_screenshot` launches the GUI, captures the PNG, and optionally closes the window in one tool call.

![Wireshark GUI opened to a filtered loopback ICMP capture](docs/demo.png)

```mermaid
flowchart LR
    Client["MCP Client (Antigravity / Claude / Cursor)"] -->|"stdio (JSON/Markdown)"| Server["wireshark-gui-mcp"]
    Server -->|"interfaces & live capture"| Dumpcap["dumpcap.exe"]
    Server -->|"filter, dissect, follow, stats"| Tshark["tshark.exe / capinfos.exe"]
    Server -->|"launch -r -Y -g -J & Win32 PrintWindow"| GUI["Wireshark.exe (Windows GUI)"]
```

## Use Cases

- **Incident triage with human handoff:** Let an agent scan a noisy `.pcapng` for retransmissions, resets, or DNS errors, then open `Wireshark.exe` on the exact offending frame for interactive review or attach a screenshot directly to a ticket.
- **Socket, API, and backend QA:** Capture loopback or interface traffic during integration tests to inspect 3-way handshakes, HTTP/TLS streams, timeouts, and `FIN` vs `RST` teardown behavior.
- **Security triage and CTF forensics:** Extract top talkers (`endpoints,ip`), DNS query stats (`dns,tree`), and reassembled `tcp`/`udp`/`tls`/`http` payloads in ASCII, hex, or raw format.
- **Reproducible technical documentation:** Capture traffic and generate consistent Wireshark GUI PNGs programmatically for runbooks, postmortems, and lab reports.

## Quickstart

### Requirements

- Windows 10 or Windows 11
- [Wireshark](https://www.wireshark.org/) 4.2+ installed with `tshark.exe`, `dumpcap.exe`, `capinfos.exe`, `Wireshark.exe`, and Npcap (enable Npcap loopback support for `\Device\NPF_Loopback` captures)
- Python 3.12+ and [`uv`](https://docs.astral.sh/uv/)

Choose either automated setup with an AI agent or manual installation below.

### Option 1: Setup with an AI Agent

Paste this prompt into an AI coding agent (Antigravity, Claude Code, Cursor, or Codex) to check prerequisites, install dependencies, register the MCP server, and verify it on Windows:

```text
Set up the wireshark-gui-mcp server from https://github.com/Erlangga235/wireshark-gui-mcp.git on this Windows machine:
1. Check prerequisites:
   - Confirm Python 3.12+ and `uv` are installed (`uv --version`; if missing, install `uv` via `winget install --id astral-sh.uv -e` or ask me to install it).
   - Locate Wireshark binaries (`tshark.exe`, `dumpcap.exe`, `capinfos.exe`, `Wireshark.exe`) in `C:\Program Files\Wireshark` or on `PATH`. If Wireshark or Npcap is missing, install `WiresharkFoundation.Wireshark` via winget or stop and ask me to run the Wireshark/Npcap installer with loopback capture enabled.
2. Clone the repo to a clean local directory (or use the current workspace if already cloned) and run `uv sync` to create `.venv` with `mcp`, `pillow`, and `pydantic`.
3. Verify the installation and Wireshark/Npcap access:
   - Run `uv run python -c "import asyncio; from wireshark_mcp import server, tshark; print('tools:', len(asyncio.run(server.mcp.list_tools())), 'interfaces:', len(asyncio.run(tshark.list_interfaces())))"` (if `dumpcap -D` reports no interfaces, remind me to enable/reinstall Npcap with loopback support).
4. Register `"wireshark"` in my active MCP client config (`mcp_config.json`, `claude_desktop_config.json`, or `.cursor/mcp.json`) without removing existing servers:
   - `command`: `"uv"`
   - `args`: `["--directory", "<repo>", "run", "wireshark-mcp"]`
   - Only add `env` (`WIRESHARK_DIR`) if Wireshark is installed outside `PATH` and `C:\Program Files\Wireshark`.
5. Tell me to reload the MCP client, then confirm `wireshark_list_interfaces` works.
```

### Option 2: Manual Setup

If you prefer to install and configure it manually:

1. Clone the repository and sync dependencies:

```powershell
git clone https://github.com/Erlangga235/wireshark-gui-mcp.git
cd wireshark-gui-mcp
uv sync
```

2. Add the server to your MCP client configuration (Antigravity `mcp_config.json`, Claude Desktop `claude_desktop_config.json`, or Cursor `.cursor/mcp.json`):

```json
{
  "mcpServers": {
    "wireshark": {
      "command": "uv",
      "args": ["--directory", "C:\\path\\to\\wireshark-gui-mcp", "run", "wireshark-mcp"]
    }
  }
}
```

Optional `env` overrides if needed: `WIRESHARK_DIR` (when Wireshark is not on `PATH` or in `C:\Program Files\Wireshark`) and `WIRESHARK_MCP_OUTPUT_DIR` (defaults to `<repo>\artifacts`).

## Example Workflows

These scenarios require correlating fields across multiple protocols, pivoting between summary stats and individual frames, and producing desktop visual proof—work that normally takes several manual filter passes in Wireshark.

1. **Root-cause intermittent HTTPS/TLS failures in a large capture**
   - **Problem:** A noisy production `.pcapng` mixes normal traffic with sporadic port 443 resets or TLS handshake alerts, making manual scrolling slow.
   - **Prompt:** *"Analyze `checkout_fail.pcapng` for failed or reset port 443 connections, inspect the failing TLS handshake parameters, and capture a Wireshark screenshot of the reset frame for the incident ticket."*
   - **Automated MCP chain:**
     1. `wireshark_triage_pcap(pcap_file="checkout_fail.pcapng", display_filter="tcp.port == 443 || dns")` — gets packet count, protocol hierarchy, and active TCP conversations in parallel.
     2. `wireshark_read_packets(pcap_file="checkout_fail.pcapng", display_filter="(tls.alert_message || tcp.flags.reset == 1) && tcp.port == 443", fields=["frame.number", "frame.time_relative", "tcp.stream", "ip.src", "ip.dst", "tls.alert_message.desc", "_ws.col.info"])` — pulls only port 443 error frames via `-n` and early-stop `-c` (note: `tls.alert_message` matches unencrypted pre-ServerHello alerts unless a TLS keylog file is configured in Wireshark).
     3. `wireshark_read_packets(pcap_file="checkout_fail.pcapng", display_filter="tcp.stream == <N> && tls.handshake", fields=["frame.number", "tls.handshake.type", "tls.handshake.extensions_server_name", "tls.handshake.ciphersuite"])` + `wireshark_packet_details(pcap_file="checkout_fail.pcapng", packet_number=<frame>, output_mode="tree")` — distinguishes ClientHello offered suites from ServerHello selected suite via `tls.handshake.type` and inspects the failure layer.
     4. `wireshark_open_and_screenshot(pcap_file="checkout_fail.pcapng", display_filter="tcp.stream == <N>", packet_number=<frame>, close_after=True)` — jumps `Wireshark.exe` to the failing stream/frame and writes a ticket-ready PNG.

2. **Hunt suspicious DNS and plaintext C2 / exfiltration in a forensic PCAP**
   - **Problem:** Anomalous traffic hides inside thousands of benign frames as failed or unusually long DNS lookups, HTTP beacons, or raw TCP payloads on non-standard ports.
   - **Prompt:** *"Check `endpoint_capture.pcapng` for rare external endpoints, NXDOMAIN bursts or long DNS queries, and non-TLS HTTP/raw TCP payloads; reconstruct the suspicious stream and save GUI evidence."*
   - **Automated MCP chain:**
     1. `wireshark_protocol_stats(pcap_file="endpoint_capture.pcapng", stat_type="endpoints,ip")` + `wireshark_protocol_stats(pcap_file="endpoint_capture.pcapng", stat_type="dns,tree")` — surfaces unusual remote hosts and DNS error rates.
     2. `wireshark_read_packets(pcap_file="endpoint_capture.pcapng", display_filter="dns.flags.rcode == 3 || dns.qry.name.len > 50 || http.request", fields=["frame.number", "ip.dst", "dns.qry.name", "http.host", "http.request.uri", "tcp.stream"], limit=100)` + a raw TCP pass `wireshark_read_packets(pcap_file="endpoint_capture.pcapng", display_filter="tcp.len > 0 && !tls && !http", fields=["frame.number", "ip.dst", "tcp.dstport", "tcp.stream", "tcp.len", "_ws.col.info"], limit=100)` — catches NXDOMAIN responses, long DNS tunneling queries, HTTP beacons, and non-HTTP/non-TLS payloads without loading full packet trees.
     3. `wireshark_follow_stream(pcap_file="endpoint_capture.pcapng", protocol="http", stream_index=<idx>, mode="ascii")` (or `protocol="tcp", mode="hex"` for binary protocols) — reassembles the full exfiltrated/command payload.
     4. `wireshark_open_and_screenshot(pcap_file="endpoint_capture.pcapng", display_filter="tcp.stream == <idx>", packet_number=<first_frame>, close_after=True)` — saves visual proof of the exact conversation.

3. **Debug wire-level socket timeouts and framing bugs live**
   - **Problem:** Intermittent timeout or abrupt-teardown bugs require capturing live with a BPF filter, checking per-stream inter-packet deltas and raw bytes, and handing the exact frame off to a developer.
   - **Prompt:** *"Capture loopback traffic on port 5000 during my test run, find any stream with >10s gaps or `RST` teardown, inspect the raw bytes, and leave Wireshark open on that packet."*
   - **Automated MCP chain:**
     1. `wireshark_list_interfaces()` -> `wireshark_capture_packets(interface="<loopback_id_or_name>", capture_filter="tcp port 5000", duration_seconds=20)` — resolves the host's `\Device\NPF_Loopback` interface (`Adapter for loopback traffic capture`) dynamically and captures targeted traffic via `dumpcap.exe`.
     2. `wireshark_read_packets(pcap_file=..., display_filter="tcp.time_delta > 10 || tcp.flags.reset == 1", fields=["frame.number", "tcp.time_delta", "tcp.stream", "tcp.flags.str", "tcp.len", "_ws.col.info"], limit=100)` — uses per-stream `tcp.time_delta` and filters before `limit=100` so concurrent streams or high packet counts do not hide stalls or late resets.
     3. `wireshark_follow_stream(pcap_file=..., protocol="tcp", stream_index=<idx>, mode="hex")` + `wireshark_packet_details(pcap_file=..., packet_number=<frame>, output_mode="hex")` — checks byte-level framing and TCP header flags.
     4. `wireshark_open_gui(pcap_file=..., display_filter="tcp.stream == <idx>", packet_number=<frame>)` — opens `Wireshark.exe` on the desktop focused directly on the offending packet.

## Tool Reference

Every tool accepts strict Pydantic-validated inputs (`extra="forbid"`) and supports `response_format` (`"markdown"` or `"json"`) where structured summaries apply.

| Tool | Backend | Purpose | Key Options |
|---|---|---|---|
| `wireshark_list_interfaces` | `dumpcap` / `tshark` | List Windows capture interfaces. | `include_extcap` (true includes `USBPcap`/`etwdump`), `response_format` |
| `wireshark_capture_packets` | `dumpcap` / `tshark` | Capture live traffic to `.pcapng`. | `interface`, `duration_seconds` (1-300, default 5), `packet_count` (1-100000), `capture_filter`, `promiscuous` |
| `wireshark_read_packets` | `tshark` | Filter, extract fields, and paginate packets. | `display_filter`, `fields` (max 25), `limit` (1-200), `offset`, `resolve_names`, `exact_count` |
| `wireshark_packet_details` | `tshark` | Decode all protocol layers for one packet. | `packet_number`, `output_mode` (`tree`, `json`, `hex`), `resolve_names` |
| `wireshark_follow_stream` | `tshark` | Reassemble a conversation payload. | `protocol` (`tcp`, `udp`, `tls`, `http`), `stream_index`, `mode` (`ascii`, `hex`, `raw`), `resolve_names` |
| `wireshark_protocol_stats` | `tshark` | Generate Wireshark protocol/endpoint tables. | `stat_type` (`io,phs`, `conv,tcp`, `conv,udp`, `conv,ip`, `endpoints,ip`, `endpoints,tcp`, `http,tree`, `dns,tree`), `display_filter` |
| `wireshark_triage_pcap` | `capinfos` + `tshark` | Run packet count, `io,phs`, `conv,tcp`, and packet preview in parallel. | `display_filter`, `packet_limit` (1-100), `resolve_names`, `response_format` |
| `wireshark_open_gui` | `Wireshark.exe` | Launch desktop GUI on a file or live interface. | `pcap_file`, `display_filter`, `packet_number`, `jump_filter`, `interface`, `capture_filter`, `auto_start`, `maximize`, `fullscreen` |
| `wireshark_list_windows` | Win32 API | List open `Wireshark.exe` windows (`HWND`, `PID`, title, bounds). | `include_hidden`, `response_format` |
| `wireshark_screenshot` | Win32 `PrintWindow` | Capture a PNG from a Wireshark GUI window. | `hwnd`, `pid`, `title_contains`, `output_file`, `bring_to_front`, `restore_if_minimized`, `settle_ms` |
| `wireshark_open_and_screenshot` | `Wireshark.exe` + Win32 | Open GUI on a capture/filter/packet, screenshot it, and optionally close it. | `pcap_file`, `display_filter`, `packet_number`, `jump_filter`, `output_file`, `close_after` |
| `wireshark_close_gui` | Win32 / `taskkill` | Close one or all open Wireshark GUI windows. | `pid`, `hwnd`, `close_all`, `force` |

## Architecture & Performance

- **Shell-free async subprocesses:** `tshark.py` executes `dumpcap.exe`, `tshark.exe`, and `capinfos.exe` via `asyncio.create_subprocess_exec` with explicit timeouts and no shell expansion.
- **Non-blocking GUI calls:** All synchronous Win32 and `Wireshark.exe` operations in `win_gui.py` run inside `asyncio.to_thread(...)` so the MCP stdio event loop stays responsive.
- **DPI-aware Win32 capture:** `win_gui.py` enables Per-Monitor V2 DPI awareness, reads window rectangles via `DwmGetWindowAttribute` (`DWMWA_EXTENDED_FRAME_BOUNDS`), and renders windows offscreen with `PrintWindow(PW_RENDERFULLCONTENT)` with blank-frame detection and `ImageGrab` fallback.

Measured locally on Windows 11 (Loopback interface, 4-packet ICMP `.pcapng`):

| Operation | Measured Time | Notes |
|---|---|---|
| `wireshark_list_interfaces` | `0.17s` | Uses `dumpcap -D` instead of `tshark -D` (`1.27s`) |
| `wireshark_capture_packets` | `2.24s` | Uses `dumpcap.exe` (`3.28s` with `tshark.exe`) |
| `wireshark_read_packets` | `0.31s` | Uses `-n` and early-stop `-c` pagination |
| `wireshark_triage_pcap` | `0.54s` | Runs `capinfos`, `io,phs`, `conv,tcp`, and preview concurrently |
| `wireshark_open_and_screenshot` | `5.11s` | Launches `Wireshark.exe`, captures via `PrintWindow`, and closes |

## License

MIT — see [LICENSE](LICENSE).