Metadata-Version: 2.4
Name: tshark-mcp
Version: 0.1.2
Summary: MCP server for using TShark to analyze network packets
Author: Neo
License-Expression: MIT
Project-URL: Homepage, https://github.com/ouonet/tshark-mcp
Project-URL: Repository, https://github.com/ouonet/tshark-mcp
Project-URL: Issues, https://github.com/ouonet/tshark-mcp/issues
Keywords: mcp,tshark,wireshark,pcap,network-analysis,ss7
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Information Technology
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Internet
Classifier: Topic :: System :: Networking :: Monitoring
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: mcp[cli]>=1.0.0
Dynamic: license-file

# TShark MCP Server

An MCP (Model Context Protocol) server that exposes TShark as tools for AI-assisted network packet analysis. Supports PCAP analysis, live capture, TLS decryption, and telecom/SS7 signaling protocols.

## Requirements

- Python 3.10+
- [Wireshark / TShark](https://www.wireshark.org/download.html) installed on the system
- `mergecap` (bundled with Wireshark, required for `merge_pcap_files`)

## Installation

This MCP server can be installed via your package manager and configured in your MCP client.

```bash
# Using uv (recommended)
uv pip install tshark-mcp

# Or pip
pip install tshark-mcp
```

## Configuration

### TShark path

The server automatically detects TShark in common installation locations:

- **Windows**: `C:\Program Files\Wireshark\tshark.exe`, `C:\Program Files (x86)\Wireshark\tshark.exe`
- **macOS**: `/usr/local/bin/tshark`, `/opt/homebrew/bin/tshark`
- **Linux**: `/usr/bin/tshark`, `/usr/sbin/tshark`, `/usr/local/bin/tshark`

If TShark is installed in a non-standard location or auto-detection fails, set the `TSHARK_PATH` environment variable:

```bash
# Windows
set TSHARK_PATH=C:\Program Files\Wireshark\tshark.exe

# Linux / macOS
export TSHARK_PATH=/opt/wireshark/bin/tshark
```

### MCP client (Claude Desktop / VS Code)

`uv run server.py` works only when the current working directory is the project root.
For reliable usage, prefer one of the two options below.

#### Option A (recommended after publishing): run installed command

Use the key for your client:

- VS Code MCP: `servers`
- Claude Desktop: `mcpServers`

Ready-to-use copy templates:

- Claude Desktop (published package)

```json
{
  "mcpServers": {
    "tshark-mcp": {
      "type": "stdio",
      "command": "uv",
      "args": ["tool", "run", "tshark-mcp"]
    }
  }
}
```

- VS Code MCP (published package)

```json
{
  "servers": {
    "tshark-mcp": {
      "type": "stdio",
      "command": "uv",
      "args": ["tool", "run", "tshark-mcp"]
    }
  }
}
```

#### Option B (source checkout): pin project path explicitly

VS Code MCP example:

```json
{
  "servers": {
    "tshark-mcp": {
      "type": "stdio",
      "command": "uv",
      "args": ["run", "--project", "C:/path/to/tshark-mcp", "server.py"]
    }
  }
}
```

Claude Desktop example:

```json
{
  "mcpServers": {
    "tshark-mcp": {
      "type": "stdio",
      "command": "uv",
      "args": ["run", "--project", "C:/path/to/tshark-mcp", "server.py"]
    }
  }
}
```

To use a custom TShark path pass it via `env`.

VS Code MCP example:

```json
{
  "servers": {
    "tshark-mcp": {
      "type": "stdio",
      "command": "uv",
      "args": ["tool", "run", "tshark-mcp"],
      "env": {
        "TSHARK_PATH": "C:\\Program Files\\Wireshark\\tshark.exe"
      }
    }
  }
}
```

Claude Desktop example:

```json
{
  "mcpServers": {
    "tshark-mcp": {
      "type": "stdio",
      "command": "uv",
      "args": ["tool", "run", "tshark-mcp"],
      "env": {
        "TSHARK_PATH": "C:\\Program Files\\Wireshark\\tshark.exe"
      }
    }
  }
}
```

## Development

To contribute or modify the server, clone the repository and set up the development environment:

```bash
# Clone and setup
git clone <repository-url>
cd tshark-mcp
uv sync

# Run the server during development
uv run server.py

# Run tests
uv run pytest test_server.py
```

---

## Tools (25 total)

### Basic Analysis

| Tool | Key Parameters | Description |
|------|---------------|-------------|
| `analyze_pcap_file` | `display_filter`, `keylog_file`, `max_packets` | Packet summaries with optional display filter and TLS decryption |
| `get_packet_statistics` | — | Protocol hierarchy statistics (`io,phs`) — shows all protocol layers present |
| `extract_packet_details` | `packet_number` | Full verbose detail for a specific packet (1-based index) |
| `extract_fields` | `fields`, `display_filter`, `keylog_file` | Extract any tshark field as tab-separated values |
| `export_to_json` | `display_filter`, `keylog_file`, `max_packets` | Export packets as JSON for structured analysis |
| `run_tshark_command` | `command_args` | Run any raw tshark command |

### Traffic Aggregation & Statistics

| Tool | Key Parameters | Description |
|------|---------------|-------------|
| `get_conversations` | `protocol` | Conversation statistics — protocol: `eth` / `ip` / `tcp` / `udp` / `sctp` |
| `get_flow_matrix` | `display_filter`, `top_n` | Host-pair communication matrix (ip.src × ip.dst), ranked by bytes |
| `get_traffic_timeseries` | `interval_seconds`, `display_filter` | Packets and bytes per time bucket — identifies bursts and periodic patterns |
| `aggregate_flows` | `group_by`, `display_filter`, `top_n` | Group packets by any field combination (e.g. `ip.src,tcp.dstport`) |

### Protocol-Specific Analysis

| Tool | Key Parameters | Description |
|------|---------------|-------------|
| `analyze_dns` | `display_filter`, `top_n` | DNS query patterns, NXDOMAIN detection, response time statistics |
| `get_tcp_performance` | `display_filter` | RTT, retransmissions, window size — diagnose network quality issues |
| `follow_stream` | `protocol`, `stream_index`, `keylog_file` | Reconstruct a TCP / UDP / **SCTP** stream as ASCII text |

### Telecom / SS7 Signaling

These tools handle the telecom core network signaling stack:
**SCTP → M3UA → SCCP → TCAP → MAP**

| Tool | Key Parameters | Description |
|------|---------------|-------------|
| `reconstruct_tcap_dialogue` | `display_filter`, `max_dialogues` | Group TCAP messages (Begin/Continue/End/Abort) by transaction ID (OTID/DTID) |
| `analyze_map_operations` | `display_filter`, `top_n` | MAP operation frequency table + per-IMSI activity summary |

### TLS Decryption

> Requires a [TLS key log file](#tls-decryption-setup) generated by the target application.

| Tool | Description |
|------|-------------|
| `follow_tls_stream` | Reconstruct a decrypted TLS stream as plaintext from a PCAP + key log file |
| `capture_and_decrypt` | Capture live traffic and immediately show decrypted TLS content |
| `tshark_reading_manual` | **Read this first** — full TLS decryption workflow including debugger-based key extraction |

### Live Capture

| Tool | Key Parameters | Description |
|------|---------------|-------------|
| `list_interfaces` | — | List available network interfaces for live capture |
| `capture_live` | `interface`, `packet_count`, `duration`, `display_filter` | Capture live packets (max 500 packets / 60 s) |
| `capture_process` | `pid`, `interface`, `output_pcap`, `duration`, `keylog_file` | Capture traffic for a specific process by PID |

### File Operations

| Tool | Key Parameters | Description |
|------|---------------|-------------|
| `filter_and_save` | `display_filter` | Filter packets from a PCAP and save to a new PCAP file |
| `export_objects` | `protocol`, `output_dir` | Extract files transferred over HTTP / SMB / TFTP / IMF / DICOM |
| `merge_pcap_files` | `input_files`, `output_file`, `display_filter` | Merge multiple PCAPs in timestamp order (uses `mergecap`) |

### Process Management

| Tool | Description |
|------|-------------|
| `list_processes` | List running processes with PIDs (filter by name) |

---

## Examples

### General PCAP Analysis

```python
# Protocol hierarchy — confirm what layers are in the capture
get_packet_statistics("/captures/traffic.pcap")

# First 100 packets, HTTP only
analyze_pcap_file("/captures/traffic.pcap", display_filter="http")

# Extract source IPs, methods, and URIs from HTTP requests
extract_fields(
    file_path="/captures/traffic.pcap",
    fields="ip.src,http.request.method,http.request.uri",
    display_filter="http.request"
)

# Full detail for packet 42
extract_packet_details("/captures/traffic.pcap", packet_number=42)
```

### Traffic Aggregation

```python
# Which hosts talk to each other most? (top 20 by bytes)
get_flow_matrix("/captures/traffic.pcap")

# Traffic volume over time — 5-second buckets
get_traffic_timeseries("/captures/traffic.pcap", interval_seconds=5.0)

# TCP traffic only, 1-second buckets
get_traffic_timeseries("/captures/traffic.pcap", interval_seconds=1.0, display_filter="tcp")

# Per-service breakdown: which src IP hits which dst port most?
aggregate_flows(
    file_path="/captures/traffic.pcap",
    group_by="ip.src,ip.dst,tcp.dstport",
    display_filter="tcp"
)

# SCTP conversation statistics
get_conversations("/captures/ss7.pcap", protocol="sctp")
```

### DNS Analysis

```python
# Top queried domains, NXDOMAIN failures, response times
analyze_dns("/captures/traffic.pcap")

# DNS from a specific client only
analyze_dns("/captures/traffic.pcap", display_filter="ip.src == 192.168.1.10")
```

### TCP Performance Diagnosis

```python
# RTT, retransmission rate, window size — is the network healthy?
get_tcp_performance("/captures/traffic.pcap")

# Performance for a specific server
get_tcp_performance("/captures/traffic.pcap", display_filter="ip.addr == 10.0.0.1")
```

### Stream Reconstruction

```python
# Follow the first TCP stream
follow_stream("/captures/traffic.pcap", protocol="tcp", stream_index=0)

# Follow an SCTP stream
follow_stream("/captures/ss7.pcap", protocol="sctp", stream_index=0)

# Follow a TELNET session (TELNET runs over TCP port 23)
follow_stream("/captures/traffic.pcap", protocol="tcp", stream_index=0)
```

### Telecom / SS7 Signaling Analysis

The typical protocol stack is: **SCTP → M3UA → SCCP → TCAP → MAP**

```python
# Step 1 — confirm SS7 layers are present
get_packet_statistics("/captures/ss7.pcap")
# Expected output includes: sctp, m3ua, mtp3, sccp, tcap, gsm_map

# Step 2 — reconstruct TCAP dialogues (Begin→Continue→End chains)
reconstruct_tcap_dialogue("/captures/ss7.pcap")

# Step 3 — MAP operation frequency + IMSI tracking
analyze_map_operations("/captures/ss7.pcap")

# Step 4 — raw MAP field extraction
extract_fields(
    file_path="/captures/ss7.pcap",
    fields="gsm_map.opr.code,gsm_map.imsi,gsm_map.msisdn.digits",
    display_filter="gsm_map"
)

# SCCP routing analysis — who calls whom?
aggregate_flows(
    file_path="/captures/ss7.pcap",
    group_by="sccp.calling_party,sccp.called_party",
    display_filter="sccp"
)

# Filter to a specific TCAP dialogue by OTID
extract_fields(
    file_path="/captures/ss7.pcap",
    fields="frame.time_relative,tcap.MessageType,tcap.otid,tcap.dtid,gsm_map.opr.code",
    display_filter="tcap.otid == aabbccdd"
)
```

### File Extraction (Forensics)

```python
# Extract files transferred over HTTP in a capture
export_objects(
    file_path="/captures/traffic.pcap",
    protocol="http",
    output_dir="/tmp/extracted/"
)

# Extract SMB file transfers
export_objects(
    file_path="/captures/traffic.pcap",
    protocol="smb",
    output_dir="/tmp/smb_files/"
)
```

### Multi-PCAP Correlation

```python
# Merge two captures from different taps, analyze combined
merge_pcap_files(
    input_files="/captures/tap1.pcap,/captures/tap2.pcap",
    output_file="/captures/merged.pcap"
)

# With a display filter on the merged result
merge_pcap_files(
    input_files="/captures/tap1.pcap,/captures/tap2.pcap",
    output_file="/captures/merged.pcap",
    display_filter="tcp"
)
```

### TLS Decryption

```python
# Decrypt and reconstruct HTTPS stream
follow_tls_stream(
    file_path="/captures/traffic.pcap",
    keylog_file="C:/captures/keys.log",
    stream_index=0
)

# Extract HTTP fields from decrypted traffic
extract_fields(
    file_path="/captures/traffic.pcap",
    fields="ip.src,http.request.method,http.request.uri",
    display_filter="http.request",
    keylog_file="C:/captures/keys.log"
)

# Live capture + real-time TLS decryption
capture_and_decrypt(
    interface=r"\Device\NPF_{...}",
    keylog_file="C:/captures/keys.log",
    output_pcap="C:/captures/session.pcap",
    duration=30
)
```

### Process-Specific Capture

```python
# Find process PID
list_processes("chrome")
# → chrome.exe  PID 4812

# Capture traffic for that process
capture_process(
    pid=4812,
    interface=r"\Device\NPF_{...}",   # from list_interfaces()
    output_pcap="C:/captures/chrome.pcap",
    duration=30
)

# Capture + decrypt TLS in one step
capture_process(
    pid=4812,
    interface=r"\Device\NPF_{...}",
    output_pcap="C:/captures/chrome.pcap",
    duration=30,
    keylog_file="C:/captures/keys.log"   # set SSLKEYLOGFILE before launching Chrome
)
```

---

## Protocol Support Reference

| Protocol | Filter | Relevant Fields | Best Tool |
|----------|--------|-----------------|-----------|
| TCP | `tcp` | `tcp.srcport`, `tcp.dstport`, `tcp.stream` | `follow_stream`, `get_tcp_performance` |
| UDP | `udp` | `udp.srcport`, `udp.dstport` | `follow_stream`, `get_conversations` |
| **SCTP** | `sctp` | `sctp.srcport`, `sctp.dstport`, `sctp.chunk_type` | `get_conversations`, `follow_stream` |
| HTTP | `http` | `http.request.uri`, `http.response.code` | `extract_fields`, `export_objects` |
| TLS/HTTPS | `tls` | `tls.record.content_type` | `follow_tls_stream`, `capture_and_decrypt` |
| DNS | `dns` | `dns.qry.name`, `dns.flags.rcode`, `dns.time` | `analyze_dns` |
| TELNET | `telnet` | (follow TCP stream) | `follow_stream` (protocol=tcp) |
| **M3UA** | `m3ua` | `m3ua.protocol_data_opc`, `m3ua.protocol_data_dpc` | `extract_fields`, `aggregate_flows` |
| **SCCP** | `sccp` | `sccp.calling_party`, `sccp.called_party`, `sccp.ssn` | `aggregate_flows`, `extract_fields` |
| **TCAP** | `tcap` | `tcap.otid`, `tcap.dtid`, `tcap.MessageType` | `reconstruct_tcap_dialogue` |
| **MAP** | `gsm_map` | `gsm_map.opr.code`, `gsm_map.imsi`, `gsm_map.msisdn.digits` | `analyze_map_operations` |

---

## TLS Decryption Setup

TShark can decrypt TLS traffic when given the session keys written by the application. Set the `SSLKEYLOGFILE` environment variable **before** launching the target application:

```bash
# Windows
set SSLKEYLOGFILE=C:\captures\keys.log
start chrome

# Linux / macOS
export SSLKEYLOGFILE=/tmp/keys.log
google-chrome &
```

Supported runtimes: Chrome, Edge, Firefox, curl, Python (requests / httpx / aiohttp), Go `crypto/tls` (with `SSLKEYLOGFILE` patch), Node.js (`--tls-keylog`).

For applications that do **not** support `SSLKEYLOGFILE` (compiled binaries, custom TLS stacks), keys must be extracted from process memory using a debugger. Call `tshark_reading_manual` for the complete step-by-step workflow including x64dbg-based key extraction.

---

## Process-Specific Capture — How It Works

1. **`list_processes`** — find the PID of the target process.
2. **`capture_process`** — snapshots the process's open connections at capture start, builds a BPF filter from its local ports, then runs a timed capture saving to a PCAP file.

Because the filter is derived at capture start, connections opened later still get captured if they share a port already in the filter. For long-running captures or applications with many short-lived connections, re-run `capture_process` as needed, or use `capture_live` without a filter and post-filter with `filter_and_save`.

| Platform | Tool used internally | Notes |
|----------|---------------------|-------|
| Windows  | `netstat -ano` (built-in) | No extra installation needed |
| macOS    | `lsof` (built-in) | No extra installation needed |
| Linux    | `ss` (iproute2) | Usually pre-installed; `apt install iproute2` if missing |

---

## Development

Run the test suite (no TShark installation required — all tests mock the subprocess):

```bash
# Install pytest
uv add --dev pytest

# Run tests
uv run python -m pytest test_server.py -v
```

## Project Policies

- License: see [LICENSE](LICENSE)
- Contributing guide: see [CONTRIBUTING.md](CONTRIBUTING.md)
- Code of conduct: see [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md)
- Security policy: see [SECURITY.md](SECURITY.md)

## Release

- One-command pre-release check: `uv run python scripts/release_check.py`
- Versioning and release notes template: see [RELEASE.md](RELEASE.md)
