Skip to content

fix: implement missing MCP resources API + readSSE message drop (R3-BUG35) - #48

Closed
lezi-fun wants to merge 6 commits into
HEXUXIU:devfrom
lezi-fun:fix/mcp-resources-and-sse-drop
Closed

lezi-fun wants to merge 6 commits into
HEXUXIU:devfrom
lezi-fun:fix/mcp-resources-and-sse-drop

Conversation

@lezi-fun

Copy link
Copy Markdown
Contributor

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) references Resource, ResourceContent, ResourceProvider, GlobalResourceProvider and the resources/list + resources/read RPC methods — none of which exist on dev, so go test ./internal/mcp/ fails to build:

vet: internal/mcp/resources_test.go:13:14: undefined: Resource

This ports the implementation from main (d8e50da), including:

  • Resource / ResourceContent / ResourceProvider types
  • GlobalResourceProvider var
  • resources/list + resources/read handlers with the mcp:// / gateway:// / m365:// URI scheme allowlist (SSRF guard)
  • resources capability advertised in initialize

2. readSSE silently drops responses (R3-BUG35 from the bug list)

readSSE used a non-blocking send and dropped messages when msgCh (cap 64) was full, leaving the pending sendRequest caller 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

go build ./...        # OK
go test ./internal/... # all 5 packages pass

TestResourcesListReturnsRegisteredResources, TestResourcesReadReturnsContent and TestInitializeAdvertisesResourcesCapability now compile and pass.

…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.
@lezi-fun

Copy link
Copy Markdown
Contributor Author

Added commit 2e2561a: found three regressions introduced by the upstream bug-fix batch itself (1cd4455):

  1. dropLocked never cleaned byExplicit — TTL/LRU session eviction leaked explicit-index entries unboundedly (an OOM vector of exactly the kind this batch set out to fix) and left dangling mappings that could resolve to recycled session IDs.

  2. DeleteSession/UnbindByConversation deleted the wrong key — delete(sr.byExplicit, sessionID), but byExplicit is keyed by the client's X-M365-Session-Id header, not the internal session ID. Only worked when the two happened to be equal. Both paths now remove every explicit entry pointing at the dropped session.

  3. Tenant eviction in responseMessages was arbitrary, not LRU — the inner loop had an unconditional break, so with Go's random map iteration order each tenant's "oldest" timestamp was a random sample. Removed the break so the full bucket is scanned.

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 HEXUXIU left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

