mcp: a response that has already arrived is discarded when the caller's context is cancelled during decoding, and notifications/cancelled is sent for the completed request
Maintainer thường phản hồi trong vòng 1 ngày
Đánh giá
- Độ khó
- 3/5
- Thời gian dự kiến
- Nửa ngày
- Mức phù hợp với người mới
- 35/100
Hướng nghiên cứu
Start with the three failing tests named in the logs: TestAwaitPrefersDeliveredResponse in internal/jsonrpc2/conn_test.go, TestAwaitPrefersDeliveredError, and TestCallKeepsDeliveredResponseOnCancel in mcp/transport_test.go. The race sits in the cancellation check in call (mcp/transport.go, about line 306) and the two-way select in AsyncCall.Await (internal/jsonrpc2/conn.go, about line 434). Done means those tests pass and a completed request no longer produces notifications/cancelled.
Do mô hình lập chỉ mục viết ra từ nội dung của issue.
Mô tả
Describe the bug
ClientSession methods such as ListTools and CallTool can return context.Canceled for a request whose response the client has already received and decoded. The result is lost. The client then sends notifications/cancelled for a request that is not in progress any more.
Two things combine to produce this:
callinmcp/transport.gotestsctx.Err() != nilbefore it testserr == nil(mcp/transport.go:306on main 3c08147). WhenAwaitreturnsnilbecause the response arrived and decoded, but the context was cancelled whilejson.Unmarshalwas running,calltakes the cancellation branch anyway. It retires the call, returnsctx.Err()and sendsnotifications/cancelledin a goroutine.AsyncCall.Awaitininternal/jsonrpc2/conn.go:434selects betweenctx.Done()andac.readywith no preference. When both are ready, Go picks one at random, so a response that is already in hand is reported as a cancellation about half the time.
The window is the time it takes to decode the result. A large tools/list result makes it several milliseconds wide, but any call is affected when a deadline expires right as its response lands.
To Reproduce
- Connect a client to an in-memory server that exposes a few thousand tools so the result takes a while to decode.
- Wrap the client transport so that the caller's context is cancelled on the first
Readafter thetools/listresponse has been returned fromRead. At that point jsonrpc2 has already retired the call with its result, because the read loop dispatches a message before it reads the next one. - Call
ListToolswith that context.
package main
import (
"context"
"fmt"
"log"
"sync"
"time"
"github.com/modelcontextprotocol/go-sdk/jsonrpc"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
// cancelAfterResponse cancels ctx on the first Read after the response to
// tools/list has been delivered, and records what the client writes.
type cancelAfterResponse struct {
mcp.Transport
cancel context.CancelFunc
mu sync.Mutex
ids map[int64]string
wrote []string
}
func (t *cancelAfterResponse) Connect(ctx context.Context) (mcp.Connection, error) {
c, err := t.Transport.Connect(ctx)
if err != nil {
return nil, err
}
t.ids = map[int64]string{}
return &conn{Connection: c, t: t}, nil
}
type conn struct {
mcp.Connection
t *cancelAfterResponse
delivered bool
}
func (c *conn) Read(ctx context.Context) (jsonrpc.Message, error) {
if c.delivered {
c.delivered = false
c.t.cancel()
}
m, err := c.Connection.Read(ctx)
if r, ok := m.(*jsonrpc.Response); ok {
c.t.mu.Lock()
c.delivered = c.t.ids[r.ID.Raw().(int64)] == "tools/list"
c.t.mu.Unlock()
}
return m, err
}
func (c *conn) Write(ctx context.Context, m jsonrpc.Message) error {
if r, ok := m.(*jsonrpc.Request); ok {
c.t.mu.Lock()
if id, ok := r.ID.Raw().(int64); ok {
c.t.ids[id] = r.Method
}
c.t.wrote = append(c.t.wrote, r.Method)
c.t.mu.Unlock()
}
return c.Connection.Write(ctx, m)
}
func main() {
ctx := context.Background()
server := mcp.NewServer(&mcp.Implementation{Name: "s", Version: "0"}, &mcp.ServerOptions{PageSize: 3000})
for i := range 3000 {
server.AddTool(&mcp.Tool{Name: fmt.Sprintf("tool-%04d", i), InputSchema: map[string]any{"type": "object"}},
func(context.Context, *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
return &mcp.CallToolResult{Content: []mcp.Content{&mcp.TextContent{Text: "ok"}}}, nil
})
}
ct, st := mcp.NewInMemoryTransports()
if _, err := server.Connect(ctx, st, nil); err != nil {
log.Fatal(err)
}
callCtx, cancel := context.WithCancel(ctx)
defer cancel()
tr := &cancelAfterResponse{Transport: ct, cancel: cancel}
cs, err := mcp.NewClient(&mcp.Implementation{Name: "c", Version: "0"}, nil).Connect(ctx, tr, nil)
if err != nil {
log.Fatal(err)
}
defer cs.Close()
res, err := cs.ListTools(callCtx, nil)
fmt.Println("error:", err)
if res != nil {
fmt.Println("tools:", len(res.Tools))
}
// The cancelled notification is written from a goroutine; give it a moment.
time.Sleep(100 * time.Millisecond)
fmt.Println("written:", tr.wrote)
}
Output on v1.8.0 and on main (3c08147), every run:
error: context canceled
written: [server/discover tools/list notifications/cancelled]
With a timing-based variant (cancel 50 µs to 1 ms after Read returned a 10 000-tool response, 20 runs per delay) the result was lost 20/20 times and notifications/cancelled was written 20/20 times on both versions. With the cancel fired after decoding had finished, 0/20 were lost. That pins the window to the decode duration.
Expected behavior
ListTools returns the decoded result. The response was received before the cancellation was observed, so the request is complete. No notifications/cancelled is written for it.
Expected output:
error: <nil>
tools: 3000
written: [server/discover tools/list]
Logs
Regression tests from the fix, run against main before the fix:
--- FAIL: TestAwaitPrefersDeliveredResponse (0.00s)
conn_test.go:56: iteration 1: Await() = context canceled, want nil for a delivered response
--- FAIL: TestAwaitPrefersDeliveredError (0.00s)
conn_test.go:74: iteration 0: Await() = context canceled, want bad params
--- FAIL: TestCallKeepsDeliveredResponseOnCancel (0.04s)
transport_test.go:476: ListTools() = context canceled, want the delivered result
Additional context
Specification, 2025-11-25, Cancellation, Behavior Requirements: "Cancellation notifications MUST only reference requests that: Were previously issued in the same direction; Are believed to still be in-progress."
https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/cancellation
The same requirement in 2026-07-28: https://modelcontextprotocol.io/specification/2026-07-28/basic/patterns/cancellation
Root cause:
mcp/transport.go:306(call):case ctx.Err() != nilis evaluated beforeerr == nil.internal/jsonrpc2/conn.go:434(AsyncCall.Await): the two-wayselectdoes not prefer a response that is already ready.
This is the client-side counterpart of #1259 (a cancelled request is still answered on the server). It is distinct from #1150, which made the cancellation notification non-blocking. The eager retirement from #1150 is kept by the fix.
SDK versions: v1.8.0 (3f3b699) and main at 3c0814798be7e813740406029e8efef07828f34f (2026-10-09).
Go version: go1.27.1 darwin/arm64.
I have a fix with regression tests ready and will open a pull request.
- Ngôn ngữ chính
- Go
- Star
- 5.3k
- Fork
- 606
- Merge trung bình
- 1 ngày 15 giờ
- Pull request đã merge (30 ngày)
- 75
Chuẩn bị môi trường
Khởi chạy dev container của dự án ngay trên trình duyệt, bằng tài khoản GitHub của bạn.
- Không có Dockerfile hay tệp Docker Compose
- Có mẫu pull request
- Đọc hướng dẫn đóng góp
Bắt đầu từ đâu
- Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
- Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
- Fork repository và làm thay đổi trên một nhánh.
- Mở pull request có tham chiếu số hiệu của issue.
Issue khác của modelcontextprotocol/go-sdk
-
Expose generic `SendNotification` on `ServerSession` for custom protocol extensionsCó thể làm lại được Pull request cho issue này đã bị đóng mà không được merge. Đang mởneeds investigation
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 72/100
modelcontextprotocol/go-sdk#745 · 13 bình luận · 1 reaction ·
Maintainer thường phản hồi trong vòng 1 ngày
-
mcp: ClientSession.CallTool omits Mcp-Param-* headers unless the tool is in the ListTools cache, so a call without a prior tools/list is rejectedCó thể đã có người làm @sundarshahi đã nhận 1 ngày trước. Đang mở
Độ khó 4/5 1-2 ngày Mức phù hợp với người mới 35/100
modelcontextprotocol/go-sdk#1481 · 1 bình luận ·
Maintainer thường phản hồi trong vòng 1 ngày
-
Độ khó 4/5 1-2 ngày Mức phù hợp với người mới 32/100
modelcontextprotocol/go-sdk#1480 ·
Maintainer thường phản hồi trong vòng 1 ngày
-
mcp: LoggingHandler drops records logged at custom slog levelsCó thể đã có người làm @kaankucukx đã nhận 8 ngày trước. Đang mở
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 45/100
modelcontextprotocol/go-sdk#1445 ·
Maintainer thường phản hồi trong vòng 1 ngày
-
mcp: Client.Connect falls back to initialize after a 401 on server/discover, running the authorization flow twiceCó thể đã có người làm @kerthans đã nhận 12 ngày trước. Đang mở
Độ khó 3/5 1-2 ngày Mức phù hợp với người mới 35/100
modelcontextprotocol/go-sdk#1423 · 1 bình luận ·
Maintainer thường phản hồi trong vòng 1 ngày
Tất cả issue của modelcontextprotocol/go-sdk
Issue tương tự
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 72/100
apache/arrow-swift#209 ·
Maintainer thường phản hồi trong vòng 1 ngày
-
orchestrator: NFS-cache "cache path is not set" WARN logged on every build/launch instead of onceCó thể đã có người làm Có pull request liên kết đang mở hoặc đã được merge. Đang mở
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 72/100
Maintainer thường phản hồi trong vòng 2 ngày
-
Độ khó 1/5 1-3 giờ Mức phù hợp với người mới 65/100
influxdata/telegraf#20031 ·
Maintainer thường phản hồi trong vòng 1 ngày
-
pkg/registry/file no longer builds for GOOS=windows: unguarded syscall.Stat_t in qualified_resource_migration.goCó thể đã có người làm @AnshulPatil2005 đã nhận hôm nay. Đang mở
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 78/100
Maintainer thường phản hồi trong vòng 1 ngày
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 74/100
OneBusAway/maglev#1914 ·
Maintainer thường phản hồi trong vòng 2 ngày