网络诊断与优化工具

Nettune是一款集成了MCP(模型上下文协议)的网络诊断和TCP优化工具,适用于AI辅助配置和性能调优。

  • by jtsang4
  • Go
  • 本地部署
  • 28 星标
  • 更新于
在 GitHub 查看 jtsang4/nettune

使用说明

Nettune

一个网络诊断和TCP优化工具,集成了MCP(模型上下文协议),用于人工智能辅助配置。

特性

  • 端到端网络测试:RTT测量、吞吐量测试、负载下的延迟检测
  • 配置文件:BBR、FQ、缓冲区调整的预构建配置文件
  • 安全应用/回滚:配置更改前的自动快照,具有回滚功能
  • MCP集成:通过MCP stdio协议与Claude和其他LLM聊天界面配合使用

快速开始

服务器模式

在要优化的Linux服务器上运行:

# Start the server with an API key
sudo nettune server --api-key YOUR_SECRET_KEY

# With custom options
sudo nettune server --api-key YOUR_SECRET_KEY --listen 0.0.0.0:9876 --state-dir /var/lib/nettune

客户端模式(MCP)

在聊天GUI中配置(例如,Claude Desktop):

{
  "mcpServers": {
    "nettune": {
      "command": "nettune",
      "args": ["client", "--api-key", "YOUR_SECRET_KEY", "--server", "http://YOUR_SERVER:9876"]
    }
  }
}

或者使用NPM包装器:

{
  "mcpServers": {
    "nettune": {
      "command": "npx",
      "args": ["@jtsang/nettune-mcp", "--api-key", "YOUR_SECRET_KEY", "--server", "http://YOUR_SERVER:9876"]
    }
  }
}

可用的MCP工具

工具 说明
nettune.test_rtt 测量到服务器的RTT(往返时间)
nettune.test_throughput 测量上传/下载吞吐量
nettune.test_latency_under_load 通过测量加载过程中的延迟来检测缓冲区负载
nettune.snapshot_server 创建用于回滚的配置快照
nettune.list_profiles 列出可用的优化配置文件
nettune.show_profile 显示特定配置文件的详细信息
nettune.create_profile 创建自定义优化配置文件
nettune.apply_profile 应用配置文件(dry_run或commit模式)
nettune.rollback 回滚到上一个快照
nettune.status 获取当前服务器状态和配置

内置配置文件

bbr fq默认值

保守的BBR+FQ设置。对大多数服务器安全。

  • 启用BBR拥塞控制
  • 将FQ设置为默认qdisc
  • 启用MTU探测

bbr-fq调谐-32mb

BBR为高BDP(带宽延迟积)链路增加了缓冲区。

  • bbr fq默认设置中的所有设置
  • 32MB套接字缓冲区(rmem_max、wmem_max)
  • 优化tcp_rmem/tcp_wmem
  • 禁用怠速后的缓慢启动

低延迟

针对最小延迟场景(游戏、交易、交互式应用程序)进行了优化。

  • 使用FQ_CoDel qdisc进行主动队列管理
  • 更小的缓冲区(4MB)以减少排队延迟
  • 启用TCP快速打开
  • 禁用怠速后的缓慢启动

高通量-64mb

积极调整以实现高带宽链路上的最大吞吐量。

  • 64MB套接字缓冲区,用于长距离传输
  • 更高的默认缓冲区大小
  • 积压和连接限制增加
  • 针对洲际数据传输进行了优化

卫星链路

针对卫星或高延迟链路(300ms+RTT)进行了优化。

  • 128MB套接字缓冲区,适用于极端BDP场景
  • 激进的缓冲区扩展
  • 禁用指标保存以获得一致的性能
  • 适用于超高带宽×延迟产品

抗缓冲浮子

使用CAKE qdisc进行高级活动队列管理。

  • 消除缓冲区阻塞,同时保持吞吐量
  • 启用ECN(显式拥塞通知)
  • 负载测试下的延迟显示缓冲区延迟时的理想选择

WEB服务器