感谢你的贡献。逐一审核了 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.
@lezi-fun

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review. All six points are addressed in 0fd1d4b:

  1. readSSE blocking send (P0) — replaced with a bounded send: select { case c.msgCh <- msg: case <-time.After(5s): log+drop }. The reader keeps draining the HTTP body even when no waiter arrives, while a slow consumer still gets a grace window before anything is dropped.

  2. byExplicit O(n) cleanup (P1) — added a reverse index explicitBySession map[string]map[string]struct{} maintained in reindexExplicitLocked; dropLocked, DeleteSession and UnbindByConversation now call unbindExplicitForSessionLocked, which removes all bindings for a session without scanning the map.

  3. responseMessages tenant eviction (P1) — rewrote it to evict the least recently active tenant: each bucket is compared by its newest record, so the semantics are explicit and independent of map iteration order (a tenant that wrote recently is never chosen over an idle one). Comment added in-code.

  4. GlobalResourceProvider data race — replaced the bare global with an RWMutex-guarded struct accessed via resourceProvider() / SetGlobalResourceProvider().

  5. resources/read SSRF — reads are now restricted to URIs the provider itself advertised via resources/list (allowlist check against the enumerated surface); the scheme-prefix check is kept as a first filter. Covered by TestResourcesReadRejectsUnlistedURI.

  6. MCP endpoint auth — added an AuthHook on HandleSSE/HandleMessage/HandleToolsList (the mcp package can't import web, so it takes a hook). web.New wires it to validAPIKey, so MCP endpoints require the same API key as every other /v1/ route.

Also added TestUnbindExplicitReverseIndex for the reverse-index cleanup. go build ./..., go vet ./... and go test ./... all pass.

@HEXUXIU

HEXUXIU commented Aug 22, 2026

Copy link
Copy Markdown
Owner

重新审核结果

之前 6 个问题全部修复,修复质量良好 ✅

# 问题 状态
1 P0: readSSE 死锁 ✅ 5s 有界等待
2 P1: byExplicit O(n) ✅ 反向索引 + 测试
3 P1: tenant 淘汰语义 ✅ per-tenant LRU
4 P1: GlobalResourceProvider race ✅ RWMutex
5 P1: SSRF 防护不足 ✅ scheme + allowlist
6 P2: MCP 无鉴权 ✅ AuthHook

新发现 1 个 P2:
esources/read\ 和
esources/list\ 的 RPC 错误消息直接返回 \err.Error()\,可能泄露内部信息(文件路径、连接字符串等)。建议改为通用消息,detail 仅写服务端日志。不阻塞合并。

整体:LGTM,P2 可后续修。

@HEXUXIU HEXUXIU left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

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
@lezi-fun

Copy link
Copy Markdown
Contributor Author

P2 已在 05d5a88 修复。

resources/list 和 resources/read 不再把 err.Error() 直接返回给客户端。三处 provider 错误路径均改为服务端 log.Printf 记录详细错误、客户端只收到通用消息:

  • resources/list 列举失败 → internal error: unable to list resources
  • resources/read allowlist 预检失败 → internal error: unable to read resource
  • resources/read ReadResource 失败 → internal error: unable to read resource

go build ./... / go vet ./... / go test ./internal/mcp/... 全部通过。

@lezi-fun
lezi-fun requested a review from HEXUXIU August 24, 2026 02:15
@HEXUXIU

HEXUXIU commented Aug 25, 2026

Copy link
Copy Markdown
Owner

感谢贡献!MCP resources 补全和 readSSE 修复都是需要的,实现质量也不错。以下是我的评审意见:

通过项:

  • SSRF 防护双重校验(URI scheme + allowlist 匹配),设计扎实
  • AuthHook 设计合理,nil 默认放行便于测试,生产环境由 initMCPAuth 注入
  • session_resolver 反向索引解决 O(n) 遍历问题
  • responseMessages 淘汰逻辑修正(原来 break 依赖 map 随机迭代)
  • 错误消息脱敏,provider 错误不暴露内部细节

需要修改的问题:

1. readSSE 的 time.After GC 压力
client.go:143 每次收到 SSE 消息都 time.After(5s) 创建新 timer,高频场景下会产生大量短命 timer。建议改用 time.NewTimer + timer.Stop() + timer.Reset() 复用。

2. resources/read 参数校验泄露 err.Error()
server.go:352 返回 "invalid params: " + err.Error(),与 PR 中其他错误处理(provider 错误返回通用消息)不一致。建议改为通用消息 + 日志记录详情。

3. resources/read allowlist O(n) 线性扫描
每次 read 都 ListResources + 线性遍历。当前资源数量少可接受,但建议加 TODO 注释或增加 ResourceExists(ctx, uri) bool 方法。

4. 缺少 readSSE 行为变更的测试
从立即丢弃改为 5 秒有界阻塞是关键行为变更,应有测试覆盖 channel 满时的等待/超时行为。

结论: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.
@lezi-fun

Copy link
Copy Markdown
Contributor Author

All four points from the latest review are addressed in 3f6da82:

  1. readSSE time.After GC pressure — replaced with a single reused time.Timer (NewTimer + Stop/Reset, with the standard drain-on-Stop-failed dance). The 5s grace window is now the named constant sendGraceWindow.

  2. resources/read params error leaking err.Error() — raw unmarshal errors are now logged server-side; the client gets a generic invalid params: uri is required (-32602), consistent with the provider-error sanitization in 05d5a88.

  3. allowlist O(n) scan — added an in-code comment documenting why it's acceptable at current resource counts, plus a TODO describing the ResourceExists(ctx, uri) bool escape hatch on ResourceProvider if that ever changes.

  4. readSSE behavior tests — new client_sse_test.go:

    • TestReadSSEDropsAfterGraceWindowWhenFull: with msgCh full and no consumer, readSSE must block ≥ grace window then drop and keep going — pins both regressions (immediate drop / unbounded block).
    • TestReadSSEDeliversWhenDrained: 200+ messages delivered in order through the reused-timer fast path.

go build ./..., go vet ./internal/... and go test ./internal/... all pass locally.

@HEXUXIU HEXUXIU left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

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.go in this PR targets the old msgCh model (dev), but main (1b1d53e) has been refactored to pending map[int64]chan. The patch no longer applies and the sendTimer bounded-block logic needs to be reimplemented for the new per-request channel model (also update client_sse_test.go).
  • Auth hook duplicates mcp.APIKeyValidator already on main. Please unify on one variable (keep APIKeyValidator), wire it in Routes() only, and make HandleSSE/HandleMessage reuse it. The new AuthHook/initMCPAuth() should be removed/merged.
  • resources/read 404 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.

@lezi-fun

Copy link
Copy Markdown
Contributor Author

Superseded by #67 — ported onto current main as requested (old base dev no longer applies). Thanks for the reviews!

@lezi-fun lezi-fun closed this Aug 26, 2026
jackSun074 pushed a commit to jackSun074/M365-Copilot2API that referenced this pull request Sep 1, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants