Repository navigation
Conversation
…ndefined types) resources_test.go (added in fe5a424) references Resource, ResourceContent, ResourceProvider, GlobalResourceProvider and resources/list+read RPC methods that were never committed. Port the implementation from main (d8e50da), including the mcp:///gateway:///m365:// URI scheme allowlist (SSRF guard).
The non-blocking send silently dropped messages when msgCh was full, leaving the pending sendRequest caller to time out. Use a blocking send: waiters drain the channel, and a drop would hang the request forever, which is strictly worse than backpressure.
1. sessionResolver.dropLocked never cleaned byExplicit (added in 1cd4455), so TTL/LRU eviction leaked explicit-index entries unboundedly and left dangling mappings that could resolve to recycled session IDs. 2. DeleteSession/UnbindByConversation used delete(sr.byExplicit, sessionID) but byExplicit is keyed by the client's X-M365-Session-Id, not the internal session ID — only worked when the two happened to be equal. Both now remove every explicit entry pointing at the dropped session. 3. responseMessages tenant eviction (1cd4455) broke out of the inner loop after one entry; since Go map iteration order is random, each tenant's 'oldest' timestamp was a random sample. Remove the break so the full bucket is scanned.
|
Added commit 2e2561a: found three regressions introduced by the upstream bug-fix batch itself (1cd4455):
All other fixes in 1cd4455/fe5a424/afb0b3f/af27720/19ff6c8 were reviewed and verified correct (sync.Cond watcher pattern, singleflight refresh, authFail lifecycle, atomic writes, UTF-8-safe truncate, safeInt64, failover guard). |
HEXUXIU
left a comment
There was a problem hiding this comment.
感谢你的贡献。逐一审核了 diff,有几个问题需要修正后才能合并:
1. readSSE 阻塞 send 会导致 MCP session 死锁(P0)
把 select+default 改成直接 c.msgCh <- msg,如果 msgCh(cap 64)满了,readSSE goroutine 永久阻塞,不再读取 HTTP body,SSE 连接卡死,该 session 上所有后续请求全部超时。原来的 non-blocking send + log 在实际运行中是正确的——丢弃消息比死锁好得多。如果担心丢消息,应该加大 channel 或加 context 超时,而不是无条件阻塞。
2. session_resolver byExplicit 清理逻辑 O(n) 遍历(P1)
dropLocked、DeleteSession、UnbindByConversation 三处都遍历整个 byExplicit map 删除匹配项。高并发下 session 数千时这是性能退化。应该建反向索引 sessionID -> explicitIDs,O(1) 删除。
3. responseMessages tenant 淘汰逻辑改动有误(P1)
去掉了 break 后,内层循环遍历一个 tenant 的所有 entry 找 oldest,但外层 for range 遍历所有 tenant。原来 break 是因为只关心当前遍历到的第一个 tenant 的第一个 entry(淘汰整个 tenant bucket)。去掉 break 后语义变了,变成找全局最老的 entry,然后删掉它所属的 tenant bucket——这和原来的淘汰最久未访问的 tenant 语义不同。如果这就是你的意图,请加注释说明;如果不是,请恢复 break 或重写淘汰逻辑。
4. GlobalResourceProvider 无锁保护
裸全局变量,多 goroutine 并发读写存在 data race。应使用 sync.Once 或 sync.RWMutex。
5. resources/read SSRF 防护不充分
只校验 URI 前缀(mcp://、gateway://、m365://),但这些 scheme 可能指向内部资源。ResourceProvider 实现如果没有二次校验,可以读取任意内部数据。
6. MCP resources 端点无鉴权
任何连上 SSE 端点的客户端都能枚举和读取资源,应校验 session 权限。
- readSSE: replace unbounded blocking send with a 5s grace window. A plain blocking send deadlocks the SSE reader when msgCh fills up with no waiter; dropping immediately can hang a pending caller. The bounded send keeps the reader draining while giving waiters time to consume. - session_resolver: add explicitBySession reverse index so dropLocked, DeleteSession and UnbindByConversation remove explicit bindings in O(#bindings) instead of scanning the whole byExplicit map. - responses: tenant eviction now compares tenants by their newest record (least recently active tenant is evicted), instead of the previous global-oldest-entry scan whose semantics differed from the original per-bucket eviction. - mcp: guard GlobalResourceProvider with an RWMutex (resourceProvider / SetGlobalResourceProvider) to remove the data race on concurrent handleRPC calls. - mcp: resources/read now only accepts URIs advertised by ListResources, so reads are tied to the enumerated surface instead of trusting URI prefixes alone. - mcp: add AuthHook gate on HandleSSE/HandleMessage/HandleToolsList; web.New wires it to validAPIKey so MCP endpoints require the same API key as other /v1/ routes.
|
Thanks for the thorough review. All six points are addressed in 0fd1d4b:
Also added |
重新审核结果之前 6 个问题全部修复,修复质量良好 ✅
新发现 1 个 P2: 整体:LGTM,P2 可后续修。 |
HEXUXIU
left a comment
There was a problem hiding this comment.
Review: P2 未修,暂不合并
重新审核确认之前 6 个问题全部修复,修复质量良好。
但新发现的 P2 仍未修:
RPC 错误消息泄露内部信息:resources/read 和 resources/list 的 newRPCError 直接拼接 err.Error(),可能暴露文件路径、连接字符串等。建议改为通用消息,detail 仅写服务端日志。
请修复后可合并。
…IU#48 P2) Forwarding err.Error() to MCP clients could leak internal details such as file paths or connection strings. resources/list and resources/read now log the detailed error server-side and return generic messages: - resources/list provider failure - resources/read allowlist pre-check failure - resources/read ReadResource failure
|
P2 已在 05d5a88 修复。
|
|
感谢贡献!MCP resources 补全和 readSSE 修复都是需要的,实现质量也不错。以下是我的评审意见: 通过项:
需要修改的问题: 1. readSSE 的 time.After GC 压力 2. resources/read 参数校验泄露 err.Error() 3. resources/read allowlist O(n) 线性扫描 4. 缺少 readSSE 行为变更的测试 结论:REQUEST_CHANGES — #1 和 #2 建议在本 PR 修复,#3 可加 TODO,#4 至少 readSSE 行为变更需要测试。整体方向正确,修复后可合入! |
… behavior tests (PR HEXUXIU#48 round 2) Addresses the second review round: 1. readSSE timer GC pressure: time.After allocated a fresh timer per message and kept it alive until firing. Reuse one time.Timer via NewTimer/Stop/Reset with proper channel drain; grace window is now the named constant sendGraceWindow. 2. resources/read invalid-params error leaked raw json unmarshal err.Error(). Now logs server-side and returns a generic -32602 message, consistent with the provider-error sanitization from 05d5a88. 3. resources/read allowlist O(n) scan: documented as acceptable at current scale with a TODO pointing at a ResourceExists escape hatch on ResourceProvider if resource counts grow. 4. Added client_sse_test.go covering the bounded-blocking-send behavior: full channel must block for the grace window then drop (not forever, not immediately), and the drained path must deliver 200+ messages in order through the reused timer.
|
All four points from the latest review are addressed in 3f6da82:
|
HEXUXIU
left a comment
There was a problem hiding this comment.
Thanks for the fix — the resources implementation and the SSRF allowlist+enumeration check are solid.
Requesting changes before merge:
- Rebase is required:
internal/mcp/client.goin this PR targets the oldmsgChmodel (dev), butmain(1b1d53e) has been refactored topending map[int64]chan. The patch no longer applies and thesendTimerbounded-block logic needs to be reimplemented for the new per-request channel model (also updateclient_sse_test.go). - Auth hook duplicates
mcp.APIKeyValidatoralready onmain. Please unify on one variable (keepAPIKeyValidator), wire it inRoutes()only, and makeHandleSSE/HandleMessagereuse it. The newAuthHook/initMCPAuth()should be removed/merged. resources/read404 echoes the requested URI (resource not found: <uri>). Please return a generic message and log the URI server-side.
Nice to have: cache/Exists optimization for the per-read ListResources scan, and rebuild explicitBySession on loadLocked for restart correctness. Happy to re-approve after rebase.
|
Superseded by #67 — ported onto current main as requested (old base dev no longer applies). Thanks for the reviews! |
…nnel client (port of PR HEXUXIU#48 to main) Port of the PR HEXUXIU#48 work rebased onto the refactored main branch, as requested in the last review round. resources API (was never implemented; tests added earlier did not build): - Resource / ResourceContent / ResourceProvider types - RWMutex-guarded global provider (resourceProvider() / SetGlobalResourceProvider) — safe for concurrent swap - resources/list + resources/read RPC handlers - SSRF guard: scheme allowlist (mcp:// gateway:// m365://) PLUS a check that the URI was advertised via resources/list, so reads are tied to the enumerated surface. TODO(perf) notes the O(n) scan is acceptable at current scale with ResourceExists as the escape hatch. - initialize now advertises the resources capability Error-message hygiene: - provider errors and raw unmarshal errors are logged server-side; clients get generic messages only - resource-not-found (-32002) no longer echoes the requested URI — it is logged instead Auth: - HandleSSE / HandleMessage now enforce APIKeyValidator (same variable HandleToolsList already uses; wired once in Routes()). No new hook variable. readSSE on the new pending map[int64]chan model: - non-blocking send is kept deliberately: each pending channel has capacity 1 and exactly one select-waiting consumer, so a full channel means the requester timed out. Blocking would stall the SSE reader for a response nobody will read. The drop path now logs. - client_sse_test.go rewritten for this model: late-response drop must not block, waiter delivery works, id-less notifications are skipped. The session_resolver reverse-index work from the original PR is dropped: main's Tenant/ExplicitID refactor already resolves byExplicit cleanup correctly.
Summary
Two fixes on top of
dev(afb0b3f):1. MCP resources API was never implemented (build broken)
internal/mcp/resources_test.go(added in fe5a424) referencesResource,ResourceContent,ResourceProvider,GlobalResourceProviderand theresources/list+resources/readRPC methods — none of which exist ondev, sogo test ./internal/mcp/fails to build:This ports the implementation from
main(d8e50da), including:Resource/ResourceContent/ResourceProvidertypesGlobalResourceProvidervarresources/list+resources/readhandlers with themcp:///gateway:///m365://URI scheme allowlist (SSRF guard)resourcescapability advertised ininitialize2. readSSE silently drops responses (R3-BUG35 from the bug list)
readSSEused a non-blocking send and dropped messages whenmsgCh(cap 64) was full, leaving the pendingsendRequestcaller to time out. Changed to a blocking send — waiters drain the channel, and dropping a response hangs a request forever, which is strictly worse than backpressure.Testing
TestResourcesListReturnsRegisteredResources,TestResourcesReadReturnsContentandTestInitializeAdvertisesResourcesCapabilitynow compile and pass.