Skip to main content
Glama
README.md
# sakurafrp-mcp

**English** | [简体中文](README.zh-CN.md)

An MCP server for SakuraFrp (樱花内网穿透 / Sakura Frp reverse proxy). Zero dependencies, single file, stdio transport.

Lets an AI manage your SakuraFrp tunnels directly: check traffic, browse nodes, create/edit/delete tunnels, and control the local launcher service.

## Why this exists

SakuraFrp tunnel configuration lives only in the cloud console. Changing a tunnel's local port means either clicking through the web UI or hand-writing curl commands. This MCP turns those operations into structured tools an AI can call.

Several non-obvious gotchas, all handled in the implementation:

| Gotcha | Symptom | How it's handled |
|---|---|---|
| Editing online doesn't take effect | `POST /v4/tunnel/edit` returns `{}`, cloud fields change, but frpc keeps running the old config | `edit_tunnel` forces stop → edit → start → verify |
| `online: true` lies | Only means frpc is alive, not that it picked up the new config | Verification looks at real public responses, not cloud fields |
| `ids` must be a string | Passing `[30049061]` triggers a server-side `ClassCastException` | Always `String(id)` |
| Singular vs plural paths differ | `/v4/tunnels` creates, `/v4/tunnel/edit` operates on one | Calls the actual paths |
| Local gRPC `UpdateTunnel` has side effects | It wipes `auto_start_tunnels` and drops every tunnel | Not exposed |

## Tools (12)

### Read-only

| Tool | Description |
|---|---|
| `list_tunnels` | Tunnels: id/name/node/node-name/type/local/remote/online/auto-start |
| `user_info` | Traffic usage and quota, speed limit, tunnel quota, realname level, VIP expiry |
| `nodes` | All available nodes with host and description |
| `local_status` | Process liveness, frpc TCP connections, `auto_start_tunnels`, local port probes (auto-detects http/https) |
| `logs` | Tail of the launcher log, filterable by tunnel name |

### Write operations (all require `confirm: true`)

| Tool | Description |
|---|---|
| `create_tunnel` | Create a tunnel. `name` must be 3-20 chars of letters/digits/underscore; empty `remote` auto-allocates |
| `edit_tunnel` | Modify a tunnel. Strictly four steps: stop → edit → start → verify |
| `delete_tunnel` | Delete a tunnel. Stops first, auto-rolls back on failure, optional `name` cross-check |
| `start_tunnel` | Start a tunnel (adds to `auto_start_tunnels` + restarts service) |
| `stop_tunnel` | Stop a tunnel |
| `restart_service` | Restart `SakuraFrpService` |
| `set_auto_start` | Replace `auto_start_tunnels` wholesale |

Every write operation backs up the config to `mcp-backups/` beside it before executing.

## Installation

### Requirements

