PCAP分析仪MCP服务器
](https://github.com/aws-samples/sample-pcap-analyzer-mcp)  
使用Wireshark/tshark进行全面网络数据包捕获和分析的模型上下文协议(MCP)服务器。
概述
此MCP服务器使AI模型能够执行复杂的网络数据包捕获和分析。它提供 31种专用工具 涵盖8个类别,用于深度网络分析、故障排除和安全评估。更多的工具正在开发中。
建筑
此MCP服务器有两种主要部署模式:
架构1:IDE上的直接MCP客户端(本地)
在本地与IDE(Claude Desktop、VS Code、Cursor、Kiro、Amazon Q Developer)一起运行服务器时,请使用此选项。
graph LR
subgraph IDE ["💻 IDE / AI Client"]
A[AI Model / Agent]
B[MCP Client]
end
subgraph Local ["🖥️ Local Machine"]
C[PCAP Analyzer\nMCP Server]
D[Wireshark/tshark]
E[Network Interfaces]
F[PCAP Files\n./pcap_storage]
end
subgraph Ingestion ["📥 PCAP Ingestion"]
G[Manual File Copy]
H[Live Capture]
end
A B
B |stdio / SSE| C
C D
C E
D --> F
E -->|Live Capture| F
G -->|Copy .pcap files| F
H -->|tcpdump / Wireshark| F
F --> C
style A fill:#f9f,stroke:#333,stroke-width:2px
style B fill:#bbf,stroke:#333,stroke-width:2px
style C fill:#bfb,stroke:#333,stroke-width:4px
style D fill:#fbb,stroke:#333,stroke-width:2px
style E fill:#fbf,stroke:#333,stroke-width:2px
style F fill:#dff,stroke:#333,stroke-width:2px
style G fill:#ffd,stroke:#333,stroke-width:2px
style H fill:#fdf,stroke:#333,stroke-width:2px架构2:DevOps代理与AgentCore网关+Lambda(云)
将其用于整个团队或生产部署,其中DevOps代理通过AgentCore网关调用MCP服务器,并具有完整的入站OAuth2/Cognito和出站IAM授权。
graph TB
subgraph Clients ["👥 Clients"]
A[DevOps Agent\nKiro / AI Workflow]
end
subgraph Auth_In ["🔐 Inbound Auth\n(OAuth2 / Cognito)"]
B[Amazon Cognito\nUser Pool]
C[JWT Token\nValidation]
end
subgraph Gateway ["🌐 AgentCore Gateway"]
D[AgentCore\nGateway Endpoint]
end
subgraph Compute ["⚡ AWS Lambda"]
E[PCAP Analyzer\nMCP Server]
F[tshark\nLambda Layer]
end
subgraph Auth_Out ["🔑 Outbound Auth\n(IAM)"]
G[IAM Role\npcap-analyzer-lambda-role]
end
subgraph Storage ["📦 PCAP Ingestion & Storage"]
H[Amazon S3\npcap-analyzer-storage]
I[AWS SSM\nRun Command]
J[Manual Upload\naws s3 cp]
end
subgraph Network ["🖥️ Target Infrastructure"]
K[EC2 Instances\n/ Servers]
end
A -->|1. POST /oauth2/token| B
B -->|2. Bearer JWT| A
A -->|3. MCP Request +\nAuthorization: Bearer| D
D -->|4. Validate JWT| C
C -->|5. Token Valid ✓| D
D -->|6. Invoke Lambda\nIAM SigV4| E
E --> F
E -->|7. IAM-signed\nAWS API calls| G
G -->|8. Read PCAP from S3| H
I -->|Active Capture:\ntcpdump → s3 cp| H
J -->|Manual Upload| H
K -->|SSM Agent| I
H -->|PCAP files| E
style A fill:#f9f,stroke:#333,stroke-width:2px
style B fill:#ff9,stroke:#333,stroke-width:2px
style C fill:#ff9,stroke:#333,stroke-width:2px
style D fill:#bbf,stroke:#333,stroke-width:3px
style E fill:#bfb,stroke:#333,stroke-width:4px
style F fill:#fbb,stroke:#333,stroke-width:2px
style G fill:#ffd,stroke:#333,stroke-width:2px
style H fill:#dff,stroke:#333,stroke-width:2px
style I fill:#fbf,stroke:#333,stroke-width:2px
style J fill:#dfd,stroke:#333,stroke-width:2px
style K fill:#eee,stroke:#333,stroke-width:2px关键能力
- 🔧 网络接口发现和实时数据包捕获
- 📊 全面的协议分析(TCP、TLS、BGP、DNS、HTTP)
- 🔒 安全分析(TLS握手、证书验证、威胁检测)
- ⚡ 性能指标(延迟、吞吐量、带宽、质量)
- 🔍 特定于协议的故障排除和专家分析
先决条件
- Python 3.10+
- 紫外线 - 安装uv
- 配线架/配线架:
- macOS: brew install wireshark - Linux: sudo apt-get install tshark - Windows:从下载 wireshark.org
数据包捕获权限
| 平台 | 命令 |
|---|---|
| macOS | sudo dseditgroup -o edit -a $(whoami) -t user access_bpf (需要重新启动) |
| Linux | sudo setcap cap_net_raw,cap_net_admin=eip /usr/bin/dumpcap |
| 视窗 | 以管理员身份运行并安装Npcap |
📦 安装方法
选项1:一键安装(光标,VS代码)
| 光标 | VS代码 |
|---|
选项2:Kiro
适用于Kiro用户,在项目级别添加此服务器 .kiro/settings/mcp.json:
{
"mcpServers": {
"pcap-analyzer": {
"command": "uvx",
"args": ["awslabs.pcap-analyzer-mcp-server@latest"]
}
}
}访问 基罗·亚马逊.dev 了解更多信息。
选项3:带Lambda的AgentCore网关
对于AgentCore用户,此服务器可以部署为具有完全入站(OAuth2/Cognito)和出站(IAM)授权的AgentCore网关后面的Lambda函数。
先决条件
- 具有Lambda、Amazon Cognito和AgentCore网关访问权限的AWS帐户
- 为您的项目配置Kiro
- 已配置AWS凭据(
aws configure或环境变量)
______________________________________________________________________
步骤1:创建Lambda执行角色(IAM)
Lambda函数需要一个IAM角色,该角色具有与AgentCore及其代表用户调用的任何AWS服务进行交互的权限。
# Create the trust policy
cat > lambda-trust-policy.json **备注**:添加 `/opt/bin` 到 `ALLOWED_TSHARK_DIRS` 在 `server.py` 对于tshark位于Lambda层的Lambda部署。
______________________________________________________________________
#### 步骤3:部署tshark层(必需)
由于Lambda不包含tshark,您必须通过Lambda层提供它:
Create Lambda layer with tshark
mkdir -p layer/bin cp /path/to/static-tshark layer/bin/tshark # Download static binary for Amazon Linux 2023 chmod +x layer/bin/tshark
cd layer && zip -r ../tshark-layer.zip . && cd ..
Publish layer
aws lambda publish-layer-version \ --layer-name tshark-layer \ --zip-file fileb://tshark-layer.zip \ --compatible-runtimes python3.10 python3.11
Attach layer to the Lambda function
aws lambda update-function-configuration \ --function-name pcap-analyzer-mcp-server \ --layers arn:aws:lambda:REGION:YOUR_ACCOUNT_ID:layer:tshark-layer:1
______________________________________________________________________
#### 步骤4:通过Amazon Cognito配置入站授权--OAuth2
入站授权保护AgentCore网关端点,因此只有经过身份验证的用户才能调用MCP工具。这使用 **亚马逊Cognito用户池** OAuth2。
##### 4a。创建Cognito用户池
aws cognito-idp create-user-pool \ --pool-name pcap-analyzer-user-pool \ --policies '{"PasswordPolicy":{"MinimumLength":8,"RequireUppercase":true,"RequireLowercase":true,"RequireNumbers":true}}' \ --auto-verified-attributes email \ --region us-east-1
Note the UserPoolId from the output, e.g.: us-east-1_XXXXXXXXX
##### 4b。创建资源服务器和应用程序客户端
Create resource server (defines OAuth2 scopes)
aws cognito-idp create-resource-server \ --user-pool-id us-east-1_XXXXXXXXX \ --identifier https://pcap-analyzer.example.com \ --name "PCAP Analyzer MCP Server" \ --scopes ScopeName=read,ScopeDescription="Read access" \ ScopeName=write,ScopeDescription="Write/capture access" \ --region us-east-1
Create app client with client_credentials grant
aws cognito-idp create-user-pool-client \ --user-pool-id us-east-1_XXXXXXXXX \ --client-name pcap-analyzer-gateway-client \ --allowed-o-auth-flows client_credentials \ --allowed-o-auth-scopes pcap-analyzer/read pcap-analyzer/write \ --generate-secret \ --region us-east-1
Note the ClientId and ClientSecret from the output
##### 4c。配置Cognito域名
aws cognito-idp create-user-pool-domain \ --domain pcap-analyzer-auth \ --user-pool-id us-east-1_XXXXXXXXX \ --region us-east-1
Token endpoint: https://pcap-analyzer-auth.auth.us-east-1.amazoncognito.com/oauth2/token
##### 4d。配置AgentCore网关
添加到您的Kiro项目 `.kiro/agentcore-gateway.json`:
{ "mcpServers": { "pcap-analyzer": { "type": "lambda", "functionName": "pcap-analyzer-mcp-server", "region": "us-east-1", "timeout": 300, "inboundAuth": { "type": "oauth2", "provider": "cognito", "userPoolId": "us-east-1_XXXXXXXXX", "clientId": "YOUR_COGNITO_CLIENT_ID", "tokenEndpoint": "https://pcap-analyzer-auth.auth.us-east-1.amazoncognito.com/oauth2/token", "scopes": ["pcap-analyzer/read", "pcap-analyzer/write"], "jwksUri": "https://cognito-idp.us-east-1.amazonaws.com/us-east-1_XXXXXXXXX/.well-known/jwks.json" }, "outboundAuth": { "type": "iam", "roleArn": "arn:aws:iam::YOUR_ACCOUNT_ID:role/pcap-analyzer-lambda-role", "sessionName": "AgentCoreGatewaySession" } } } }
> **令牌验证**:AgentCore网关根据Cognito的JWKS端点自动验证JWT。HTTP 401会拒绝令牌过期、无效或丢失的请求。
______________________________________________________________________
#### 步骤5:配置出站授权--IAM
出站授权控制Lambda函数可以访问的AWS资源。创建范围IAM策略:
cat > pcap-analyzer-outbound-policy.json >Cognito: POST /oauth2/token (client_credentials) Cognito-->>Client: Bearer Token (JWT)
Client->>Gateway: MCP Request + Authorization: Bearer Gateway->>Cognito: Validate JWT (JWKS) Cognito-->>Gateway: Token Valid ✓
Gateway->>Lambda: Invoke (IAM SigV4 signed) Lambda->>S3: GetObject PCAP file (IAM role) S3-->>Lambda: PCAP data Lambda-->>Gateway: MCP Response Gateway-->>Client: MCP Response
______________________________________________________________________
#### 步骤7:PCAP摄入用于云部署
Lambda函数从S3读取PCAP文件。有两种方法可以将文件导入S3:
**选项A——手动上传** (事件后法医分析,现有捕获):
Create S3 bucket (one-time setup)
aws s3 mb s3://pcap-analyzer-storage-YOUR_ACCOUNT_ID --region us-east-1
Upload PCAP files
aws s3 cp capture.pcap s3://pcap-analyzer-storage-YOUR_ACCOUNT_ID/captures/ aws s3 cp ./pcap_files/ s3://pcap-analyzer-storage-YOUR_ACCOUNT_ID/captures/ --recursive --include "*.pcap"
**选项B——通过AWS SSM进行主动捕获** (实时故障排除,无需SSH/开放端口):
Capture packets on EC2 instance for 60 seconds and upload to S3
aws ssm send-command \ --instance-ids "i-XXXXXXXXXXXXXXXXX" \ --document-name "AWS-RunShellScript" \ --parameters '{"commands":[ "CAPTURE_FILE=/tmp/capture-$(date +%Y%m%d-%H%M%S).pcap", "S3_BUCKET=pcap-analyzer-storage-YOUR_ACCOUNT_ID", "timeout 60 tcpdump -i any -w $CAPTURE_FILE -s 0 2>/dev/null || true", "aws s3 cp $CAPTURE_FILE s3://$S3_BUCKET/captures/ --region us-east-1", "rm -f $CAPTURE_FILE" ]}' \ --region us-east-1
Capture only TLS traffic (port 443)
aws ssm send-command \ --instance-ids "i-XXXXXXXXXXXXXXXXX" \ --document-name "AWS-RunShellScript" \ --parameters '{"commands":[ "CAPTURE_FILE=/tmp/capture-tls-$(date +%Y%m%d-%H%M%S).pcap", "S3_BUCKET=pcap-analyzer-storage-YOUR_ACCOUNT_ID", "timeout 120 tcpdump -i eth0 -w $CAPTURE_FILE -s 0 tcp port 443 2>/dev/null || true", "aws s3 cp $CAPTURE_FILE s3://$S3_BUCKET/captures/tls/ --region us-east-1", "rm -f $CAPTURE_FILE" ]}' \ --region us-east-1
Check command status
aws ssm get-command-invocation \ --command-id "COMMAND_ID" \ --instance-id "i-XXXXXXXXXXXXXXXXX" \ --region us-east-1
> **SSM先决条件**:EC2实例必须运行SSM代理(预装在Amazon Linux 2/2023上),并且实例IAM角色必须 `AmazonSSMManagedInstanceCore` + `s3:PutObject` PCAP铲斗上。
||手动上传|SSM运行命令|
|---|---|---|
| **最佳** |现有捕获、离线分析|实时故障排除|
| **SSH/入站端口** |不需要|不需要|
| **实时捕捉** |否|是|
______________________________________________________________________
#### 步骤8:测试集成
Get Cognito access token
TOKEN=$(curl -s -X POST \ https://pcap-analyzer-auth.auth.us-east-1.amazoncognito.com/oauth2/token \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_SECRET&scope=pcap-analyzer/read" \ | jq -r '.access_token')
List available MCP tools via AgentCore Gateway
curl -X POST https://YOUR_AGENTCORE_ENDPOINT/mcp \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","method":"tools/list","params":{},"id":1}'
#### Lambda注意事项
|考虑因素|详细信息|
|--------------|---------|
| **存储** |Lambda有512MB `/tmp` --适用于分析,仅限于捕获|
| **超时** |最大900秒;根据分析复杂度设置(建议默认为300秒)|
| **记忆** |对于大型PCAP文件,建议使用1024MB+|
| **捕捉** |Lambda不支持实时数据包捕获(仅用于分析)|
| **tshark** |必须通过Lambda层提供(不包含在基本运行时中)|
| **冷启动** |对延迟敏感的部署使用Provisioned Concurrency|
| **令牌到期** |Cognito代币将在1小时后过期;在客户端实现令牌刷新|
______________________________________________________________________
### 选项4:手动安装
Using uvx (recommended)
uvx awslabs.pcap-analyzer-mcp-server@latest
Using pip
pip install awslabs.pcap-analyzer-mcp-server awslabs.pcap-analyzer-mcp-server
From source
git clone https://github.com/aws-samples/sample-pcap-analyzer-mcp.git cd sample-pcap-analyzer-mcp uv sync uv run awslabs.pcap-analyzer-mcp-server
## 配置
### 克劳德桌面
**macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
{ "mcpServers": { "pcap-analyzer": { "command": "uvx", "args": ["awslabs.pcap-analyzer-mcp-server@latest"] } } }
**视窗**: `%APPDATA%\Claude\claude_desktop_config.json`
> **备注**:添加 `C:\Program Files\Wireshark` 到 `ALLOWED_TSHARK_DIRS` 在 `server.py`.
{ "mcpServers": { "pcap-analyzer": { "command": "uvx", "args": ["awslabs.pcap-analyzer-mcp-server@latest"], "env": { "WIRESHARK_PATH": "C:\\Program Files\\Wireshark\\tshark.exe" } } } }
### 亚马逊Q开发者
编辑 `~/.aws/amazonq/mcp.json`:
{ "mcpServers": { "pcap-analyzer": { "command": "uvx", "args": ["awslabs.pcap-analyzer-mcp-server@latest"] } } }
### 环境变量
|变量|描述|默认值|
|----------|-------------|---------|
| `PCAP_STORAGE_DIR` |用于存储捕获的PCAP文件的目录| `./pcap_storage` |
| `MAX_CAPTURE_DURATION` |最大捕获持续时间(秒)| `3600` |
| `WIRESHARK_PATH` |tshark可执行文件的路径| `tshark` |
#### `WIRESHARK_PATH` 安全验证
tshark可执行路径在启动时根据一组安全目录进行验证:
- `/usr/bin`, `/usr/local/bin`, `/opt/homebrew/bin`, `/snap/bin`
如果您的tshark位于不同的位置(例如。, `/opt/bin` 对于Lambda层,或 `C:\Program Files\Wireshark\` 在Windows上),将其添加到 `ALLOWED_TSHARK_DIRS` 在 `server.py`.
## 工具
该服务器提供31个工具,分为8类:
Network Interface Management (1 tool)
- `list_network_interfaces` -列出用于数据包捕获的可用网络接口
Packet Capture Management (4 tools)
- `start_packet_capture` -在指定接口上启动数据包捕获
- `stop_packet_capture` -停止活动的数据包捕获会话
- `get_capture_status` -获取所有活动捕获会话的状态
- `list_captured_files` -列出存储目录中所有捕获的pcap文件
Basic PCAP Analysis (4 tools)
- `analyze_pcap_file` -分析pcap文件并生成见解
- `extract_http_requests` -从pcap文件中提取HTTP请求
- `generate_traffic_timeline` -生成具有指定时间间隔的交通时间线
- `search_packet_content` -搜索数据包内容中的特定模式
Network Performance Analysis (2 tools)
- `analyze_network_performance` -从pcap文件分析网络性能指标
- `analyze_network_latency` -分析网络延迟和响应时间
TLS/SSL Security Analysis (6 tools)
- `analyze_tls_handshakes` -分析TLS握手,包括SNI、证书详细信息
- `analyze_sni_mismatches` -分析SNI不匹配并与连接重置相关联
- `extract_certificate_details` -提取SSL证书详细信息并根据SNI进行验证
- `analyze_tls_alerts` -分析指示握手失败的TLS警报消息
- `analyze_connection_lifecycle` -分析从SYN到FIN/RST的完整连接生命周期
- `extract_tls_cipher_analysis` -分析TLS密码套件协商和兼容性问题
TCP Protocol Analysis (5 tools)
- `analyze_tcp_retransmissions` -分析TCP重传和丢包模式
- `analyze_tcp_zero_window` -分析TCP零窗口条件和流量控制问题
- `analyze_tcp_window_scaling` -分析TCP窗口缩放和流量控制机制
- `analyze_packet_timing_issues` -分析数据包定时问题和重复数据包
- `analyze_congestion_indicators` -分析网络拥塞指标和质量指标
Advanced Network Analysis (5 tools)
- `analyze_dns_resolution_issues` -分析DNS解析问题和查询模式
- `analyze_expert_information` -分析Wireshark网络问题专家信息
- `analyze_protocol_anomalies` -分析协议异常和格式错误的数据包
- `analyze_network_topology` -分析网络拓扑和路由信息
- `analyze_security_threats` -分析潜在的安全威胁和可疑活动
Performance & Quality Metrics (4 tools)
- `generate_throughput_io_graph` -以指定的时间间隔生成吞吐量I/O图数据
- `analyze_bandwidth_utilization` -分析带宽利用率和流量模式
- `analyze_application_response_times` -分析应用层响应时间和性能
- `analyze_network_quality_metrics` -分析网络质量指标,包括抖动和丢包
## 用法示例
### 示例1:分析BGP连接问题
"Analyze bgp.pcap and explain why the BGP connection is failing"
服务器检查BGP OPEN消息、AS号、连接生命周期,并识别配置不匹配。
### 示例2:实时数据包捕获
"Capture network traffic on eth0 for 60 seconds and analyze for security threats"
### 示例3:TLS故障排除
"Examine TLS handshakes in https-traffic.pcap and identify any certificate issues"
### 示例4:TCP性能分析
"Check for TCP retransmissions and analyze connection quality in the packet capture"
### 示例5:综合分析
"Give me a complete analysis of all protocols and traffic patterns in network-dump.pcap"
## 故障排除
tshark not found
Verify installation
tshark --version
Install if missing
brew install wireshark # macOS sudo apt-get install tshark # Linux
Windows: Download from wireshark.org and add to PATH
如果安装了tshark,但您看到 `tshark path ... is not in allowed directories`,将tshark的父目录添加到 `ALLOWED_TSHARK_DIRS` 在 `server.py`.
Permission denied during capture
**macOS**: `sudo dseditgroup -o edit -a $(whoami) -t user access_bpf` (需要重新启动)
**Linux**: `sudo setcap cap_net_raw,cap_net_admin=eip /usr/bin/dumpcap`
**视窗**:以管理员身份运行
PCAP file not found
- 列出文件 `list_captured_files`
- 使用相对路径: `bgp.pcap` 或绝对路径: `/full/path/file.pcap`
- 验证 `.pcap` 扩展
Analysis returns empty results
- PCAP可能不包含分析的协议
- 显示筛选器可能限制过多
- 首先运行基本分析: `analyze_pcap_file`
## 发展
Clone repository
git clone https://github.com/aws-samples/sample-pcap-analyzer-mcp.git cd sample-pcap-analyzer-mcp
Install dependencies
uv sync
Run server
uv run awslabs.pcap-analyzer-mcp-server
Run tests
uv run pytest
## 贡献
我们欢迎社区捐款!请看 [贡献.md](CONTRIBUTING.md) 作为指导方针。
## 许可证
此库根据MIT-0许可证获得许可。请参阅 [许可证](LICENSE) 文件。
## 免责声明
提供的示例代码没有任何保证,不建议您将其用于生产级工作负载。其目的是提供构建和学习的内容。请务必阅读许可条款。
版权所有2024 Amazon.com,股份有限公司或其附属公司。保留所有权利。