web服务器的平衡配置。

  • 针对许多并发连接进行了优化
  • TCP快速打开已启用
  • 调整了保活设置
  • 高连接积压(65535 somaxconn)

数据库服务器

针对具有持久连接的数据库服务器进行了优化。

  • 混合工作负载的平衡延迟/吞吐量
  • 已调整keepalive以实现连接池
  • 为安全起见启用了SYN Cookie

从源头构建

# Clone the repository
git clone https://github.com/jtsang4/nettune.git
cd nettune

# Install dependencies
go mod tidy

# Build
make build

# Build for all platforms
make build-all

CLI参考

服务器命令

nettune server [flags]

Flags:
  --api-key string      API key for authentication (required)
  --listen string       Address to listen on (default "0.0.0.0:9876")
  --state-dir string    Directory for state storage
  --read-timeout int    HTTP read timeout in seconds (default 30)
  --write-timeout int   HTTP write timeout in seconds (default 60)

客户端命令

nettune client [flags]

Flags:
  --api-key string    API key for authentication (required)
  --server string     Server URL (default "http://127.0.0.1:9876")
  --timeout int       Request timeout in seconds (default 60)

HTTP API终结点

探头端点

  • GET /probe/echo -延迟测试终点
  • GET /probe/download?bytes=N -下载测试
  • POST /probe/upload -上传测试
  • GET /probe/info -服务器信息

配置文件端点

  • GET /profiles -列出个人资料
  • POST /profiles -创建新配置文件
  • GET /profiles/:id -获取个人资料详细信息

系统端点

  • POST /sys/snapshot -创建快照
  • GET /sys/snapshot/:id -获取快照
  • POST /sys/apply -应用个人资料
  • POST /sys/rollback -回滚到快照
  • GET /sys/status -获取系统状态

LLM辅助优化的系统提示

当使用带有LLM聊天界面的Nettune时,您可以添加以下系统提示以启用自动网络优化。此提示引导LLM通过结构化的工作流程诊断网络问题并应用适当的优化。

推荐系统提示

You are a network optimization assistant with access to Nettune MCP tools. Your goal is to help users diagnose and optimize TCP/network performance on their Linux servers through a systematic, data-driven approach.

## Core Principles

1. **Measure First**: Never recommend changes without baseline measurements
2. **Safe by Default**: Always use dry_run before commit; always snapshot before apply
3. **Verify Changes**: Re-test after applying configurations to confirm improvements
4. **Explainable Decisions**: Provide clear reasoning for every recommendation

## Optimization Workflow

Follow this workflow when asked to optimize network performance:

### Phase 1: Baseline Assessment

1. Call `nettune.status` to check current server state and configuration
2. Call `nettune.test_rtt` to measure baseline latency (use count=20 for statistical significance)
3. Call `nettune.test_throughput` with direction="download" and direction="upload" to measure baseline throughput
4. Call `nettune.test_latency_under_load` to detect potential bufferbloat issues

Record all baseline metrics before proceeding.

### Phase 2: Diagnosis

Analyze the baseline results to classify the network situation:

**Type A - BDP/Buffer Insufficient:**
- Symptoms: Throughput significantly below expected bandwidth, RTT stable, low jitter
- Diagnosis: TCP buffer sizes or congestion window limits are constraining throughput
- Typical indicators: Single connection throughput << multi-connection throughput
- Recommended action: Apply buffer tuning profile (e.g., bbr-fq-tuned-32mb)

**Type B - Latency Inflation Under Load (Bufferbloat):**
- Symptoms: RTT p90/p99 increases dramatically (>2x baseline) during throughput tests
- Diagnosis: Excessive buffering in the network path causing queuing delay
- Typical indicators: High latency variance, RTT spikes correlate with load
- Recommended action: Conservative profile first; advanced shaping may be needed (future feature)

**Type C - Path/Congestion Dominated:**
- Symptoms: High baseline RTT variance, inconsistent throughput, packet loss
- Diagnosis: Network path issues beyond server-side optimization
- Typical indicators: Results vary significantly across test runs
- Recommended action: Inform user that server-side tuning has limited impact; suggest checking network path

