Compare commits

...
5 Commits
Author SHA1 Message Date
kory 78d3ee6527 fix: repair one-click installer
Release / Build & Release (push) Canceled after 0s
2026-10-02 14:52:05 +08:00
kory 5551f69b17 test: stabilize local session lifecycle timing 2026-10-02 14:35:32 +08:00
kory 650dc7186e docs: document constrained diagnostic mode
Release / Build & Release (push) Canceled after 0s
2026-10-02 14:34:30 +08:00
kory 5e6281ae99 feat: add constrained read-only diagnostics 2026-10-02 14:32:40 +08:00
kory 2a072f9cc9 fix: detach local sessions from request context
Release / Build & Release (push) Canceled after 0s
2026-10-02 14:18:24 +08:00
18 changed files with 273 additions and 13 deletions
+1 -1
View File
@@ -111,7 +111,7 @@ Tool Registry 首先确定操作风险:
## 🤖 当前 MCP 能力
目前共 **11 个 MCP Tools**:
目前共 **12 个 MCP Tools**:
| Tool | Risk | 功能 |
| :--- | :--- | :--- |
+11
View File
@@ -152,6 +152,17 @@ func run(hub, name, token string, insecure bool) error {
func handle(writeJSON func(cluster.Message) error, exec executor.Local, mcpRuntime *cluster.MCPRuntime, sessions *executor.SessionManager, msg cluster.Message) error {
switch msg.Action {
case "diagnostic_command":
var p executor.DiagnosticRequest
if err := decodePayload(msg.Payload, &p); err != nil {
return sendError(writeJSON, msg.ID, err)
}
v, err := executor.Diagnostic(context.Background(), p)
if err != nil {
return sendError(writeJSON, msg.ID, err)
}
return writeJSON(cluster.Message{ID: msg.ID, Status: "success", Payload: v})
case "mcp_list":
return writeJSON(cluster.Message{ID: msg.ID, Status: "success", Payload: mcpRuntime.List()})
case "mcp_test":
+1 -1
View File
@@ -195,7 +195,7 @@ Agent 启动后主动连接 Hub,并在设备列表中显示为 `online`。
本地 stdio 使用 `vps-commander-mcp-stdio`。
当前共 11 个 MCP tools,详见 `docs/MCP_INTEGRATION.md`。
当前共 12 个 MCP tools,详见 `docs/MCP_INTEGRATION.md`。
---
+2 -3
View File
@@ -133,8 +133,8 @@ install_hub() {
read -rp "请输入监听端口 (默认 9521): " HUB_PORT
HUB_PORT=${HUB_PORT:-9521}
GEN_API_KEY=$(head -c 24 /dev/urandom | xxd -p)
GEN_PASS=$(head -c 16 /dev/urandom | xxd -p)
GEN_API_KEY=$(od -An -N24 -tx1 /dev/urandom | tr -d ' \n')
GEN_PASS=$(od -An -N16 -tx1 /dev/urandom | tr -d ' \n')
read -rp "请输入 API Key (默认随机生成): " API_KEY
API_KEY=${API_KEY:-$GEN_API_KEY}
@@ -145,7 +145,6 @@ install_hub() {
cat << ENV > "${CONF_DIR}/hub.env"
VPS_COMMANDER_API_KEY=${API_KEY}
VPS_COMMANDER_WEB_PASSWORD=${WEB_PASS}
ENV
ENV
chmod 0600 "${CONF_DIR}/hub.env"
+4 -1
View File
@@ -88,6 +88,7 @@ Agent 返回结果后,Hub 完成审计并将结果返回 HTTP/MCP 调用方。
| :--- | :--- |
| Low | read_file、read_multiple_files、list_directory、file_info、search、list_processes |
| Medium | edit_block、write_file、create_directory、move_file、mcp_call |
| Low | diagnostic_command:严格白名单只读诊断(Docker、systemd、journal、网络监听、磁盘、内存、uptime) |
| High | exec_command、start_process、interact_with_process、kill_process、force_terminate |
### 4.3 Policy Snapshot
@@ -121,7 +122,7 @@ kill / terminate 使用 Session 内部进程句柄,不接受客户端任意 PI
## 六、MCP 架构
当前 MCP 共 11 个工具:
当前 MCP 共 12 个工具:
1. `list_devices`
2. `exec_command`
3. `read_file`
@@ -129,6 +130,8 @@ kill / terminate 使用 Session 内部进程句柄,不接受客户端任意 PI
5. `create_directory`
6. `move_file`
7. `list_processes`
8. `diagnostic_command`:严格白名单的只读系统诊断;
8. `edit_block`
9. `write_file`
10. `list_agent_mcp`
+1 -1
View File
@@ -86,7 +86,7 @@ Hub 根据 Credential 建立 Canonical Device Identity。
Server version:`1.2.0`。
Protocol Version:`2024-11-05`。
当前工具共 11 个:
当前工具共 12 个:
`list_devices`、`exec_command`、`read_file`、`read_multiple_files`、`create_directory`、`move_file`、`list_processes`、`edit_block`、`write_file`、`list_agent_mcp`、`call_agent_mcp`。
远程 transport:legacy HTTP + SSE。
+1 -1
View File
@@ -40,7 +40,7 @@ VPS-Commander 是自托管、多节点、AI Agent 友好的 Linux 运维控制
## 三、当前 MCP 基线
11 个工具:
12 个工具:
`list_devices`、`exec_command`、`read_file`、`read_multiple_files`、`create_directory`、`move_file`、`list_processes`、`edit_block`、`write_file`、`list_agent_mcp`、`call_agent_mcp`。
远程:legacy SSE。
+8 -1
View File
@@ -20,7 +20,7 @@ VPS-Commander 当前提供两种 MCP 接入模式:
---
## 二、当前支持的 11 大 MCP Tools
## 二、当前支持的 12 大 MCP Tools
| Tool 名称 | 风险等级 | 参数/功能说明 |
| :--- | :--- | :--- |
@@ -31,6 +31,7 @@ VPS-Commander 当前提供两种 MCP 接入模式:
| `create_directory` | Medium | 创建目录 |
| `move_file` | Medium | 移动/重命名文件 |
| `list_processes` | Low | 查看进程 |
| `diagnostic_command` | Low | 严格白名单只读诊断,不接受任意 Shell |
| `edit_block` | Medium | 唯一匹配 + 原子写回 |
| `write_file` | Medium | 创建或覆写文件 |
| `list_agent_mcp` | Low | 查询 Agent MCP 服务 |
@@ -145,6 +146,12 @@ API Key 不应提交到 Git 仓库。
### 6.6 list_processes
- `device` 可选。
### 6.7 diagnostic_command
- `device`、`action` 必填。
- `action` 仅允许:`docker_ps`、`docker_logs`、`docker_inspect`、`systemctl_status`、`journalctl`、`ss_listen`、`df`、`free`、`uptime`。
- 这是 Low 风险只读诊断通道,不接受任意 Shell;Medium 模式可使用,但 `exec_command` 仍保持 High。
### 6.7 edit_block
- `device`、`path`、`old_text`、`new_text`。
- `old_text` 必须唯一匹配。
+1 -1
View File
@@ -28,7 +28,7 @@
## 二、MCP 当前能力
当前共 11 个 Tools:
当前共 12 个 Tools:
1. `list_devices`
2. `exec_command`
3. `read_file`
+1 -1
View File
@@ -851,7 +851,7 @@ func (s *Server) processSession(w http.ResponseWriter, r *http.Request) {
}
}
var sess *executor.Session
sess, err = s.LocalSessions.Start(ctx, req.SessionID, req.Command, req.Workdir, owner, req.RingCapacity)
sess, err = s.LocalSessions.Start(context.Background(), req.SessionID, req.Command, req.Workdir, owner, req.RingCapacity)
if err == nil {
result = map[string]any{"session_id": sess.ID, "started_at": sess.StartedAt.Unix()}
}
+33
View File
@@ -9,6 +9,7 @@ import (
"strings"
"sync"
"testing"
"time"
"github.com/wjyhk/vps-commander/internal/executor"
"github.com/wjyhk/vps-commander/internal/storage"
@@ -92,6 +93,38 @@ func TestSecurityEffectiveModeAndExecGate(t *testing.T) {
}
}
func TestProcessSessionLocalSnakeCaseAndLifecycle(t *testing.T) {
dir := t.TempDir()
store, err := storage.Open(filepath.Join(dir, "db.sqlite"))
if err != nil {
t.Fatal(err)
}
defer store.DB.Close()
if err := store.SetGlobalSecurityMode("high"); err != nil {
t.Fatal(err)
}
s := &Server{Exec: executor.Local{MaxOutput: 1024 * 1024}, Store: store, LocalName: "local", LocalSessions: executor.NewSessionManager(0)}
if err := s.LoadSecurityPolicySnapshot(); err != nil {
t.Fatal(err)
}
req := httptest.NewRequest(http.MethodPost, "/api/v1/process/session?action=start", strings.NewReader(`{"device":"local","session_id":"session-test-001","command":"sleep 0.2; printf local-ok"}`))
w := httptest.NewRecorder()
s.processSession(w, req)
if w.Code != http.StatusOK {
t.Fatalf("start status=%d body=%s", w.Code, w.Body.String())
}
time.Sleep(1 * time.Second)
req = httptest.NewRequest(http.MethodPost, "/api/v1/process/session?action=read", strings.NewReader(`{"device":"local","session_id":"session-test-001"}`))
w = httptest.NewRecorder()
s.processSession(w, req)
if w.Code != http.StatusOK {
t.Fatalf("read status=%d body=%s", w.Code, w.Body.String())
}
if !strings.Contains(w.Body.String(), "local-ok") {
t.Fatalf("missing session output: %s", w.Body.String())
}
}
func TestEditBlockSecurityAndReplacement(t *testing.T) {
dir := t.TempDir()
store, err := storage.Open(filepath.Join(dir, "db.sqlite"))
+27
View File
@@ -98,6 +98,33 @@ func (b *MCPBackend) ExecCommand(ctx context.Context, clientIP, device, command,
}, nil
}
func (b *MCPBackend) DiagnosticCommand(ctx context.Context, clientIP, device string, req executor.DiagnosticRequest) (any, error) {
if device == "" {
device = b.server.LocalName
}
if err := b.authorize(device, "diagnostic", clientIP); err != nil {
return nil, err
}
if req.Action == "" {
return nil, errors.New("diagnostic action required")
}
if b.server.isRemote(device) {
if b.server.Cluster == nil || !b.server.Cluster.Online(device) {
return nil, fmt.Errorf("device %s is offline", device)
}
res, err := b.server.Cluster.Diagnostic(ctx, device, req)
if err != nil {
return nil, err
}
return res, nil
}
res, err := executor.Diagnostic(ctx, req)
if err != nil {
return nil, err
}
return res, nil
}
func (b *MCPBackend) ReadFile(ctx context.Context, clientIP, device, path string, offset, limit int64) (any, error) {
if device == "" {
device = b.server.LocalName
+14
View File
@@ -13,6 +13,7 @@ import (
"time"
"github.com/gorilla/websocket"
"github.com/wjyhk/vps-commander/internal/executor"
"github.com/wjyhk/vps-commander/internal/security"
"github.com/wjyhk/vps-commander/internal/storage"
"github.com/wjyhk/vps-commander/internal/sysinfo"
@@ -464,6 +465,19 @@ func (m *Manager) Exec(ctx context.Context, name string, p ExecPayload) (Result,
return Result{msg.ExitCode, msg.Stdout, msg.Stderr, msg.DurationMS}, nil
}
func (m *Manager) Diagnostic(ctx context.Context, name string, req executor.DiagnosticRequest) (executor.DiagnosticResult, error) {
msg, err := m.call(ctx, name, "diagnostic_command", req)
if err != nil {
return executor.DiagnosticResult{}, err
}
b, _ := json.Marshal(msg.Payload)
var out executor.DiagnosticResult
if err := json.Unmarshal(b, &out); err != nil {
return out, err
}
return out, nil
}
func (m *Manager) ReadFile(ctx context.Context, name string, p FileReadPayload) (FileResult, error) {
msg, err := m.call(ctx, name, "file_read", p)
if err != nil {
+117
View File
@@ -0,0 +1,117 @@
package executor
import (
"context"
"errors"
"fmt"
"os/exec"
"strconv"
"strings"
"time"
)
// DiagnosticRequest is a structured, read-only diagnostic operation. It is deliberately
// not a shell command: every action maps to a fixed executable/argument set.
type DiagnosticRequest struct {
Action string `json:"action"`
Target string `json:"target,omitempty"`
Lines int `json:"lines,omitempty"`
}
type DiagnosticResult struct {
Action string `json:"action"`
Target string `json:"target,omitempty"`
ExitCode int `json:"exit_code"`
Stdout string `json:"stdout"`
Stderr string `json:"stderr"`
DurationMS int64 `json:"duration_ms"`
}
func Diagnostic(ctx context.Context, req DiagnosticRequest) (DiagnosticResult, error) {
args, err := diagnosticArgs(req)
if err != nil {
return DiagnosticResult{}, err
}
if req.Lines <= 0 {
req.Lines = 100
}
if req.Lines > 500 {
req.Lines = 500
}
// docker logs is the only operation where a caller-controlled numeric limit is useful.
if req.Action == "docker_logs" {
args = []string{"logs", "--tail", strconv.Itoa(req.Lines), req.Target}
}
start := time.Now()
c, cancel := context.WithTimeout(ctx, 15*time.Second)
defer cancel()
cmd := exec.CommandContext(c, args[0], args[1:]...)
out, runErr := cmd.CombinedOutput()
const maxOutput = 256 * 1024
if len(out) > maxOutput {
out = append(out[:maxOutput], []byte("\n[output truncated at 256 KiB]\n")...)
}
code := 0
if cmd.ProcessState != nil {
code = cmd.ProcessState.ExitCode()
}
result := DiagnosticResult{Action: req.Action, Target: req.Target, ExitCode: code, Stdout: string(out), DurationMS: time.Since(start).Milliseconds()}
if runErr != nil && code == -1 {
return result, fmt.Errorf("diagnostic failed: %w", runErr)
}
return result, nil
}
func diagnosticArgs(req DiagnosticRequest) ([]string, error) {
target := strings.TrimSpace(req.Target)
switch req.Action {
case "docker_ps":
if target != "" {
return nil, errors.New("docker_ps does not accept target")
}
return []string{"docker", "ps", "--no-trunc"}, nil
case "docker_logs":
if target == "" || strings.ContainsAny(target, " \t\r\n;|&<>$`") {
return nil, errors.New("invalid docker container target")
}
return []string{"docker", "logs", "--tail", "100", target}, nil
case "docker_inspect":
if target == "" || strings.ContainsAny(target, " \t\r\n;|&<>$`") {
return nil, errors.New("invalid docker target")
}
return []string{"docker", "inspect", target}, nil
case "systemctl_status":
if target == "" || strings.ContainsAny(target, " \t\r\n;|&<>$`") {
return nil, errors.New("invalid systemd unit")
}
return []string{"systemctl", "status", "--no-pager", "--full", target}, nil
case "journalctl":
if target == "" || strings.ContainsAny(target, " \t\r\n;|&<>$`") {
return nil, errors.New("invalid journal unit")
}
return []string{"journalctl", "--no-pager", "-u", target, "-n", "100"}, nil
case "ss_listen":
if target != "" {
return nil, errors.New("ss_listen does not accept target")
}
return []string{"ss", "-lntp"}, nil
case "df":
if target != "" {
return nil, errors.New("df does not accept target")
}
return []string{"df", "-h"}, nil
case "free":
if target != "" {
return nil, errors.New("free does not accept target")
}
return []string{"free", "-h"}, nil
case "uptime":
if target != "" {
return nil, errors.New("uptime does not accept target")
}
return []string{"uptime"}, nil
default:
return nil, fmt.Errorf("unsupported diagnostic action: %s", req.Action)
}
}
+24
View File
@@ -0,0 +1,24 @@
package executor
import (
"context"
"strings"
"testing"
)
func TestDiagnosticRejectsShellInjection(t *testing.T) {
_, err := Diagnostic(context.Background(), DiagnosticRequest{Action: "docker_logs", Target: "edgeever;rm -rf /"})
if err == nil || !strings.Contains(err.Error(), "invalid docker") {
t.Fatalf("expected target rejection, got %v", err)
}
}
func TestDiagnosticAllowsReadOnlyUptime(t *testing.T) {
got, err := Diagnostic(context.Background(), DiagnosticRequest{Action: "uptime"})
if err != nil {
t.Fatal(err)
}
if got.ExitCode != 0 || strings.TrimSpace(got.Stdout) == "" {
t.Fatalf("unexpected uptime result: %#v", got)
}
}
+24
View File
@@ -12,6 +12,7 @@ import (
"time"
"github.com/wjyhk/vps-commander/internal/auth"
"github.com/wjyhk/vps-commander/internal/executor"
)
// MCP Protocol / JSON-RPC 2.0 Types
@@ -77,6 +78,10 @@ type ActionBackend interface {
EditBlock(ctx context.Context, clientIP, device, path, oldText, newText string) (any, error)
}
type DiagnosticBackend interface {
DiagnosticCommand(ctx context.Context, clientIP, device string, req executor.DiagnosticRequest) (any, error)
}
type ExtendedBackend interface {
ReadMultipleFiles(ctx context.Context, clientIP, device string, paths []string, limit int64) (any, error)
CreateDirectory(ctx context.Context, clientIP, device, path string) (any, error)
@@ -280,6 +285,7 @@ func (s *Server) handleRequest(ctx context.Context, r *http.Request, req JSONRPC
{Name: "create_directory", Description: "创建目录", InputSchema: InputSchema{Type: "object", Properties: map[string]PropertyDef{"device": {Type: "string", Description: "目标设备"}, "path": {Type: "string", Description: "目录路径"}}, Required: []string{"path"}}},
{Name: "move_file", Description: "移动或重命名文件", InputSchema: InputSchema{Type: "object", Properties: map[string]PropertyDef{"device": {Type: "string", Description: "目标设备"}, "source": {Type: "string", Description: "源路径"}, "destination": {Type: "string", Description: "目标路径"}}, Required: []string{"source", "destination"}}},
{Name: "list_processes", Description: "列出受控节点当前进程", InputSchema: InputSchema{Type: "object", Properties: map[string]PropertyDef{"device": {Type: "string", Description: "目标设备"}}}},
{Name: "diagnostic_command", Description: "执行严格白名单的只读系统诊断,不接受任意 Shell", InputSchema: InputSchema{Type: "object", Properties: map[string]PropertyDef{"device": {Type: "string", Description: "目标设备"}, "action": {Type: "string", Description: "docker_ps|docker_logs|docker_inspect|systemctl_status|journalctl|ss_listen|df|free|uptime"}, "target": {Type: "string", Description: "容器名或 systemd unit(按 action 使用)"}, "lines": {Type: "integer", Description: "docker_logs 最大行数,1-500"}}, Required: []string{"action"}}},
{
Name: "edit_block",
Description: "对指定文件执行唯一文本块的原子替换;old_text 必须恰好匹配一次",
@@ -430,6 +436,24 @@ func (s *Server) callTool(ctx context.Context, clientIP string, params CallToolP
return map[string]string{"error": err.Error()}, true
}
return res, false
case "diagnostic_command":
var a struct {
Device string `json:"device"`
Action string `json:"action"`
Target string `json:"target"`
Lines int `json:"lines"`
}
_ = json.Unmarshal(params.Arguments, &a)
b, ok := s.Backend.(DiagnosticBackend)
if !ok {
return map[string]string{"error": "diagnostic tools unavailable"}, true
}
res, err := b.DiagnosticCommand(ctx, clientIP, a.Device, executor.DiagnosticRequest{Action: a.Action, Target: a.Target, Lines: a.Lines})
if err != nil {
return map[string]string{"error": err.Error()}, true
}
return res, false
case "list_processes":
var a struct {
Device string `json:"device"`
+1 -1
View File
@@ -79,7 +79,7 @@ func TestMCPInitializeAndListTools(t *testing.T) {
t.Fatalf("expected map result")
}
tools, ok := resMap["tools"].([]any)
if !ok || len(tools) != 11 {
if !ok || len(tools) != 12 {
t.Fatalf("expected 11 tools, got %d", len(tools))
}
foundWriteFile := false
+2 -1
View File
@@ -15,6 +15,7 @@ var registry = map[string]ToolSpec{
"start_search": {Name: "start_search", RequiredRisk: RiskLow, Category: "search", ReadOnly: true},
"get_more_search_results": {Name: "get_more_search_results", RequiredRisk: RiskLow, Category: "search", ReadOnly: true},
"list_processes": {Name: "list_processes", RequiredRisk: RiskLow, Category: "process", ReadOnly: true},
"diagnostic_command": {Name: "diagnostic_command", RequiredRisk: RiskLow, Category: "diagnostic", ReadOnly: true},
"list_sessions": {Name: "list_sessions", RequiredRisk: RiskLow, Category: "process", ReadOnly: true},
"read_process_output": {Name: "read_process_output", RequiredRisk: RiskLow, Category: "process", ReadOnly: true},
"edit_block": {Name: "edit_block", RequiredRisk: RiskMedium, Category: "file", ReadOnly: false},
@@ -31,7 +32,7 @@ var registry = map[string]ToolSpec{
var actionTools = map[string]string{
"read": "read_file", "probe": "read_file", "write": "write_file",
"mcp": "mcp_call", "exec": "exec_command",
"mcp": "mcp_call", "exec": "exec_command", "diagnostic": "diagnostic_command",
}
func Lookup(name string) (ToolSpec, bool) {