Skip to content

feat: admin tools operate the connected database (admin HTTP API + MCP dual mode) - #109

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

Svtter merged 4 commits into
mainfrom
feat/mcp-server

Conversation

@Svtter

@Svtter Svtter commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

What

Closes #101 (follow-up to the v2.7.0 MCP semantics).

Problem

v2.7.0 made the MCP admin tools (user_add / user_issue_key / user_revoke_key / user_list / audit) always operate on the MCP process's local --db store — even when --server pointed at a remote instance. An agent connected to sth.sun-praise.com would mint users into its own machine's SQLite instead of the instance's database.

Change

  • Admin HTTP API (internal/server/admin.go): GET/POST /api/admin/users, PUT /api/admin/users/{name}/role, POST /api/admin/users/{name}/keys, DELETE /api/admin/keys/{idOrPrefix}, GET /api/admin/audit, POST /api/admin/audit/prune. Bearer key must belong to an admin-role user (member → 403 admin role required, missing/invalid → 401); every mutation writes an audit event (actor = acting admin).
  • MCP dual mode (internal/cli/mcp.go): the five admin tools now mirror the tag-family semantics — with --server they call the remote admin API (identity via GET /api/me, mutations land in the remote store/audit log); without it they keep the local --db behavior. requireAdminFor falls back to the configured --api-key in local mode (bug: member keys were reported as "no API key configured").
  • Fix (internal/cli/metadata.go): doJSONRequest now parses the request path with url.Parse before ResolveReference, so query strings no longer get their ? percent-encoded into the path (audit reads 404'd).
  • Server.ListenAddr() exported accessor for tests.

Tests

  • internal/server/admin_test.go (new): no-key 401 across endpoints, member 403 with untouched store, admin lifecycle (list shape, create + admin flag, 409 duplicate, 400 empty username / bad role, 404 unknown user, issue/verify/revoke incl. 404 re-revoke), audit list/filter validation + prune validation.
  • TestMCPAdminToolsRemoteEndToEnd: real HTTP server — admin key's user_add/user_issue_key/audit land on the remote store (issued key verifies remotely, NOT locally); member key denied everywhere.
  • Full go test -race ./internal/... green.

Docs

README.md / README.cn.md: dual-mode wording + admin API endpoint tables (replaces the "admin tools always operate on the local --db" wording and the "no audit HTTP endpoint" rationale); CHANGELOG 2.8.0 entry with the behavior change called out.

Refs #101

…CP dual mode

- Server: /api/admin/* endpoints (users list/create, role, key issue/revoke,
  audit list/prune), gated on admin-role Bearer keys, all mutations audited
- MCP: user_add/user_issue_key/user_revoke_key/user_list/audit are dual-mode —
  with --server they call the remote admin API (remote store + remote audit);
  without it they keep the local --db behavior
- requireAdminFor falls back to the configured --api-key in local mode;
  doJSONRequest passes query strings through url.Parse (fixes ?encoding)
- Tests: remote e2e over a real server (admin path lands remotely, member
  denied), server-side admin_test.go covering auth matrix and endpoint shapes
- Docs: README/README.cn admin dual-mode + endpoint tables, CHANGELOG 2.8.0

Refs #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

评审详情

整体方向没问题:admin HTTP API 的门控(Bearer → IsAdmin → 403/401)、审计落地、MCP admin tools 的双模式改造以及端到端测试都成立,CI 层面的行为变化也在 CHANGELOG 里写清了。下面两类问题建议修掉再合。

Should-fix

  • internal/cli/metadata.go:27(配合 internal/cli/mcp.go:851/893、internal/cli/share.go:89):把 &url.URL{Path: path} 换成 url.Parse(path) 后,路径里的 ? / # / .. 不再是普通字符而是 URL 语法(./.. 段会被 ResolveReference 归一化,# 之后被当 fragment 丢弃)。而新代码把用户/agent 输入的段直接拼进 path:"/api/admin/users/"+in.Name+"/keys"、"/api/admin/keys/"+in.IDOrPrefix。后果:(1) 用户名/id 里带 ?/#// 时请求打到错误路径(服务器侧 CreateUser 只拒绝空用户名,允许这些字符,internal/session/auth.go:87);(2) --allow-admin-tools=true 时被注入的 tool 调用可以借 .. 跳出 admin 端点,用配置的 admin key 请求同源的其他接口(不再是声明出来的 tool 面)。建议:动态段一律 url.PathEscape(或给 doJSONRequest 增加独立的 query 参数,path 继续用 &url.URL{Path: ...} 转义)。
  • internal/cli/mcp.go:1135(remoteAudit):ID: int64(m["id"].(float64)) 是未检查的类型断言,远端返回缺 id 或 id 为字符串(旧版本/代理/字段改名)时 panic 会把整个 stdio MCP server 打挂;同文件其他字段都用 stringField 这类安全读法。改成安全取值(if v, ok := m["id"].(float64); ok)。
  • internal/server/admin.go:143/185/215/244/355:五处 _ = s.store.RecordAudit(...) 绕过了既有 s.recordAuditAs(internal/server/audit.go:118),因此 admin API 的审计行缺 IP、UserAgent、actorID(adminActor 只给了 username),写失败也不写 stderr。请复用 recordAuditAs(r, action, target, auditOK, detail, actor, actorUID)。
  • 文档与行为不一致(internal/cli/mcp.go registerMCPTools 里 user_add/user_issue_key/user_revoke_key/user_list/audit 的 Description 仍写 "in the local DB",README.md:137、README.cn.md:159 仍称 "read-only user_list is always available" / "user_list 对所有人开放"):admin tools 已双模式,且 user_list 远程走的是 admin-only 的 GET /api/admin/users(internal/cli/mcp.go:937),按 README 推荐的低权限 member key 配置 --server 后 user_list 必然 403。要么补一句文档/改 Description,要么给 user_list 明确"远程需 admin key"的说明(CHANGELOG 也没提这条变化)。
  • internal/cli/mcp.go:180(requireAdminFor remote 分支):remote 模式没有 apiKey == "" 的提前判断,无 key 时会拿空 key 打 /api/me,报 "resolving identity from …: Unauthorized…",而不是原本清晰的 "no API key configured…"。把本地分支那段空 key 检查提到 remote 之前。

Nits

  • internal/server/admin.go:148:CreateUser 成功后 SetUserRole 失败只返回 500,用户已建出但角色未生效(无回滚/无提示)。概率很低,但要么先校验 role,要么在错误里说明用户已创建。
  • 测试覆盖回退:被删掉的 TestMCPAdminGatingRemoteIdentity 里还有一条"/api/me 挂掉时 admin 调用失败但非 admin 工具照常工作"的断言,新测试没覆盖该路径。
  • internal/server/server.go:1296 ListenAddr() 与既有 Origin() 重叠,测试里直接复用 Origin() 可以少一个导出方法。
  • admin 接口的 500 响应体直接回 err.Error()(如 admin.go:29/85),会露出 store 层错误文本;与仓库其他地方一致,可留,但更好的是固定文案 + stderr 记录。

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

Details

Comment thread internal/cli/metadata.go Outdated
return nil, fmt.Errorf("invalid server URL: %w", err)
}

ref, err := url.Parse(path)

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/metadata.go:27(配合 internal/cli/mcp.go:851/893、internal/cli/share.go:89):把 &url.URL{Path: path} 换成 url.Parse(path) 后,路径里的 ? / # / .. 不再是普通字符而是 URL 语法(./.. 段会被 ResolveReference 归一化,# 之后被当 fragment 丢弃)。而新代码把用户/agent 输入的段直接拼进 path:"/api/admin/users/"+in.Name+"/keys"、`"…

Comment thread internal/cli/mcp.go
ID: int64(m["id"].(float64)),
Time: stringField(m, "time"),
Actor: stringField(m, "actor"),
ActorID: stringField(m, "actorId"),

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:1135(remoteAudit):ID: int64(m["id"].(float64)) 是未检查的类型断言,远端返回缺 id 或 id 为字符串(旧版本/代理/字段改名)时 panic 会把整个 stdio MCP server 打挂;同文件其他字段都用 stringField 这类安全读法。改成安全取值(if v, ok := m["id"].(float64); ok)。

Comment thread internal/server/admin.go Outdated
Actor: actor,
Action: session.AuditUserAdd,
Target: user.Username,
Detail: "role=" + role,

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/server/admin.go:143/185/215/244/355:五处 _ = s.store.RecordAudit(...) 绕过了既有 s.recordAuditAs(internal/server/audit.go:118),因此 admin API 的审计行缺 IP、UserAgent、actorID(adminActor 只给了 username),写失败也不写 stderr。请复用 recordAuditAs(r, action, target, auditOK, detail, actor, actorUID)。

…recordAuditAs, docs consistency

- doJSONRequest: path stays an opaque escaped segment; new doJSONRequestQuery
  carries query strings (audit reads, unshare ?path=). Dynamic segments are
  validated with pathSeg (rejects /, ?, #, bare dot-segments) so a crafted
  session id / username / key prefix cannot escape the endpoint namespace
- remoteAudit: mcpAuditEvent.ID read defensively (no unchecked assertion)
- admin API mutations record audit via recordAuditAs (IP, User-Agent, actorID,
  stderr on write failure); role-assignment failure error names the created user
- requireAdminFor: empty-key check before the remote/local branch (clear error
  instead of a keyless /api/me Unauthorized)
- Tool descriptions + README/README.cn/CHANGELOG: dual-mode wording; user_list
  is admin-gated remotely
- Tests: TestMCPAdminToolsRemoteIdentityDown (dead remote breaks admin calls,
  local tools keep working); ListenAddr dropped in favor of Origin()

Refs #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)

🚫 CANNOT MERGE

评审详情

第 4 轮的大部分意见都改到位了:remoteAudit 的 m["id"] 断言改为安全取值、admin API 的四处审计改走 s.recordAuditAs(补齐 IP/UA/actorID 与 stderr 失败日志)、文档与 tool Description 统一成双模式表述、ListenAddr 直接用 Origin()、path 段统一走 pathSeg + doJSONRequestQuery。但本轮新引入的一段逻辑带来一个真实的凭据泄露回归,必须拦下。

Blocking

  • internal/cli/mcp.go:141-146(requireAdminFor):新加的无条件 if apiKey == "" { apiKey = c.apiKey } 破坏了"凭据与主机绑定"的不变量。resolveRemote(mcp.go:340-352)对 per-call 覆盖的 server 故意返回 apiKey == "",注释和 README「安全说明」都写明这是为了让被 prompt 注入的调用无法把配置的 key 带到别的主机。现在只要 agent 传入 server: "https://attacker.example"(不带 api_key),remoteIsAdmin 就把 c.apiKey(真正的 admin key)当作 Authorization: Bearer … 发到该主机的 /api/me;若对方返回 {"isAdmin":true},紧接着的 POST /api/admin/users / /api/admin/keys/… 还会再带同一把 key 发过去——等于把 admin key 交给注入方。上一轮的代码在 remote 分支不做 fallback,会直接以空 key 失败,所以这是本 delta 引入的回归(同时也与 README:139 与 README.cn.md:186 的承诺矛盾)。
    修复:fallback 只对本地模式生效 —— if apiKey == "" && !remote { apiKey = c.apiKey },remote 只信任 resolveRemote 给出的 key;随后仍返回 "no API key configured: …"。这样 --server + 无 key 的默认主机场景依然拿到这条友好错误(resolveRemote 对默认主机返回 c.apiKey,为空时命中该分支),而指向第三方主机时不再外发任何凭据。
    配套测试:起一个 httptest server 记录 Authorization 头,配置 serverURL/apiKey 为某 admin key,再以 per-call server 覆盖指向该 httptest(不带 api_key)调用 user_add,断言该请求没有收到 Bearer 头且 tool 返回拒绝。

Nits

  • internal/cli/mcp_test.go:1173(TestMCPAdminToolsRemoteIdentityDown):用的是非空 apiKey,只覆盖"远端挂掉"分支,没覆盖上面"per-call 覆盖 server 不应带配置 key"的分支;建议补上,否则这条安全不变量仍无测试守护。
  • internal/cli/metadata.go:24(pathSeg):拒绝 /?# 与纯点段是对的,但含 / 的用户名(CreateUser 只拒绝空名)在远程路径上现在统一报 invalid path segment。错误文案里带一句 "use local=true (or the CLI) for such names" 会更好排查。

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

Details

Comment thread internal/cli/mcp.go
if c.apiKey == "" {

if apiKey == "" {
apiKey = c.apiKey

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.

[blocking] internal/cli/mcp.go:141-146(requireAdminFor):新加的无条件 if apiKey == "" { apiKey = c.apiKey } 破坏了"凭据与主机绑定"的不变量。resolveRemote(mcp.go:340-352)对 per-call 覆盖的 server 故意返回 apiKey == "",注释和 README「安全说明」都写明这是为了让被 prompt 注入的调用无法把配置的 key 带到别的主机。现在只要 agent 传入 server: "https://attacker.example"(不…

Round-5 review blocking finding: the unconditional apiKey=c.apiKey fallback
in requireAdminFor sent the configured admin key to any per-call server
override (prompt injection could exfiltrate it). The fallback now applies
only to local calls; remote overrides with no key fail closed with the clear
'no API key configured' error.

- pathSeg error message names the offending characters and the local escape hatch
- TestMCPAdminToolsOverrideServerGetsNoConfiguredKey: a recorder server captures
  Authorization headers — override calls must carry none and be denied

Refs #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)

✅ CAN MERGE

评审详情

唯一的 Blocking 已修掉,前几轮的其余意见也都保持修复状态。

本轮确认

  • internal/cli/mcp.go:144:if apiKey == "" && !remote —— 配置的 key 现在只在本地模式回填,per-call server 覆盖(resolveRemote 返回的空 key)不会再被补上 c.apiKey,因此 remoteIsAdmin 里那发 Bearer 根本不会发往第三方主机;--server 为默认主机时 resolveRemote 已返回 c.apiKey,--server 无 key 的友好错误 "no API key configured…" 仍然成立。--allow-admin-tools=true 的早退分支同样只带空 key,不外发凭据。
  • internal/cli/mcp_test.go:1199:新测试用伪装成 admin 的 httptest 记录 Authorization,断言覆盖主机收不到任何 Bearer 且调用 fail-closed,正好锁住这条不变量(顺带也校准了 resolveRemote 与 requireAdminFor 的契约)。
  • internal/cli/metadata.go:25:pathSeg 的错误文案补齐了原因与出路(改用户名或不走远程),上一轮 Nit 已消化。
  • 更早的修复仍然在:remoteAudit 的安全数值取值、admin API 审计走 recordAuditAs(含 IP/UA/actorID)、README/CHANGELOG/工具 Description 的双模式与 user_list 远程需 admin key 说明、ListenAddr 复用 Origin()。

Nits(可选,不阻塞)

  • internal/cli/mcp_test.go:1223:因为没有请求真的发出,尾部断言 Authorization 全为空是"空集合为真";再加一条 len(authHeaders) != 0 → t.Fatal 的负向断言,会让"回归时确实有请求发出去"这一点更明确。

累计来看:admin HTTP API 的门控与审计、MCP 双模式改造、路径段转义、凭据主机绑定都有对应测试覆盖,剩余项都是风格级。


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

Details

@Svtter
Svtter merged commit 8b9020c into main Nov 19, 2026
3 checks passed
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