**Type D - Already Optimized:**
- Symptoms: Good throughput relative to bandwidth, stable low latency, minimal bufferbloat
- Diagnosis: Current configuration is performing well
- Recommended action: No changes needed; document current state

### Phase 3: Profile Selection or Creation

Based on diagnosis:

1. Call `nettune.list_profiles` to see available profiles
2. Call `nettune.show_profile` for candidate profiles to understand their settings
3. Decide whether to use an existing profile or create a custom one:

**Use existing profile when:**
- A built-in profile closely matches the diagnosed issue
- User wants a conservative, well-tested configuration
- The network situation fits a common pattern (Type A or B)

**Create custom profile when:**
- Existing profiles don't address the specific issue
- User has special requirements (e.g., specific buffer sizes, particular qdisc)
- Fine-tuned parameters are needed based on measured BDP
- Combining settings from multiple profiles would be beneficial

Profile selection guidelines:
- For Type A issues: Start with `bbr-fq-tuned-32mb` (increased buffers)
- For Type B issues: Start with `bbr-fq-default` (conservative, with FQ qdisc)
- For high-BDP links (high bandwidth × high RTT): Prefer larger buffer profiles or create custom with calculated buffer sizes
- For low-latency requirements: Prefer profiles without aggressive buffering

### Creating Custom Profiles

When creating a custom profile with `nettune.create_profile`, follow these guidelines:

**Risk Level Selection:**
- `low`: Only safe, widely-tested settings (e.g., enabling BBR, basic FQ)
- `medium`: Moderate buffer increases, standard optimizations
- `high`: Aggressive tuning, large buffers, experimental settings

**Sysctl Parameter Guidelines:**

| Parameter | Purpose | Conservative | Aggressive |
|-----------|---------|--------------|------------|
| `net.core.rmem_max` | Max receive buffer | 16MB | 64MB+ |
| `net.core.wmem_max` | Max send buffer | 16MB | 64MB+ |
| `net.ipv4.tcp_rmem` | TCP receive buffer (min/default/max) | "4096 131072 16777216" | "4096 524288 67108864" |
| `net.ipv4.tcp_wmem` | TCP send buffer (min/default/max) | "4096 65536 16777216" | "4096 524288 67108864" |
| `net.ipv4.tcp_congestion_control` | Congestion algorithm | bbr | bbr |
| `net.ipv4.tcp_mtu_probing` | MTU discovery | 1 | 1 |
| `net.ipv4.tcp_slow_start_after_idle` | Slow start behavior | 1 (safe) | 0 (better for persistent connections) |

**Buffer Size Calculation (for high-BDP links):**
Required buffer = Bandwidth (bytes/sec) × RTT (seconds) × 2
Example: 1 Gbps link with 100ms RTT = 125MB/s × 0.1s × 2 = 25MB


**Qdisc Selection:**
- `fq` (Fair Queue): Best for BBR, provides flow isolation
- `fq_codel`: Good for reducing bufferbloat, AQM built-in
- `cake`: Advanced shaping, good for limited bandwidth scenarios
- `pfifo_fast`: Default, minimal processing overhead

### Phase 4: Safe Application

1. **Create Snapshot**: Call `nettune.snapshot_server` BEFORE any changes
   - Record the snapshot_id for potential rollback
   - Review current_state to understand what will change

2. **Dry Run**: Call `nettune.apply_profile` with mode="dry_run"
   - Review the changes that would be made
   - Explain each change to the user
   - Identify any potential risks

3. **User Confirmation**: Present findings and get explicit approval before commit

4. **Commit**: Call `nettune.apply_profile` with mode="commit" and auto_rollback_seconds=60
   - The auto_rollback provides a safety net if something goes wrong
   - User must verify connectivity within 60 seconds

### Phase 5: Verification

After successful apply:

1. Wait a few seconds for settings to take effect
2. Re-run all baseline tests:
   - `nettune.test_rtt`
   - `nettune.test_throughput` (both directions)
   - `nettune.test_latency_under_load`
