This is an automated email from the ASF dual-hosted git repository.
lizhimins pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/rocketmq-dashboard.git
The following commit(s) were added to refs/heads/master by this push:
new ec24d1f01 fix: preserve large MCP ids and keep stale 401 from logging
out newer session (#7373)
ec24d1f01 is described below
commit ec24d1f01974e687a181264aa192e8ec96a5e689
Author: bob <[email protected]>
AuthorDate: Fri Nov 27 11:48:03 2026 +0800
fix: preserve large MCP ids and keep stale 401 from logging out newer
session (#7373)
Integration batch (same author NUAAwqy): #7372 rmqctl MCP id precision +
#7373 stale-401 session epoch guard.
---
rmqctl/internal/studio/mcp_http.go | 209 +++++++++++++++++-
rmqctl/internal/studio/mcp_id_precision_test.go | 279 ++++++++++++++++++++++++
rmqctl/internal/studio/mcp_message.go | 83 ++++++-
web/src/api/ai.test.ts | 21 ++
web/src/api/ai.ts | 10 +-
web/src/api/client.test.ts | 19 ++
web/src/api/client.ts | 19 +-
web/src/stores/authStorage.ts | 10 +
8 files changed, 640 insertions(+), 10 deletions(-)
diff --git a/rmqctl/internal/studio/mcp_http.go
b/rmqctl/internal/studio/mcp_http.go
index 78307a619..2b77ee47f 100644
--- a/rmqctl/internal/studio/mcp_http.go
+++ b/rmqctl/internal/studio/mcp_http.go
@@ -17,10 +17,13 @@
package studio
import (
+ "bytes"
"encoding/json"
+ "errors"
"fmt"
"io"
"log/slog"
+ "math/big"
"net/http"
"net/url"
"strings"
@@ -132,8 +135,15 @@ type mcpStatusRoundTripper struct {
base http.RoundTripper
}
+// errMCPResponseIDMismatch is returned when a JSON-RPC response frame carries
+// a raw id token that differs from the originating request's. The SDK decodes
+// ids through float64, so an adjacent large integer would otherwise decode to
+// the same value and be silently accepted (issue #6904).
+var errMCPResponseIDMismatch = errors.New("MCP JSON-RPC response id does not
match the request id")
+
func (transport mcpStatusRoundTripper) RoundTrip(request *http.Request)
(*http.Response, error) {
- response, err := transport.base.RoundTrip(request)
+ exchange, requestID := mcpCorrelatedRequest(request)
+ response, err := transport.base.RoundTrip(exchange)
if err != nil {
return nil, err
}
@@ -149,9 +159,206 @@ func (transport mcpStatusRoundTripper) RoundTrip(request
*http.Request) (*http.R
_ = response.Body.Close()
return nil, statusError
}
+ if requestID != nil && response.StatusCode == http.StatusOK {
+ if err := correlateMCPResponseID(response, requestID); err !=
nil {
+ return nil, err
+ }
+ }
return response, nil
}
+// mcpCorrelatedRequest buffers a JSON-RPC POST so the raw top-level id token
+// can be compared against the response, and returns a replayable clone. The
+// original request is returned unchanged for anything that is not a JSON-RPC
+// request frame.
+func mcpCorrelatedRequest(request *http.Request) (*http.Request,
json.RawMessage) {
+ if request.Method != http.MethodPost || request.Body == nil ||
+ !strings.HasPrefix(request.Header.Get("Content-Type"),
"application/json") {
+ return request, nil
+ }
+ body, readErr := io.ReadAll(request.Body)
+ _ = request.Body.Close()
+ clone := request.Clone(request.Context())
+ clone.Body = io.NopCloser(bytes.NewReader(body))
+ clone.ContentLength = int64(len(body))
+ if readErr != nil {
+ return clone, nil
+ }
+ var fields map[string]json.RawMessage
+ if json.Unmarshal(body, &fields) != nil {
+ return clone, nil
+ }
+ if _, hasMethod := fields["method"]; !hasMethod {
+ return clone, nil
+ }
+ rawID, hasID := fields["id"]
+ if !hasID {
+ return clone, nil
+ }
+ return clone, rawID
+}
+
+// correlateMCPResponseID verifies that the response frame carries the exact
+// request identity before the SDK decodes it through float64. For JSON
+// responses the check happens eagerly; for POST SSE streams the body reader
+// enforces it as the response frame is consumed, so a mismatched frame never
+// reaches the transport's parser.
+func correlateMCPResponseID(response *http.Response, requestID
json.RawMessage) error {
+ contentType := strings.ToLower(response.Header.Get("Content-Type"))
+ switch {
+ case strings.HasPrefix(contentType, "application/json"):
+ body, err := io.ReadAll(response.Body)
+ _ = response.Body.Close()
+ response.Body = io.NopCloser(bytes.NewReader(body))
+ if err != nil {
+ return nil
+ }
+ var fields map[string]json.RawMessage
+ if json.Unmarshal(body, &fields) != nil {
+ return nil
+ }
+ rawID, hasID := fields["id"]
+ _, hasMethod := fields["method"]
+ if !hasID || hasMethod {
+ return nil
+ }
+ if !mcpIDTokensEqual(requestID, rawID) {
+ return fmt.Errorf("%w: request %s, response %s",
errMCPResponseIDMismatch, requestID, rawID)
+ }
+ return nil
+ case strings.HasPrefix(contentType, "text/event-stream"):
+ response.Body = &mcpSSEResponseIDReader{body: response.Body,
want: requestID}
+ return nil
+ default:
+ return nil
+ }
+}
+
+// mcpIDTokensEqual compares two raw JSON-RPC id tokens without decoding
+// numbers through float64: numeric tokens are compared by value (1 equals
1.0),
+// while a numeric and a string token never match.
+func mcpIDTokensEqual(a, b json.RawMessage) bool {
+ a = bytes.TrimSpace(a)
+ b = bytes.TrimSpace(b)
+ if bytes.Equal(a, b) {
+ return true
+ }
+ var an, bn json.Number
+ aNumber := json.Unmarshal(a, &an) == nil
+ bNumber := json.Unmarshal(b, &bn) == nil
+ if aNumber != bNumber {
+ return false
+ }
+ if !aNumber {
+ return false
+ }
+ ar, aOK := new(big.Rat).SetString(an.String())
+ br, bOK := new(big.Rat).SetString(bn.String())
+ return aOK && bOK && ar.Cmp(br) == 0
+}
+
+// mcpSSEResponseIDReader enforces the raw request identity on a POST SSE
+// stream. Complete events that are not the JSON-RPC response frame (id with
+// result or error, no method) are released immediately so server
+// notifications keep streaming; the response frame itself is released only
+// when its raw id token matches the request's, and a mismatched frame is
+// withheld and surfaced as a read error so the transport cannot accept it.
+type mcpSSEResponseIDReader struct {
+ body io.ReadCloser
+ want json.RawMessage
+ pending []byte
+ tail []byte
+ decided bool
+ mismatch error
+}
+
+func (reader *mcpSSEResponseIDReader) Read(p []byte) (int, error) {
+ for {
+ if len(reader.pending) > 0 {
+ n := copy(p, reader.pending)
+ reader.pending = reader.pending[n:]
+ return n, nil
+ }
+ if reader.mismatch != nil {
+ return 0, reader.mismatch
+ }
+ if reader.decided {
+ return reader.body.Read(p)
+ }
+ var chunk [4096]byte
+ n, err := reader.body.Read(chunk[:])
+ if n > 0 {
+ reader.tail = append(reader.tail, chunk[:n]...)
+ reader.scan()
+ }
+ if err != nil {
+ reader.decided = true
+ reader.pending = append(reader.pending, reader.tail...)
+ reader.tail = nil
+ }
+ }
+}
+
+func (reader *mcpSSEResponseIDReader) Close() error {
+ return reader.body.Close()
+}
+
+func (reader *mcpSSEResponseIDReader) scan() {
+ for {
+ idx := bytes.Index(reader.tail, []byte("\n\n"))
+ if idx < 0 {
+ return
+ }
+ event := reader.tail[:idx]
+ reader.tail = reader.tail[idx+2:]
+ frame, isResponse := mcpSSEFrameResponse(event)
+ matched := isResponse && mcpIDTokensEqual(reader.want, frame)
+ if isResponse {
+ reader.decided = true
+ reader.tail = nil
+ if !matched {
+ reader.mismatch = fmt.Errorf(
+ "%w: request %s, response %s",
errMCPResponseIDMismatch, reader.want, frame)
+ return
+ }
+ }
+ reader.pending = append(reader.pending, event...)
+ reader.pending = append(reader.pending, "\n\n"...)
+ }
+}
+
+// mcpSSEFrameResponse returns the raw id token when a complete SSE event
+// carries a JSON-RPC response frame.
+func mcpSSEFrameResponse(event []byte) (json.RawMessage, bool) {
+ var payload []byte
+ for _, line := range bytes.Split(event, []byte("\n")) {
+ line = bytes.TrimRight(line, "\r")
+ if !bytes.HasPrefix(line, []byte("data:")) {
+ continue
+ }
+ value := bytes.TrimLeft(bytes.TrimPrefix(line,
[]byte("data:")), " ")
+ if len(payload) > 0 {
+ payload = append(payload, '\n')
+ }
+ payload = append(payload, value...)
+ }
+ if len(payload) == 0 {
+ return nil, false
+ }
+ var fields map[string]json.RawMessage
+ if json.Unmarshal(payload, &fields) != nil {
+ return nil, false
+ }
+ _, hasMethod := fields["method"]
+ _, hasResult := fields["result"]
+ _, hasError := fields["error"]
+ rawID, hasID := fields["id"]
+ if hasID && !hasMethod && (hasResult || hasError) {
+ return rawID, true
+ }
+ return nil, false
+}
+
type mcpHTTPErrorBody struct {
Code string `json:"code"`
Message string `json:"message"`
diff --git a/rmqctl/internal/studio/mcp_id_precision_test.go
b/rmqctl/internal/studio/mcp_id_precision_test.go
new file mode 100644
index 000000000..45b9bed6f
--- /dev/null
+++ b/rmqctl/internal/studio/mcp_id_precision_test.go
@@ -0,0 +1,279 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package studio
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "net/http"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/mark3labs/mcp-go/mcp"
+)
+
+// The SDK decodes JSON-RPC request ids and notification params.requestId
+// values through float64, which silently rounds integers beyond 2^53. The
+// bridge must preserve the original textual identity on the wire, in the
+// returned response payload, and when forwarding cancellations, and it must
+// reject a response whose raw id token differs from the request's.
+// See issue #6904.
+
+type mcpIDPeer struct {
+ mu sync.Mutex
+ bodies map[string][]byte
+}
+
+func newMCPIDPeer() *mcpIDPeer {
+ return &mcpIDPeer{bodies: map[string][]byte{}}
+}
+
+func (peer *mcpIDPeer) record(payload observedMCPPayload) {
+ peer.mu.Lock()
+ defer peer.mu.Unlock()
+ peer.bodies[payload.Method] = append([]byte(nil), payload.Raw...)
+}
+
+func (peer *mcpIDPeer) body(method string) []byte {
+ peer.mu.Lock()
+ defer peer.mu.Unlock()
+ return peer.bodies[method]
+}
+
+func mcpIDPeerTransport(t *testing.T, peer *mcpIDPeer, respond
func(observedMCPPayload) *http.Response) roundTripFunc {
+ return func(request *http.Request) (*http.Response, error) {
+ switch request.Method {
+ case http.MethodDelete:
+ return mcpHTTPResponse(http.StatusNoContent, "", ""),
nil
+ case http.MethodPost:
+ payload := readMCPPayload(t, request)
+ peer.record(payload)
+ switch payload.Method {
+ case string(mcp.MethodInitialize):
+ response := mcpJSONResultResponse(payload.ID,
map[string]any{
+ "protocolVersion":
mcp.LATEST_PROTOCOL_VERSION,
+ "capabilities": map[string]any{},
+ "serverInfo":
map[string]any{"name": "studio", "version": "1"},
+ })
+ return response, nil
+ case string(mcp.MethodNotificationInitialized):
+ return mcpHTTPResponse(http.StatusAccepted, "",
""), nil
+ default:
+ return respond(payload), nil
+ }
+ default:
+ return mcpHTTPResponse(http.StatusMethodNotAllowed,
"text/plain", "method not allowed"), nil
+ }
+ }
+}
+
+func newMCPIDTestSession(t *testing.T, transport roundTripFunc)
(*MCPClientSession, context.Context) {
+ t.Helper()
+ client := NewClient(&http.Client{Transport: transport})
+ session := newMCPTestSession(t, client, Target{
+ Server: "http://localhost", InstanceID: "instance-dev",
+ Credential: Credential{AccessKey: "test-ak", SecretKey:
"test-sk"}, Timeout: 2 * time.Second,
+ })
+ ctx, cancel := context.WithCancel(context.Background())
+ t.Cleanup(cancel)
+ initializeClientSession(t, ctx, session)
+ return session, ctx
+}
+
+func toolsListResult(id json.RawMessage) *http.Response {
+ return mcpJSONResultResponse(id, map[string]any{"tools": []any{}})
+}
+
+// sendToolsListWithID runs one tools/list exchange with the given raw id
token and
+// returns the response payload sent to the stdio client.
+func sendToolsListWithID(t *testing.T, session *MCPClientSession, ctx
context.Context, idToken string) json.RawMessage {
+ t.Helper()
+ response, ok, err := session.SendMessage(ctx, json.RawMessage(
+
`{"jsonrpc":"2.0","id":`+idToken+`,"method":"tools/list","params":{}}`))
+ if err != nil || !ok {
+ t.Fatalf("tools/list id=%s = ok:%t err:%v", idToken, ok, err)
+ }
+ return response
+}
+
+func assertWireAndReturnedID(t *testing.T, peer *mcpIDPeer, response
json.RawMessage, want string) {
+ t.Helper()
+ sent := peer.body(string(mcp.MethodToolsList))
+ if !bytes.Contains(sent, []byte(`"id":`+want)) {
+ t.Errorf("wire request id was changed, body = %s", sent)
+ }
+ if !bytes.Contains(response, []byte(`"id":`+want)) {
+ t.Errorf("returned response id was changed, payload = %s",
response)
+ }
+}
+
+// Defect scenario 1: a numeric id beyond 2^53 echoed by the peer must be sent
+// and returned exactly.
+func TestLargeNumericRequestIDIsPreserved(t *testing.T) {
+ peer := newMCPIDPeer()
+ session, ctx := newMCPIDTestSession(t, mcpIDPeerTransport(t, peer,
func(payload observedMCPPayload) *http.Response {
+ return toolsListResult(payload.ID)
+ }))
+ response := sendToolsListWithID(t, session, ctx, `9007199254740993`)
+ assertWireAndReturnedID(t, peer, response, `9007199254740993`)
+}
+
+// Defect scenario 2: the same for the int64 maximum.
+func TestInt64MaxRequestIDIsPreserved(t *testing.T) {
+ peer := newMCPIDPeer()
+ session, ctx := newMCPIDTestSession(t, mcpIDPeerTransport(t, peer,
func(payload observedMCPPayload) *http.Response {
+ return toolsListResult(payload.ID)
+ }))
+ response := sendToolsListWithID(t, session, ctx, `9223372036854775807`)
+ assertWireAndReturnedID(t, peer, response, `9223372036854775807`)
+}
+
+// Defect scenario 3: a response whose id is the rounded neighbour of the
+// request id must be rejected instead of silently accepted.
+func TestAdjacentResponseIDIsRejected(t *testing.T) {
+ peer := newMCPIDPeer()
+ session, ctx := newMCPIDTestSession(t, mcpIDPeerTransport(t, peer,
func(payload observedMCPPayload) *http.Response {
+ return toolsListResult(json.RawMessage(`9007199254740992`))
+ }))
+ _, ok, err := session.SendMessage(ctx, json.RawMessage(
+
`{"jsonrpc":"2.0","id":9007199254740993,"method":"tools/list","params":{}}`))
+ if err == nil || ok {
+ t.Fatalf("adjacent response id was accepted: ok:%t err:%v", ok,
err)
+ }
+}
+
+// Defect scenario 4: a large numeric params.requestId in a cancellation must
+// be forwarded exactly.
+func TestLargeCancellationRequestIDIsPreserved(t *testing.T) {
+ peer := newMCPIDPeer()
+ session, ctx := newMCPIDTestSession(t, mcpIDPeerTransport(t, peer,
func(payload observedMCPPayload) *http.Response {
+ return mcpHTTPResponse(http.StatusAccepted, "", "")
+ }))
+ if _, ok, err := session.SendMessage(ctx, json.RawMessage(
+
`{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":9007199254740993}}`));
err != nil || ok {
+ t.Fatalf("notifications/cancelled = ok:%t err:%v", ok, err)
+ }
+ sent := peer.body(string(mcp.MethodNotificationCancelled))
+ if !bytes.Contains(sent, []byte(`"requestId":9007199254740993`)) {
+ t.Errorf("cancellation requestId was changed, body = %s", sent)
+ }
+}
+
+// Defect scenario 3 over the POST SSE response channel: the mismatched frame
+// must be withheld even when it arrives as a stream rather than a JSON body.
+func TestAdjacentResponseIDIsRejectedOverSSE(t *testing.T) {
+ peer := newMCPIDPeer()
+ session, ctx := newMCPIDTestSession(t, mcpIDPeerTransport(t, peer,
func(payload observedMCPPayload) *http.Response {
+ return mcpHTTPResponse(http.StatusOK, "text/event-stream",
+ "event: message\ndata:
{\"jsonrpc\":\"2.0\",\"id\":9007199254740992,\"result\":{\"tools\":[]}}\n\n")
+ }))
+ _, ok, err := session.SendMessage(ctx, json.RawMessage(
+
`{"jsonrpc":"2.0","id":9007199254740993,"method":"tools/list","params":{}}`))
+ if err == nil || ok {
+ t.Fatalf("adjacent SSE response id was accepted: ok:%t err:%v",
ok, err)
+ }
+}
+
+// Control: small numeric ids keep their exact (unchanged) representation.
+func TestSmallNumericRequestIDIsPreserved(t *testing.T) {
+ peer := newMCPIDPeer()
+ session, ctx := newMCPIDTestSession(t, mcpIDPeerTransport(t, peer,
func(payload observedMCPPayload) *http.Response {
+ return toolsListResult(payload.ID)
+ }))
+ response := sendToolsListWithID(t, session, ctx, `7`)
+ assertWireAndReturnedID(t, peer, response, `7`)
+}
+
+// Control: string ids are forwarded and returned exactly.
+func TestStringRequestIDIsPreserved(t *testing.T) {
+ peer := newMCPIDPeer()
+ session, ctx := newMCPIDTestSession(t, mcpIDPeerTransport(t, peer,
func(payload observedMCPPayload) *http.Response {
+ return toolsListResult(payload.ID)
+ }))
+ response, ok, err := session.SendMessage(ctx, json.RawMessage(
+
`{"jsonrpc":"2.0","id":"list-7","method":"tools/list","params":{}}`))
+ if err != nil || !ok {
+ t.Fatalf("tools/list = ok:%t err:%v", ok, err)
+ }
+ sent := peer.body(string(mcp.MethodToolsList))
+ if !bytes.Contains(sent, []byte(`"id":"list-7"`)) {
+ t.Errorf("wire request id was changed, body = %s", sent)
+ }
+ if !bytes.Contains(response, []byte(`"id":"list-7"`)) {
+ t.Errorf("returned response id was changed, payload = %s",
response)
+ }
+}
+
+// Control: a string response id for a numeric request id stays rejected.
+func TestStringResponseIDForNumericRequestIsRejected(t *testing.T) {
+ peer := newMCPIDPeer()
+ session, ctx := newMCPIDTestSession(t, mcpIDPeerTransport(t, peer,
func(payload observedMCPPayload) *http.Response {
+ return toolsListResult(json.RawMessage(`"7"`))
+ }))
+ _, ok, err := session.SendMessage(ctx, json.RawMessage(
+ `{"jsonrpc":"2.0","id":7,"method":"tools/list","params":{}}`))
+ if err == nil || ok {
+ t.Fatalf("type-mismatched response id was accepted: ok:%t
err:%v", ok, err)
+ }
+}
+
+// Control: a numeric response id for a string request id stays rejected.
+func TestNumericResponseIDForStringRequestIsRejected(t *testing.T) {
+ peer := newMCPIDPeer()
+ session, ctx := newMCPIDTestSession(t, mcpIDPeerTransport(t, peer,
func(payload observedMCPPayload) *http.Response {
+ return toolsListResult(json.RawMessage(`7`))
+ }))
+ _, ok, err := session.SendMessage(ctx, json.RawMessage(
+ `{"jsonrpc":"2.0","id":"7","method":"tools/list","params":{}}`))
+ if err == nil || ok {
+ t.Fatalf("type-mismatched response id was accepted: ok:%t
err:%v", ok, err)
+ }
+}
+
+// Control: small numeric cancellation request ids are forwarded unchanged.
+func TestSmallCancellationRequestIDIsPreserved(t *testing.T) {
+ peer := newMCPIDPeer()
+ session, ctx := newMCPIDTestSession(t, mcpIDPeerTransport(t, peer,
func(payload observedMCPPayload) *http.Response {
+ return mcpHTTPResponse(http.StatusAccepted, "", "")
+ }))
+ if _, ok, err := session.SendMessage(ctx, json.RawMessage(
+
`{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":7}}`));
err != nil || ok {
+ t.Fatalf("notifications/cancelled = ok:%t err:%v", ok, err)
+ }
+ sent := peer.body(string(mcp.MethodNotificationCancelled))
+ if !bytes.Contains(sent, []byte(`"requestId":7`)) {
+ t.Errorf("cancellation requestId was changed, body = %s", sent)
+ }
+}
+
+// Control: string cancellation request ids are forwarded unchanged.
+func TestStringCancellationRequestIDIsPreserved(t *testing.T) {
+ peer := newMCPIDPeer()
+ session, ctx := newMCPIDTestSession(t, mcpIDPeerTransport(t, peer,
func(payload observedMCPPayload) *http.Response {
+ return mcpHTTPResponse(http.StatusAccepted, "", "")
+ }))
+ if _, ok, err := session.SendMessage(ctx, json.RawMessage(
+
`{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":"c-1"}}`));
err != nil || ok {
+ t.Fatalf("notifications/cancelled = ok:%t err:%v", ok, err)
+ }
+ sent := peer.body(string(mcp.MethodNotificationCancelled))
+ if !bytes.Contains(sent, []byte(`"requestId":"c-1"`)) {
+ t.Errorf("cancellation requestId was changed, body = %s", sent)
+ }
+}
diff --git a/rmqctl/internal/studio/mcp_message.go
b/rmqctl/internal/studio/mcp_message.go
index 41f3d2360..bbf0b9b34 100644
--- a/rmqctl/internal/studio/mcp_message.go
+++ b/rmqctl/internal/studio/mcp_message.go
@@ -17,6 +17,7 @@
package studio
import (
+ "bytes"
"context"
"encoding/json"
"errors"
@@ -55,7 +56,7 @@ func (session *MCPClientSession) SendMessage(ctx
context.Context, payload json.R
defer cancel()
if decoded.request != nil {
- return session.sendRequest(callCtx, *decoded.request)
+ return session.sendRequest(callCtx, *decoded.request,
decoded.rawID)
}
return nil, false, session.sendNotification(callCtx,
*decoded.notification)
}
@@ -63,6 +64,11 @@ func (session *MCPClientSession) SendMessage(ctx
context.Context, payload json.R
type decodedMCPMessage struct {
request *mcptransport.JSONRPCRequest
notification *mcp.JSONRPCNotification
+ // rawID is the untouched top-level "id" token of a request frame. The
SDK
+ // decodes numeric identities through float64, which silently rounds
+ // integers beyond 2^53, so the bridge keeps the original text to
preserve
+ // the request identity end to end (issue #6904).
+ rawID json.RawMessage
}
func decodeMCPMessage(payload json.RawMessage) (decodedMCPMessage, error) {
@@ -80,13 +86,18 @@ func decodeMCPMessage(payload json.RawMessage)
(decodedMCPMessage, error) {
if err := json.Unmarshal(payload, &request); err != nil {
return decodedMCPMessage{}, fmt.Errorf("invalid MCP
JSON-RPC request: %w", err)
}
- return decodedMCPMessage{request: &request}, nil
+ request.ID = exactRequestID(fields["id"], request.ID)
+ return decodedMCPMessage{request: &request, rawID:
fields["id"]}, nil
}
if hasMethod {
var notification mcp.JSONRPCNotification
if err := json.Unmarshal(payload, ¬ification); err != nil {
return decodedMCPMessage{}, fmt.Errorf("invalid MCP
JSON-RPC notification: %w", err)
}
+ // notifications/cancelled carries params.requestId; the SDK
decodes
+ // notification params into map[string]any, so a large numeric
identity
+ // would be rounded the same way (issue #6904).
+ notification.Params =
exactNotificationRequestID(fields["params"], notification.Params)
return decodedMCPMessage{notification: ¬ification}, nil
}
if hasID {
@@ -100,9 +111,71 @@ func decodeMCPMessage(payload json.RawMessage)
(decodedMCPMessage, error) {
return decodedMCPMessage{}, fmt.Errorf("invalid MCP JSON-RPC message:
missing method")
}
+// exactRequestID returns a RequestId that re-encodes a numeric identity with
+// its original textual representation. The SDK decodes JSON numbers through
+// float64, which silently rounds integers beyond 2^53; json.Number marshals
+// verbatim, so the wire identity stays exact. String and null identities are
+// already preserved by the SDK and returned unchanged.
+func exactRequestID(raw json.RawMessage, decoded mcp.RequestId) mcp.RequestId {
+ if number, ok := jsonNumberToken(raw); ok {
+ return mcp.NewRequestId(number)
+ }
+ return decoded
+}
+
+// exactNotificationRequestID restores the original textual representation of a
+// numeric params.requestId that the SDK decoded into AdditionalFields as a
+// float64 (issue #6904).
+func exactNotificationRequestID(rawParams json.RawMessage, params
mcp.NotificationParams) mcp.NotificationParams {
+ var fields map[string]json.RawMessage
+ if len(rawParams) == 0 || json.Unmarshal(rawParams, &fields) != nil {
+ return params
+ }
+ number, ok := jsonNumberToken(fields["requestId"])
+ if !ok {
+ return params
+ }
+ if params.AdditionalFields == nil {
+ params.AdditionalFields = map[string]any{}
+ }
+ params.AdditionalFields["requestId"] = number
+ return params
+}
+
+// jsonNumberToken reports whether a raw JSON token is a number and returns it
+// as a json.Number.
+func jsonNumberToken(raw json.RawMessage) (json.Number, bool) {
+ token := bytes.TrimSpace(raw)
+ if len(token) == 0 || (token[0] != '-' && (token[0] < '0' || token[0] >
'9')) {
+ return "", false
+ }
+ var number json.Number
+ if err := json.Unmarshal(token, &number); err != nil {
+ return "", false
+ }
+ return number, true
+}
+
+// mcpRequestIDEquivalent compares the decoded response identity against the
+// request identity normalized the way the SDK decodes it. A request carrying
+// an exact json.Number never string-matches a float64-rounded response, so the
+// raw token is re-decoded for the comparison; genuinely different tokens are
+// already rejected at the HTTP layer (see mcpStatusRoundTripper).
+func mcpRequestIDEquivalent(rawID json.RawMessage, requestID, responseID
mcp.RequestId) bool {
+ if requestID.String() == responseID.String() {
+ return true
+ }
+ var normalized mcp.RequestId
+ if err := json.Unmarshal(rawID, &normalized); err != nil {
+ return false
+ }
+ return normalized.String() == responseID.String()
+}
+
func (session *MCPClientSession) sendRequest(
ctx context.Context,
request mcptransport.JSONRPCRequest,
+ rawID json.RawMessage,
) (json.RawMessage, bool, error) {
var response *mcptransport.JSONRPCResponse
err := session.sendWithReconnect(ctx, request.Method ==
string(mcp.MethodInitialize), func() error {
@@ -116,11 +189,15 @@ func (session *MCPClientSession) sendRequest(
if response == nil {
return nil, false, fmt.Errorf("empty MCP JSON-RPC response")
}
- if response.ID.String() != request.ID.String() {
+ if !mcpRequestIDEquivalent(rawID, request.ID, response.ID) {
return nil, false, fmt.Errorf(
"MCP JSON-RPC response id %s does not match request id
%s",
response.ID.String(), request.ID.String())
}
+ // The HTTP layer has already compared the raw id tokens on the wire;
the
+ // decoded response id may still be rounded, so return the exact
outgoing
+ // identity to the stdio client (issue #6904).
+ response.ID = request.ID
if request.Method == string(mcp.MethodInitialize) && response.Error ==
nil {
if err := session.recordInitialization(request, response); err
!= nil {
return nil, false, err
diff --git a/web/src/api/ai.test.ts b/web/src/api/ai.test.ts
index b94daa7e9..3ddb6838a 100644
--- a/web/src/api/ai.test.ts
+++ b/web/src/api/ai.test.ts
@@ -18,6 +18,7 @@
import MockAdapter from 'axios-mock-adapter';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import client from './client';
+import { persistAuthSession } from '../stores/authStorage';
import {
AiStreamError,
attachRunStream,
@@ -641,6 +642,26 @@ describe('AI API', () => {
expect(localStorage.getItem('rocketmq-studio-user-admin')).toBeNull();
});
+ it('preserves a newer login when a stale stream request returns 401',
async () => {
+ localStorage.setItem('rocketmq-studio-user', 'old-admin');
+ localStorage.setItem('rocketmq-studio-user-admin', 'true');
+ vi.stubGlobal(
+ 'fetch',
+ vi
+ .fn()
+ .mockImplementation(async () =>
+ jsonResponse({ code: 401, message: 'Unauthorized', data: null },
401, 'Unauthorized'),
+ ),
+ );
+
+ const pending = openRunStream(7, body, { onEvent: vi.fn() });
+ persistAuthSession('new-admin', 2, true);
+
+ await expect(pending).rejects.toMatchObject({ status: 401 });
+ expect(localStorage.getItem('rocketmq-studio-user')).toBe('new-admin');
+ expect(localStorage.getItem('rocketmq-studio-user-admin')).toBe('true');
+ });
+
it('timesOutWhenNoByteArrivesForTwiceTheServerHeartbeatTest', async () => {
vi.useFakeTimers();
const onCancel = vi.fn();
diff --git a/web/src/api/ai.ts b/web/src/api/ai.ts
index 15cd472be..8ea339d8d 100644
--- a/web/src/api/ai.ts
+++ b/web/src/api/ai.ts
@@ -17,6 +17,7 @@
import { API_BASE_URL } from '../config';
import client, { handleSessionUnauthorized } from './client';
+import { currentSessionEpoch } from '../stores/authStorage';
import { conversationMessagesPath, runStreamPath, type AiMessageRequest } from
'./aiConversations';
import { LIVE_EVENT_TYPES, type ChatSseEvent } from './aiEvents';
@@ -349,9 +350,10 @@ async function consumeRunStream(
response: Response,
handlers: RunStreamHandlers,
label: string,
+ sessionEpoch: number,
): Promise<void> {
if (response.status === 401) {
- handleSessionUnauthorized();
+ handleSessionUnauthorized(sessionEpoch);
}
// A non-2xx body is a JSON `Result` envelope, not an event stream, so it is
parsed before the
// content-type guard gets a chance to complain about it.
@@ -390,6 +392,7 @@ export async function openRunStream(
handlers: RunStreamHandlers,
signal?: AbortSignal,
): Promise<void> {
+ const sessionEpoch = currentSessionEpoch();
const response = await
fetch(`${API_BASE_URL}${conversationMessagesPath(conversationId)}`, {
method: 'POST',
credentials: 'include',
@@ -401,7 +404,7 @@ export async function openRunStream(
signal,
});
- await consumeRunStream(response, handlers, 'AI message stream failed');
+ await consumeRunStream(response, handlers, 'AI message stream failed',
sessionEpoch);
}
/**
@@ -417,6 +420,7 @@ export async function attachRunStream(
handlers: RunStreamHandlers,
signal?: AbortSignal,
): Promise<void> {
+ const sessionEpoch = currentSessionEpoch();
const query = new URLSearchParams({ after: String(after) });
const response = await
fetch(`${API_BASE_URL}${runStreamPath(runId)}?${query.toString()}`, {
method: 'GET',
@@ -427,7 +431,7 @@ export async function attachRunStream(
signal,
});
- await consumeRunStream(response, handlers, 'AI run stream failed');
+ await consumeRunStream(response, handlers, 'AI run stream failed',
sessionEpoch);
}
export async function listTools(instanceId?: string) {
diff --git a/web/src/api/client.test.ts b/web/src/api/client.test.ts
index 7701579e7..8b3c7d6b6 100644
--- a/web/src/api/client.test.ts
+++ b/web/src/api/client.test.ts
@@ -19,6 +19,7 @@ import MockAdapter from 'axios-mock-adapter';
import { message } from 'antd';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import client from './client';
+import { persistAuthSession } from '../stores/authStorage';
vi.mock('antd', () => ({
message: {
@@ -158,6 +159,24 @@ describe('API client response contract', () => {
expect(message.error).not.toHaveBeenCalled();
});
+ it('preserves a newer login when a stale protected request returns 401',
async () => {
+ localStorage.setItem('rocketmq-studio-user', 'old-admin');
+ localStorage.setItem('rocketmq-studio-user-admin', 'true');
+ mock.onGet('/clusters').reply(401, { code: 401, message: 'Unauthorized',
data: null });
+
+ const pending = client.get('/clusters');
+ const rejected = expect(pending).rejects.toMatchObject({ response: {
status: 401 } });
+ // Let the request interceptor stamp the epoch of the old login before the
+ // superseding login happens.
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ persistAuthSession('new-admin', 2, true);
+
+ await rejected;
+
+ expect(localStorage.getItem('rocketmq-studio-user')).toBe('new-admin');
+ expect(localStorage.getItem('rocketmq-studio-user-admin')).toBe('true');
+ });
+
it('preserves the original 401 error when the request URL is malformed',
async () => {
mock.onGet('http://[').reply(401, { code: 401, message: 'Unauthorized',
data: null });
diff --git a/web/src/api/client.ts b/web/src/api/client.ts
index cb05680e8..77604949c 100644
--- a/web/src/api/client.ts
+++ b/web/src/api/client.ts
@@ -17,7 +17,7 @@
import axios from 'axios';
import { message } from 'antd';
-import { clearAuthSession } from '../stores/authStorage';
+import { clearAuthSession, currentSessionEpoch } from '../stores/authStorage';
import { API_BASE_URL } from '../config';
const SUCCESS_BUSINESS_CODES = new Set([0, 200]);
@@ -78,7 +78,12 @@ function isPublicAuthRequest(url?: string): boolean {
}
}
-export function handleSessionUnauthorized(): void {
+export function handleSessionUnauthorized(requestEpoch?: number): void {
+ if (requestEpoch !== undefined && requestEpoch !== currentSessionEpoch()) {
+ // The 401 belongs to a login that has since been replaced; leave the
current
+ // session and its redirect alone.
+ return;
+ }
clearAuthSession();
// Carry the page the operator was on so the login flow can return to it
after
// re-authenticating; an expired session while already on /login must not
self-reference.
@@ -94,6 +99,13 @@ const client = axios.create({
withCredentials: true,
});
+// Record the login each request belongs to so the response interceptor can
tell a
+// late 401 from an earlier login apart from the current session expiring.
+client.interceptors.request.use((config) => {
+ Object.assign(config, { sessionEpoch: currentSessionEpoch() });
+ return config;
+});
+
// Response interceptor: check business code and handle 401
client.interceptors.response.use(
(response) => {
@@ -106,7 +118,8 @@ client.interceptors.response.use(
},
(error) => {
if (error.response?.status === 401 &&
!isPublicAuthRequest(error.config?.url)) {
- handleSessionUnauthorized();
+ const requestEpoch = (error.config as { sessionEpoch?: number } |
undefined)?.sessionEpoch;
+ handleSessionUnauthorized(requestEpoch);
return Promise.reject(error);
}
if (isCorsRejection(error)) {
diff --git a/web/src/stores/authStorage.ts b/web/src/stores/authStorage.ts
index d060dcd77..784efb563 100644
--- a/web/src/stores/authStorage.ts
+++ b/web/src/stores/authStorage.ts
@@ -35,6 +35,14 @@ function parseUserId(raw: string | null): number | null {
return Number.isFinite(parsed) ? parsed : null;
}
+// Identifies which login owns an in-flight request: every login or logout
bumps the
+// epoch, so a 401 that started under a superseded login can be recognized as
stale.
+let sessionEpoch = 0;
+
+export function currentSessionEpoch(): number {
+ return sessionEpoch;
+}
+
export function readAuthSession(): AuthSession {
const admin = readLocalStorage(USER_ADMIN_STORAGE_KEY);
return {
@@ -45,6 +53,7 @@ export function readAuthSession(): AuthSession {
}
export function persistAuthSession(user: string, userId: number | null, admin:
boolean): void {
+ sessionEpoch += 1;
const userWritten = writeLocalStorage(USER_STORAGE_KEY, user);
const userIdWritten =
userId != null
@@ -59,6 +68,7 @@ export function persistAuthSession(user: string, userId:
number | null, admin: b
}
export function clearAuthSession(): void {
+ sessionEpoch += 1;
removeLocalStorage('token');
removeLocalStorage(USER_STORAGE_KEY);
removeLocalStorage(USER_ID_STORAGE_KEY);