- Node.js >= 18 (uses built-in `fetch`)
- [SakuraFrp Launcher](https://www.natfrp.com/) installed on Windows (provides `SakuraFrpService`)
- A SakuraFrp access key (panel → user info → view access key)

### Clone

```bash
git clone https://github.com/arstoya/sakurafrp-mcp.git
cd sakurafrp-mcp
```

No `npm install` needed — zero dependencies.

### DeepSeek Harness

Append to `cordis.patch.yml`:

```yaml
- insert:
    - id: mcp-sakurafrp
      name: '@deepseek-ai/dsh-mcp-client'
- id: mcp-sakurafrp
  disabled: false
  config:
    serverName: sakurafrp
    transport: stdio
    command: 'C:\Program Files\nodejs\node.exe'
    args:
      - 'D:\path\to\sakurafrp-mcp\server.mjs'
    toolCallTimeoutMs: 60000
    failOnStartupError: false
    reconnect:
      enabled: true
      initialDelayMs: 500
      maxDelayMs: 30000
      maxAttempts: 10
    env:
      SAKURA_CONFIG: 'C:\ProgramData\SakuraFrpService\config.json'
      SAKURA_LOG_DIR: 'C:\ProgramData\SakuraFrpService\Logs'
```

Note: `config` is replaced wholesale, not deep-merged — include every key you need.

### Claude Desktop

`claude_desktop_config.json`:

```json
{
  "mcpServers": {
    "sakurafrp": {
      "command": "node",
      "args": ["D:\\path\\to\\sakurafrp-mcp\\server.mjs"],
      "env": {
        "SAKURA_CONFIG": "C:\\ProgramData\\SakuraFrpService\\config.json"
      }
    }
  }
}
```

## Environment variables

| Variable | Default | Description |
|---|---|---|
| `SAKURA_CONFIG` | `C:\ProgramData\SakuraFrpService\config.json` | Launcher config; token is read from here |
| `SAKURA_LOG_DIR` | `C:\ProgramData\SakuraFrpService\Logs` | Log directory |
| `SAKURA_SERVICE` | `SakuraFrpService` | Windows service name |
| `SAKURA_PWSH` | auto-detected | PowerShell executable. Default order: `C:\Program Files\PowerShell\7\pwsh.exe` → `7-preview` → `pwsh` on PATH → `powershell.exe` |
| `SAKURA_API_BASE` | `https://api.natfrp.com/v4` | Cloud API base |
| `SAKURA_HTTP_TIMEOUT` | `15000` | Per-request timeout in ms |

**The token is read from `config.json` only — no second copy is stored anywhere.**

## Why config changes require stopping the tunnel first

This is the most important piece of knowledge in this project. Measured results:

```
# BAD: edit while running
edit: local_port 28092 -> 28920
API returns {}
Cloud reads back: local_port=28920, online=true     <- looks successful
Public probe: HTTPS(28920) -> 000, HTTP(28092) -> 501   <- did not take effect at all

# GOOD: stop, edit, start
1. Remove from auto_start_tunnels + Restart-Service -> online=false
2. edit
3. Add back to auto_start_tunnels + Restart-Service -> online=true
Public probe: HTTPS(28920) -> 200                     <- actually works
```

frpc reads its config at process start. The cloud `edit` only updates a database row; it does not hot-reload. Only restarting the service re-launches frpc with the new config.

That's why `edit_tunnel` refuses the "edit without restart" shortcut — it would hand the AI a false success signal.

## A sharp port trap

A tunnel's `local_port` may point at **plain HTTP** or at **self-signed HTTPS**. SakuraFrp's mainland China nodes intercept plain HTTP (returning `501 Not Implemented` with `Server: SakuraFrp`).

If your service speaks HTTPS (Jellyfin's 8920, for instance), the tunnel must target that HTTPS port, not 8096. `local_status` tries http then https automatically and reports which one hit in the `scheme` field.

## Protocol details (for further development)

The local named pipe `\\.\pipe\SakuraFrpService3` speaks gRPC over HTTP/2, but **server reflection is not registered**. Full proto recovered from the binary:

```protobuf
service NatfrpService {          // path /NatfrpService/<Method>
  rpc UpdateTunnel(TunnelUpdate) returns (TunnelUpdate);
  rpc UpdateConfig(ServiceConfig) returns (Empty);
  rpc AuthTunnel(TunnelAuthRequest) returns (Empty);
  rpc ReloadTunnels(Empty) returns (Empty);
  // ...
}

message Tunnel {
  int64  id         = 1;
  int32  node       = 2;
  string name       = 3;
  string type       = 4;
  string note       = 5;
  string extra      = 6;
  int32  status     = 7;
  bool   enabled    = 8;
  State  state      = 9;   // IDLE/STARTED/RUNNING/STOPPING/CRASHED
  string local_ip   = 10;
  int32  local_port = 11;
  string remote     = 12;
  int32  frpc_state = 13;
}

message TunnelUpdate {
  Action action = 1;  // Unknown=0 Add=1 Update=2 Delete=3 Clear=4 Edit=5
  Tunnel tunnel = 2;
}
```

**Warning**: `UpdateTunnel(action=Update)` only mutates local design state, does not push to the cloud, and **wipes `auto_start_tunnels` from `config.json`**, dropping every tunnel. This project does not expose it.

## Cloud API cheat sheet

| Operation | Endpoint | Notes |
|---|---|---|
| List tunnels | `GET /v4/tunnels` | |
| Account info | `GET /v4/user/info` | `traffic: [used, quota]` |
| Node list | `GET /v4/nodes` | Returns a map keyed by node id |
| Create tunnel | `POST /v4/tunnels` | Requires name/type/node/local_ip/local_port |
| Edit tunnel | `POST /v4/tunnel/edit` | Whole-object overwrite semantics |
| Delete tunnel | `POST /v4/tunnel/delete` | Body `{"ids":"<id>"}` — **a string, not an array** |

Singular paths (`/v4/tunnel/*`) operate on one tunnel; plural (`/v4/tunnels`) operates on the collection. Mixing them up yields 404s all the way down.

## Development

```bash
npm test             # run all unit tests (27, zero network calls)
npm run check        # syntax check
npm start            # run directly in stdio mode
```

Tests come in two layers:

- `test/unit.test.mjs` — pure logic: tool registration completeness, tunnel-name rules, cloud payload shape, timestamp precision, schema self-consistency
- `test/protocol.test.mjs` — JSON-RPC dispatch: initialize / tools/list / error codes / the confirm gate on write tools

CI runs on GitHub Actions across Node 18/20/22 × Ubuntu/Windows — six combinations. A separate `guard` job rejects commits containing hardcoded tokens or real account/tunnel ids.

After editing `server.mjs`, the running MCP child process still holds the old code. In DSH:

```
plugin_manager action=set_plugin target="include:mcp-sakurafrp" enabled=false
plugin_manager action=set_plugin target="include:mcp-sakurafrp" enabled=true
```

No need to restart the whole host.

## Known limitations

- **Windows only.** `restart_service` relies on PowerShell's `Restart-Service`, and the default config paths are Windows ones. Service-control tools fail loudly rather than silently on other platforms.
- **`edit_tunnel` interrupts the tunnel.** It must stop before editing. Other tunnels under the same service are briefly interrupted too, because the service restarts as a whole.
- **Backups are never pruned.** Each write operation leaves a file in `mcp-backups/`; clean them up manually.

## License

MIT

TDQS

A3.8/5.0

Scored across 12 tools

Disambiguation4/5

Read-only tools (list_tunnels, user_info, nodes, local_status, logs) and per-tunnel write tools (start/stop/create/edit/delete_tunnel) are clearly separable. The one fuzzy boundary is start_tunnel/stop_tunnel versus set_auto_start, since start/stop are implemented by mutating auto_start_tunnels and all three restart the service — the descriptions help but an agent could still pick wrongly for 'permanently enable one tunnel'.

Naming Consistency3/5

Write tools follow a clean verb_noun CRUD pattern (create_tunnel/edit_tunnel/delete_tunnel/start_tunnel/stop_tunnel/restart_service/set_auto_start). Read tools break it: list_tunnels uses a list_ verb while nodes, logs, user_info and local_status are bare nouns, so there are two competing conventions.

Tool Count5/5

12 tools is well within the sweet spot and each maps to a distinct operation in the tunnel lifecycle (inspect, start/stop, CRUD, service control). No redundant or filler tools; read-only diagnostics and write actions are balanced.

Completeness4/5

Full tunnel lifecycle (list, create, edit, delete, start, stop, auto-start batch) plus account, nodes, service/process and log diagnostics covers the domain well. Minor gaps: no get_tunnel by id for single-tunnel detail, no way to start a tunnel without it being added to auto_start, and no per-tunnel traffic/latency stats.

Maintenance

ActivityMaintained
ResponsivenessNo recent community issues