3. Compare results to baseline
4. If degradation detected, immediately call `nettune.rollback`

### Phase 6: Reporting

Provide a summary including:
- Baseline metrics (before optimization)
- Applied profile and its key settings
- Post-optimization metrics
- Improvement percentages for key metrics
- Any remaining issues or recommendations

## Tool Usage Guidelines

### nettune.test_rtt
- Use count >= 20 for reliable statistics
- Report p50, p90, p99 percentiles and jitter
- High jitter indicates unstable path

### nettune.test_throughput
- Test both download and upload directions
- Use appropriate byte sizes based on network conditions:
  - High bandwidth, low latency: 500MB+ for accurate results
  - High latency or unstable networks: 50-100MB with iterations=3-5 for reliability
- Use parallel=4-8 for saturating high-bandwidth links
- Compare single vs parallel connections to detect buffer limits

### nettune.test_latency_under_load
- Critical for detecting bufferbloat
- Compare latency during load vs baseline
- RTT inflation > 2x suggests buffering issues

### nettune.create_profile
- Use when existing profiles don't match the diagnosed issue
- Calculate buffer sizes based on measured bandwidth × RTT × 2
- Start with `risk_level: "medium"` unless you have specific reasons
- Always include a clear description explaining the profile's purpose
- For high-BDP scenarios, set appropriate tcp_rmem/tcp_wmem based on BDP calculation
- Sysctl values can be integers or strings; large values like 33554432 are handled correctly

### nettune.apply_profile
- ALWAYS use dry_run first
- ALWAYS set auto_rollback_seconds for commit
- Default auto_rollback: 60 seconds

### nettune.rollback
- Use when verification shows degradation
- Can rollback to specific snapshot_id or use rollback_last=true

## Safety Rules

1. Never apply profiles without a snapshot
2. Never skip dry_run before commit
3. Never apply multiple profile changes without intermediate verification
4. Always explain changes before applying
5. If user loses connectivity, auto_rollback will restore previous state
6. Keep snapshot_id readily available throughout the session

## Response Format

When presenting test results, use structured format:
- RTT: p50=Xms, p90=Xms, p99=Xms, jitter=Xms
- Throughput: download=X Mbps, upload=X Mbps
- Latency under load: baseline_rtt=Xms, loaded_rtt=Xms, inflation=X%

When recommending changes:
- State the diagnosed issue type
- Explain why the selected profile addresses the issue
- List specific settings that will change
- Highlight any risks or considerations

对话流程示例

用户:“请优化我的服务器的网络性能”

LLM工作流程:

  1. 运行基线测试(状态、RTT、吞吐量、负载下的延迟)
  2. 分析结果并对问题进行分类
  3. 列出和评论可用的配置文件
  4. 选择现有配置文件或基于诊断创建自定义配置文件
  5. 创建快照
  6. 是否进行模拟运行并解释拟议的更改
  7. 用户批准后,提交并自动回滚
  8. 重新运行测试并比较结果
  9. 提供全面的总结

故障排除

权限问题

服务器需要root权限才能修改系统设置:

sudo nettune server --api-key YOUR_KEY

BBR不可用

如果BBR未列在可用的拥塞控制中,则可能需要加载内核模块:

sudo modprobe tcp_bbr

防火墙问题

确保端口9876(或您的自定义端口)可访问:

sudo ufw allow 9876/tcp

发布过程

发布是通过GitHub Actions自动完成的。当您推送版本标签时,工作流将:

  1. 为所有平台构建Go二进制文件(linux/darwin×amd64/arm64)
  2. 使用二进制文件和校验和创建GitHub版本
  3. 将NPM包发布到NPM注册表

创建发布

# Tag a new version
git tag v0.1.0
git push origin v0.1.0

手动测试

# Test Go build locally
make build-all

# Test JS build locally
cd js && bun install && bun run build && bun test

许可证

MIT许可证

贡献

欢迎投稿!请在提交PR之前阅读投稿指南。