Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat(mcp): upgrade go-sdk to v1.7.0 and migrate elicitation to multi round-trip (#21299)
Vincent Huang75e8f4bd90d5
diff --git a/backend/api/mcp/internal_transport_test.go b/backend/api/mcp/internal_transport_test.goindex c8534b9a2d..43353b0c1f 100644--- a/backend/api/mcp/internal_transport_test.go+++ b/backend/api/mcp/internal_transport_test.go@@ -115,7 +115,7 @@ func TestMCPAuthMiddlewareLegacySessionEmptyGrantState(t *testing.T) {// TestApiRequestMintsCredentialPerCall is the session-lifetime pin. The MCP SDK// hands every tool handler the context of the request that CREATED the session-// (go-sdk v1.6.1 streamable.go: server.Connect(req.Context(), ...)), so anything+// (go-sdk v1.7.0 streamable.go: connectStreamable(req.Context(), ...)), so anything// the boundary stashes in that context is frozen at session start. A credential// minted there would carry a fixed expiry and brick every tool call once its// short TTL elapsed — while the session stays open, since /mcp never re-runsdiff --git a/backend/api/mcp/protocol_ceiling_test.go b/backend/api/mcp/protocol_ceiling_test.gonew file mode 100644index 0000000000..cc32a04f02--- /dev/null+++ b/backend/api/mcp/protocol_ceiling_test.go@@ -0,0 +1,249 @@+package mcp++import (+ "context"+ "fmt"+ "io"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/golang-jwt/jwt/v5"+ "github.com/labstack/echo/v5"+ "github.com/modelcontextprotocol/go-sdk/mcp"+ "github.com/stretchr/testify/require"++ "github.com/bytebase/bytebase/backend/common"+ "github.com/bytebase/bytebase/backend/component/config"+)++// newProbeServer stands up the real /mcp route over an internal API that+// records the credential of every internal call it receives.+func newProbeServer(t *testing.T) (endpoint string, credentials *[]string, mu *sync.Mutex) {+ t.Helper()+ var (+ lock sync.Mutex+ creds []string+ )+ stub := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ lock.Lock()+ creds = append(creds, strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer "))+ lock.Unlock()+ w.WriteHeader(http.StatusOK)+ fmt.Fprint(w, `{}`)+ })+ profile := &config.Profile{Mode: common.ReleaseModeDev, ExternalURL: "https://bb.example.com"}+ s, err := newServerWithStore(newTestServerStore(), profile, revalidationSecret, stub)+ require.NoError(t, err)++ e := echo.New()+ s.RegisterRoutes(e)+ ts := httptest.NewServer(e)+ t.Cleanup(ts.Close)+ return ts.URL + mcpResourcePath, &creds, &lock+}++// callAPITool drives one tool call that reaches the internal API.+func callAPITool(t *testing.T, session *mcp.ClientSession) {+ t.Helper()+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)+ defer cancel()+ _, err := session.CallTool(ctx, &mcp.CallToolParams{+ Name: "call_api",+ Arguments: map[string]any{"operationId": "SQLService/Query"},+ })+ require.NoError(t, err)+}++// claim reads one claim out of an internal delegated credential. The signature+// is checked elsewhere; here the credential is only being observed.+func claim(t *testing.T, credential, name string) string {+ t.Helper()+ parsed, _, err := jwt.NewParser().ParseUnverified(credential, jwt.MapClaims{})+ require.NoError(t, err)+ claims, ok := parsed.Claims.(jwt.MapClaims)+ require.True(t, ok)+ value, ok := claims[name].(string)+ require.True(t, ok, "credential must carry a string %q claim", name)+ return value+}++// TestSessionlessProtocolRefused pins that /mcp answers a request announcing+// the sessionless revision with 400 rather than serving it.+//+// The SDK refuses that revision itself for every method but server/discover,+// which it answers on a stateful transport by opening a session the client is+// never told about and can never delete. go-sdk v1.7.0 clients send exactly+// that request on every connect, so without this refusal each connect strands+// one session for the life of the process.+func TestSessionlessProtocolRefused(t *testing.T) {+ endpoint, _, _ := newProbeServer(t)+ token := mintMCPToken(t, "[email protected]", "client-A", "ws-test", "mcp:read-only", time.Hour)++ // Verbatim from a go-sdk v1.7.0 client's first POST. Without the refusal the+ // SDK answers this 200 and keeps the session it opened to do so.+ discover := `{"jsonrpc":"2.0","id":1,"method":"server/discover","params":{"_meta":{` ++ `"io.modelcontextprotocol/clientCapabilities":{"roots":{"listChanged":true}},` ++ `"io.modelcontextprotocol/clientInfo":{"name":"probe","version":"0"},` ++ `"io.modelcontextprotocol/protocolVersion":"2026-07-28"}}}`+ req, err := http.NewRequest(http.MethodPost, endpoint, strings.NewReader(discover))+ require.NoError(t, err)+ req.Header.Set("Content-Type", "application/json")+ req.Header.Set("Accept", "application/json, text/event-stream")+ req.Header.Set("Authorization", "Bearer "+token)+ req.Header.Set("MCP-Protocol-Version", sessionlessProtocolVersion)+ req.Header.Set("Mcp-Method", "server/discover")++ resp, err := http.DefaultClient.Do(req)+ require.NoError(t, err)+ body, err := io.ReadAll(resp.Body)+ require.NoError(t, resp.Body.Close())+ require.NoError(t, err)++ require.Equal(t, http.StatusBadRequest, resp.StatusCode,+ "a revision this transport cannot serve must be refused, not served into a stranded session")+ require.Contains(t, string(body), "unsupported protocol version",+ "the refusal must be ours: reaching the SDK means it opened a session to answer")+}++// TestSessionlessProtocolRefusalKeepsClientsWorking pins that the refusal costs+// nothing. A go-sdk v1.7.0 client probes for the sessionless revision first and+// falls back to the initialize handshake on any error, so it still connects and+// still runs tools.+func TestSessionlessProtocolRefusalKeepsClientsWorking(t *testing.T) {+ endpoint, credentials, mu := newProbeServer(t)+ token := mintMCPToken(t, "[email protected]", "client-A", "ws-test", "mcp:read-only", time.Hour)++ session := connectLegacy(t, endpoint, token, nil)+ callAPITool(t, session)++ mu.Lock()+ defer mu.Unlock()+ require.Len(t, *credentials, 1, "the tool call must still reach the internal API")+}++// TestRequestBodyCapRejectsBeforeDispatch pins the ingestion bound. A body over+// the cap is refused during the read, so an oversized script never reaches a+// tool — and never reaches the internal API behind it.+func TestRequestBodyCapRejectsBeforeDispatch(t *testing.T) {+ endpoint, credentials, mu := newProbeServer(t)+ token := mintMCPToken(t, "[email protected]", "client-A", "ws-test", "mcp:read-only", time.Hour)++ oversized := strings.Repeat("x", mcp.DefaultMaxRequestBodyBytes+(1<<16))+ body := fmt.Sprintf(`{"jsonrpc":"2.0","id":1,"method":"tools/call","params":`++ `{"name":"propose_database_change","arguments":{"database":"db","title":"t","sql":%q}}}`, oversized)+ req, err := http.NewRequest(http.MethodPost, endpoint, strings.NewReader(body))+ require.NoError(t, err)+ req.Header.Set("Content-Type", "application/json")+ req.Header.Set("Accept", "application/json, text/event-stream")+ req.Header.Set("Authorization", "Bearer "+token)++ resp, err := http.DefaultClient.Do(req)+ require.NoError(t, err)+ require.NoError(t, resp.Body.Close())+ require.Equal(t, http.StatusRequestEntityTooLarge, resp.StatusCode)++ mu.Lock()+ defer mu.Unlock()+ require.Empty(t, *credentials, "an over-limit body must be refused before any tool dispatch")+}++// TestRequestBodyCapEndsTheSession records what tripping the cap costs. The+// transport answers a bare 413, which the SDK client does not count as+// transient, so it fails the connection: the caller loses the session, not just+// the oversized call. v1.6.1 capped nothing, so this is new with the bump. If a+// later SDK makes 413 recoverable, this test is what notices.+func TestRequestBodyCapEndsTheSession(t *testing.T) {+ endpoint, _, _ := newProbeServer(t)+ token := mintMCPToken(t, "[email protected]", "client-A", "ws-test", "mcp:read-only", time.Hour)+ session := connectLegacy(t, endpoint, token, nil)++ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)+ defer cancel()+ call := func(size int) error {+ _, err := session.CallTool(ctx, &mcp.CallToolParams{+ Name: "propose_database_change",+ Arguments: map[string]any{"database": "db", "title": "t", "sql": strings.Repeat("x", size)},+ })+ return err+ }+ require.NoError(t, call(1024), "a small call works before the oversized one")+ require.Error(t, call(maxMCPRequestBodyBytes+(1<<16)))+ require.Error(t, call(1024), "the session does not survive an over-limit body")+}++// TestCorrelationIDIsSessionScoped is the regression pin behind the+// mcp_correlation_id filter and the MCPDelegation.correlation_id comment: every+// tool call on one session must write one correlation ID, so an operator can+// pull an MCP session's audit rows with a single filter value.+//+// The ID is minted per HTTP request in authMiddleware, and stays session-scoped+// only because the SDK runs tool handlers on the context of the request that+// opened the session. Any SDK change to that plumbing would silently scatter a+// session's rows across as many IDs as it made calls, and this is what would+// catch it.+func TestCorrelationIDIsSessionScoped(t *testing.T) {+ endpoint, credentials, mu := newProbeServer(t)+ token := mintMCPToken(t, "[email protected]", "client-A", "ws-test", "mcp:read-only", time.Hour)++ session := connectLegacy(t, endpoint, token, nil)+ callAPITool(t, session)+ callAPITool(t, session)++ mu.Lock()+ seen := append([]string(nil), *credentials...)+ mu.Unlock()++ require.Len(t, seen, 2)+ first, second := claim(t, seen[0], "correlation_id"), claim(t, seen[1], "correlation_id")+ require.NotEmpty(t, first)+ require.Equal(t, first, second, "two tool calls on one session must share one correlation ID")+}++// TestSeparateSessionsGetSeparateCorrelationIDs is the other half: the ID+// identifies a session, so a second session must not reuse the first one's.+func TestSeparateSessionsGetSeparateCorrelationIDs(t *testing.T) {+ endpoint, credentials, mu := newProbeServer(t)+ token := mintMCPToken(t, "[email protected]", "client-A", "ws-test", "mcp:read-only", time.Hour)++ callAPITool(t, connectLegacy(t, endpoint, token, nil))+ callAPITool(t, connectLegacy(t, endpoint, token, nil))++ mu.Lock()+ seen := append([]string(nil), *credentials...)+ mu.Unlock()++ require.Len(t, seen, 2)+ require.NotEqual(t, claim(t, seen[0], "correlation_id"), claim(t, seen[1], "correlation_id"))+}++// TestInterleavedSessionsExecuteAsTheirOwnPrincipal pins that identity is+// per request, not per process: two sessions held open by different bearers,+// used in turn, each execute as their own principal. Nothing that a session+// carries may leak into a request that belongs to the other.+func TestInterleavedSessionsExecuteAsTheirOwnPrincipal(t *testing.T) {+ endpoint, credentials, mu := newProbeServer(t)++ alice := connectLegacy(t, endpoint,+ mintMCPToken(t, "[email protected]", "client-A", "ws-test", "mcp:read-only", time.Hour), nil)+ bob := connectLegacy(t, endpoint,+ mintMCPToken(t, "[email protected]", "client-B", "ws-test", "mcp:read-only", time.Hour), nil)++ for _, session := range []*mcp.ClientSession{alice, bob, alice, bob} {+ callAPITool(t, session)+ }++ mu.Lock()+ seen := append([]string(nil), *credentials...)+ mu.Unlock()++ require.Len(t, seen, 4)+ want := []string{"[email protected]", "[email protected]", "[email protected]", "[email protected]"}+ for i, principal := range want {+ require.Equal(t, principal, claim(t, seen[i], "sub"),+ "call %d must execute as its own bearer's principal", i)+ }+}diff --git a/backend/api/mcp/server.go b/backend/api/mcp/server.goindex e240157b09..cf46f25284 100644--- a/backend/api/mcp/server.go+++ b/backend/api/mcp/server.go@@ -110,9 +110,27 @@ func newServerWithStore(stores serverStore, profile *config.Profile, secret stri// the token — not network position — is the security boundary, and the// rebinding threat targets unauthenticated, browser-reached localhost// servers, which Bytebase is not.+ //+ // maxMCPRequestBodyBytes bounds the JSON-RPC envelope, which makes it the+ // ceiling on a migration statement. It is written out rather than aliased to+ // the SDK's default so it survives a change to that default: past+ // common.MaxSheetCheckSize (2 MiB) SQL review and plan checks skip and prior+ // backup refuses, and base64 inflates that by 4/3, so 4 MiB clears the+ // largest statement worth admitting.+ //+ // Tripping it costs the session, not just the call: the transport answers a+ // bare 413, which the SDK client does not count as transient, so it fails the+ // connection and every later call on it.+ //+ // DEFER: no tool-level statement cap, so an oversized body is refused by the+ // transport with no code, size or remedy; upgrade when a caller reports it,+ // or when a multi-file CreateRelease needs more than the cap.streamable := mcp.NewStreamableHTTPHandler(func(_ *http.Request) *mcp.Server {return s.mcpServer- }, &mcp.StreamableHTTPOptions{DisableLocalhostProtection: true})+ }, &mcp.StreamableHTTPOptions{+ DisableLocalhostProtection: true,+ MaxRequestBodyBytes: maxMCPRequestBodyBytes,+ })// Refresh per-request metadata that would otherwise be frozen at session// start. The SDK runs tool handlers on the initialize request's context, but@@ -121,6 +139,7 @@ func newServerWithStore(stores serverStore, profile *config.Profile, secret stri// from. Identity stays pinned to the session (see below), which is what// makes trusting the live address safe: it cannot belong to another// principal.+ mcpServer.AddReceivingMiddleware(negotiateLegacyProtocol)mcpServer.AddReceivingMiddleware(liveRequestMetadata)// Pin each session to the identity it was opened with. The SDK captures@@ -130,18 +149,85 @@ func newServerWithStore(stores serverStore, profile *config.Profile, secret stri// check is inert, and since tool handlers run on the initialize request's// context, a substituted-but-valid bearer would be admitted while the tool// executed under the session's original identity.- s.httpHandler = mcpauth.RequireBearerToken(s.verifySessionBinding, nil)(streamable)+ s.httpHandler = mcpauth.RequireBearerToken(s.verifySessionBinding, nil)(refuseSessionlessProtocol(streamable))return s, nil}+// sessionlessProtocolVersion is the first MCP revision the SDK serves only on a+// stateless transport. This one is stateful and cannot become stateless: a+// stateless transport gives every request its own session carrying no client+// capabilities, which breaks elicitation for every older client.+const (+ sessionlessProtocolVersion = "2026-07-28"++ // legacyProtocolCeiling is what the SDK answers an initialize handshake+ // with, whatever the client asks for: negotiatedVersion caps there because+ // the newer revision is negotiated through server/discover instead.+ legacyProtocolCeiling = "2025-11-25"++ // maxMCPRequestBodyBytes is documented at the handler that applies it.+ maxMCPRequestBodyBytes = 4 << 20+)++// negotiateLegacyProtocol keeps a session's recorded revision equal to the one+// its handshake answered.+//+// The SDK records the revision the client ASKED for and answers with the one it+// negotiated, and for a client asking beyond legacyProtocolCeiling those differ.+// Everything downstream reads the record, so the SDK would treat such a client+// as multi round-trip capable and hand it an input-required result in place of+// the elicitation it agreed to, which it has no obligation to know how to+// retry. Rewriting the request to what was negotiated makes the two agree. The+// client sees the same initialize response either way.+//+// With refuseSessionlessProtocol covering the header, no session on this route+// records a revision this transport cannot serve.+func negotiateLegacyProtocol(next mcp.MethodHandler) mcp.MethodHandler {+ return func(ctx context.Context, method string, req mcp.Request) (mcp.Result, error) {+ if params, ok := req.GetParams().(*mcp.InitializeParams); ok &&+ params.ProtocolVersion >= sessionlessProtocolVersion {+ params.ProtocolVersion = legacyProtocolCeiling+ }+ return next(ctx, method, req)+ }+}++// refuseSessionlessProtocol rejects requests announcing that revision or newer.+//+// The SDK refuses it for every method but server/discover, and answers discover+// by opening a session: discover fills in InitializeParams, the field the+// cleanup checks before closing a session nobody adopted, while a session ID is+// returned only on an initialize response. The client never learns that ID and+// never deletes it, and no SessionTimeout is set, so each connect would strand+// one session for the process's life. Clients fall back to the initialize+// handshake on any discover error, which is the path they take here anyway.+//+// DEFER: refuses the revision whole; upgrade when the transport can serve it.+func refuseSessionlessProtocol(next http.Handler) http.Handler {+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if version := r.Header.Get("MCP-Protocol-Version"); version >= sessionlessProtocolVersion {+ // Debug, not info: every go-sdk v1.7.0 client takes this branch once+ // per connect.+ slog.Debug("refused an MCP protocol revision this transport cannot serve",+ slog.String("version", version))+ http.Error(w, "Bad Request: unsupported protocol version", http.StatusBadRequest)+ return+ }+ next.ServeHTTP(w, r)+ })+}+// registerTools registers all MCP tools.//-// The list is not filtered by the workspace's ceiling (BOT-89), and cannot be:-// the SDK builds it once at session start while the ceiling is read per-// request, so a filtered list would be a promise made under whatever the-// ceiling was at connect time and would go stale the moment an admin changed-// it. Revisit only if the SDK grows a way to revise a live session's tool list.+// The list is not filtered by the workspace's ceiling (BOT-89). It could be:+// the SDK re-reads its server-global tool registry on every tools/list, and+// receiving middleware can trim that result using the live request's headers,+// the way liveRequestMetadata already reads them. It is not, because a trimmed+// list enforces nothing the per-request ceiling check does not already enforce,+// and it would go stale in the client's hands the moment an admin changed the+// ceiling: the SDK can invalidate a tool list only server-wide, never for one+// session. Revisit if it grows per-session invalidation.func (s *Server) registerTools() {s.registerSearchTool()s.registerCallTool()diff --git a/backend/api/mcp/tool_change.go b/backend/api/mcp/tool_change.goindex 15864e9079..b345a15cbf 100644--- a/backend/api/mcp/tool_change.go+++ b/backend/api/mcp/tool_change.go@@ -194,7 +194,7 @@ func (s *Server) handleChange(ctx context.Context, req *mcp.CallToolRequest, inp}// Step 2: Resolve database.- resolved, resolveResult := s.resolveChangeTarget(ctx, req, input)+ resolved, resolveResult := s.resolveTarget(ctx, req, input.Database, input.Instance, input.Project)if resolveResult != nil {return resolveResult, nil, nil}@@ -295,27 +295,6 @@ func (s *Server) handleChange(ctx context.Context, req *mcp.CallToolRequest, inp}, output, nil}-// resolveChangeTarget runs the shared database resolver with elicitation fallback.-// The project parameter is passed to the server-side filter so it can disambiguate-// when the same database name exists in multiple projects.-func (s *Server) resolveChangeTarget(ctx context.Context, req *mcp.CallToolRequest, input ChangeInput) (*resolvedDatabase, *mcp.CallToolResult) {- resolveCtx, resolveCancel := context.WithTimeout(ctx, resolveTimeout)- defer resolveCancel()-- resolved, err := s.resolveDatabase(resolveCtx, input.Database, input.Instance, input.Project)- if err != nil {- return nil, formatToolError(err)- }- if !resolved.ambiguous {- return resolved, nil- }- picked, elicitErr := s.elicitDatabaseChoice(ctx, req, resolved)- if elicitErr != nil {- return nil, formatAmbiguousResult(input.Database, resolved.candidates)- }- return picked, nil-}-// createSheet creates a sheet with base64-encoded SQL content.func (s *Server) createSheet(ctx context.Context, project, sql string) (string, error) {return s.callAPI(ctx, "/bytebase.v1.SheetService/CreateSheet", "create sheets", "bb.sheets.create", map[string]any{diff --git a/backend/api/mcp/tool_query.go b/backend/api/mcp/tool_query.goindex 9ea9118fff..cfb5f88c0e 100644--- a/backend/api/mcp/tool_query.go+++ b/backend/api/mcp/tool_query.go@@ -87,20 +87,9 @@ func (s *Server) handleQueryDatabase(ctx context.Context, req *mcp.CallToolReque}// Resolve database.- resolveCtx, resolveCancel := context.WithTimeout(ctx, resolveTimeout)- defer resolveCancel()-- resolved, err := s.resolveDatabase(resolveCtx, input.Database, input.Instance, input.Project)- if err != nil {- return formatToolError(err), nil, nil- }- if resolved.ambiguous {- picked, elicitErr := s.elicitDatabaseChoice(ctx, req, resolved)- if elicitErr != nil {- // Elicitation unsupported or user cancelled — fall back to AMBIGUOUS_TARGET.- return formatAmbiguousResult(input.Database, resolved.candidates), nil, nil- }- resolved = picked+ resolved, resolveResult := s.resolveTarget(ctx, req, input.Database, input.Instance, input.Project)+ if resolveResult != nil {+ return resolveResult, nil, nil}// Execute query.diff --git a/backend/api/mcp/tool_resolve.go b/backend/api/mcp/tool_resolve.goindex f5852d871d..47299dc768 100644--- a/backend/api/mcp/tool_resolve.go+++ b/backend/api/mcp/tool_resolve.go@@ -26,15 +26,17 @@ type Candidate struct {// resolvedDatabase holds the result of database resolution.type resolvedDatabase struct {- resourceName string- dataSourceID string- engine string- project string // "projects/{id}" from databaseEntry.Project- ambiguous bool- candidates []Candidate- dataSourceIDs map[string]string // resourceName -> dataSourceID (populated when ambiguous)- engines map[string]string // resourceName -> engine (populated when ambiguous)- projects map[string]string // resourceName -> project (populated when ambiguous)+ resourceName string+ dataSourceID string+ engine string+ project string // "projects/{id}" from databaseEntry.Project+ ambiguous bool+ candidates []Candidate+ // Per-candidate lookups, filled for every match count. A unique match keeps+ // them so an elicited answer can be reconciled against what matches now.+ dataSourceIDs map[string]string // resourceName -> dataSourceID+ engines map[string]string // resourceName -> engine+ projects map[string]string // resourceName -> project}// listDatabasesResponse is the typed response from ListDatabases API.@@ -171,21 +173,25 @@ func matchDatabases(databases []databaseEntry, database, instance, project strin}}+ resolved := candidateView(matches)if len(matches) > 1 {- return buildAmbiguousResult(matches), nil+ resolved.ambiguous = true+ return resolved, nil}db := matches[0]- return &resolvedDatabase{- resourceName: db.Name,- dataSourceID: selectDataSource(db.InstanceResource.DataSources),- engine: db.InstanceResource.Engine,- project: db.Project,- }, nil+ resolved.resourceName = db.Name+ resolved.dataSourceID = selectDataSource(db.InstanceResource.DataSources)+ resolved.engine = db.InstanceResource.Engine+ resolved.project = db.Project+ return resolved, nil}-// buildAmbiguousResult constructs a resolvedDatabase with multiple candidates.-func buildAmbiguousResult(matches []databaseEntry) *resolvedDatabase {+// candidateView fills the candidate list and the per-candidate lookups for a+// match set. It is built for a unique match too: an answered elicitation is+// reconciled against it, and a stale answer has to be recognized as naming+// something else rather than silently replaced by what this resolve found.+func candidateView(matches []databaseEntry) *resolvedDatabase {candidates := make([]Candidate, 0, len(matches))dsIDs := make(map[string]string, len(matches))engines := make(map[string]string, len(matches))@@ -202,7 +208,6 @@ func buildAmbiguousResult(matches []databaseEntry) *resolvedDatabase {projects[db.Name] = db.Project}return &resolvedDatabase{- ambiguous: true,candidates: candidates,dataSourceIDs: dsIDs,engines: engines,@@ -219,61 +224,173 @@ func (s *Server) resolveDatabase(ctx context.Context, database, instance, projecreturn matchDatabases(databases, database, instance, project)}-// elicitDatabaseChoice prompts the user to pick from ambiguous database matches-// using MCP elicitation. Returns an error if elicitation is unsupported, the user-// cancels/declines, or the selection is invalid.-func (*Server) elicitDatabaseChoice(ctx context.Context, req *mcp.CallToolRequest, resolved *resolvedDatabase) (*resolvedDatabase, error) {+// resolveTarget resolves the database a tool was asked for and settles any+// elicitation it needs.+//+// Every tool that names a database goes through here. The answer has to be+// consulted even when this resolve is unique, and a call site that re-derived+// that condition and got it wrong would run against a database the caller never+// chose. Returns either a resolved database or the result to return unchanged.+func (s *Server) resolveTarget(ctx context.Context, req *mcp.CallToolRequest, database, instance, project string) (*resolvedDatabase, *mcp.CallToolResult) {+ resolveCtx, resolveCancel := context.WithTimeout(ctx, resolveTimeout)+ defer resolveCancel()++ resolved, err := s.resolveDatabase(resolveCtx, database, instance, project)+ if err != nil {+ return nil, formatToolError(err)+ }+ if _, answered := elicitedDatabaseChoice(req); !resolved.ambiguous && !answered {+ return resolved, nil+ }+ return s.elicitDatabaseChoice(req, resolved, database)+}++// databaseChoiceRequestID is the ID the ambiguous-database elicitation is filed+// under, and databaseChoiceField the form field it asks for. The client echoes+// both back, so the two halves of one tool call must agree on them.+const (+ databaseChoiceRequestID = "database"+ databaseChoiceField = "database"+)++// elicitDatabaseChoice picks one database out of an ambiguous match.+//+// It returns either a resolved database or a result the caller must return+// unchanged, never both: an input request, or the AMBIGUOUS_TARGET listing when+// no one can be asked or the answer is unusable.+//+// One shape serves both client generations (SEP-2322). A client on the+// 2026-07-28 protocol answers the input request itself; for an older one the+// SDK's middleware answers it by eliciting and re-invoking this handler.+func (*Server) elicitDatabaseChoice(req *mcp.CallToolRequest, resolved *resolvedDatabase, database string) (*resolvedDatabase, *mcp.CallToolResult) {+ fallback := formatAmbiguousResult(database, resolved.candidates)if req == nil || req.Session == nil {- return nil, errors.New("elicitation unsupported: no session")+ return nil, fallback+ }+ enumValues, resourceByLabel := candidateLabels(resolved.candidates)++ // Read the answer before asking again: on the retry the SDK re-invokes this+ // handler, which resolves a second time, so resourceByLabel holds whatever+ // matches now. An answer naming something else finds no entry and falls back.+ // It is read even when this resolve is no longer ambiguous, because dropping+ // it there would run the statement against a database nobody chose.+ if response, answered := elicitedDatabaseChoice(req); answered {+ selected, accepted := acceptedDatabaseLabel(response)+ if !accepted {+ return nil, fallback+ }+ resourceName, current := resourceByLabel[selected]+ if !current {+ return nil, formatStaleChoiceResult(database, selected, resolved.candidates)+ }+ return &resolvedDatabase{+ resourceName: resourceName,+ dataSourceID: resolved.dataSourceIDs[resourceName],+ engine: resolved.engines[resourceName],+ project: resolved.projects[resourceName],+ }, nil}- // Build enum values and a lookup map from display label to resource name.- enumValues := make([]any, 0, len(resolved.candidates))- resourceByLabel := make(map[string]string, len(resolved.candidates))- for _, c := range resolved.candidates {- label := fmt.Sprintf("%s (%s, %s)", c.Database, c.Instance, c.Engine)- enumValues = append(enumValues, label)- resourceByLabel[label] = c.Database+ // For an older client the SDK answers the input request itself, and an error+ // there fails the whole tool call instead of returning something the model+ // can act on. So a client that cannot answer a form gets the listing.+ //+ // DEFER: only what the client declared up front is caught; an elicitation+ // that fails once under way still fails the call. Upgrade when the SDK lets+ // a handler see that error.+ if !clientSupportsElicitation(req.Session) {+ return nil, fallback}- result, err := req.Session.Elicit(ctx, &mcp.ElicitParams{- Mode: "form",- Message: "Multiple databases match. Which one do you want to query?",- RequestedSchema: map[string]any{- "type": "object",- "properties": map[string]any{- "database": map[string]any{- "type": "string",- "enum": enumValues,- "description": "Select the target database",+ return nil, &mcp.CallToolResult{+ InputRequests: mcp.InputRequestMap{+ databaseChoiceRequestID: &mcp.ElicitParams{+ Mode: "form",+ Message: "Multiple databases match. Which one do you want to query?",+ RequestedSchema: map[string]any{+ "type": "object",+ "properties": map[string]any{+ databaseChoiceField: map[string]any{+ "type": "string",+ "enum": enumValues,+ "description": "Select the target database",+ },+ },+ "required": []string{databaseChoiceField},},},- "required": []string{"database"},},- })- if err != nil {- return nil, err}- if result.Action != "accept" {- return nil, errors.Errorf("user %sd database selection", result.Action)+}++// elicitedDatabaseChoice returns the answer the client sent for the+// ambiguous-database elicitation, if this call carries one.+func elicitedDatabaseChoice(req *mcp.CallToolRequest) (mcp.InputResponse, bool) {+ if req == nil || req.Params == nil {+ return nil, false}+ response, answered := req.Params.InputResponses[databaseChoiceRequestID]+ return response, answered+}- selected, ok := result.Content["database"].(string)- if !ok {- return nil, errors.New("invalid database selection")+// candidateLabels returns the enum values in candidate order and a lookup from+// label back to resource name.+func candidateLabels(candidates []Candidate) ([]any, map[string]string) {+ enumValues := make([]any, 0, len(candidates))+ resourceByLabel := make(map[string]string, len(candidates))+ for _, c := range candidates {+ label := fmt.Sprintf("%s (%s, %s)", c.Database, c.Instance, c.Engine)+ enumValues = append(enumValues, label)+ resourceByLabel[label] = c.Database}+ return enumValues, resourceByLabel+}- resourceName, ok := resourceByLabel[selected]- if !ok {- return nil, errors.Errorf("unknown database selection: %s", selected)+// acceptedDatabaseLabel returns the label the client picked. It reports false+// when the answer carries no pick: declined, cancelled, or malformed.+func acceptedDatabaseLabel(response mcp.InputResponse) (string, bool) {+ elicited, ok := response.(*mcp.ElicitResult)+ if !ok || elicited.Action != "accept" {+ return "", false}+ selected, ok := elicited.Content[databaseChoiceField].(string)+ return selected, ok+}- return &resolvedDatabase{- resourceName: resourceName,- dataSourceID: resolved.dataSourceIDs[resourceName],- engine: resolved.engines[resourceName],- project: resolved.projects[resourceName],- }, nil+func clientSupportsElicitation(session *mcp.ServerSession) bool {+ params := session.InitializeParams()+ if params == nil || params.Capabilities == nil || params.Capabilities.Elicitation == nil {+ return false+ }+ // The input request asks for a form, and the SDK refuses form mode to a+ // client that advertised URL elicitation without it. A client advertising+ // neither is assumed to support form, for clients older than the split.+ elicitation := params.Capabilities.Elicitation+ return elicitation.Form != nil || elicitation.URL == nil+}++// formatStaleChoiceResult answers a pick that no longer matches.+//+// It cannot reuse formatAmbiguousResult: that one says to narrow by instance,+// and one candidate is often all that is left, so following it would re-issue+// the call against the database the caller did not pick.+func formatStaleChoiceResult(database, selected string, candidates []Candidate) *mcp.CallToolResult {+ result := struct {+ Code string `json:"code"`+ Message string `json:"message"`+ Candidates []Candidate `json:"candidates"`+ }{+ Code: "STALE_TARGET",+ Message: fmt.Sprintf("The database chosen for %q (%s) no longer matches. "++ "Choose again from the candidates below, or name one explicitly.", database, selected),+ Candidates: candidates,+ }++ jsonBytes, _ := json.MarshalIndent(result, "", " ")+ return &mcp.CallToolResult{+ Content: []mcp.Content{&mcp.TextContent{Text: string(jsonBytes)}},+ IsError: true,+ }}// matchExact returns databases whose short name exactly matches the input.diff --git a/backend/api/mcp/tool_resolve_mrtr_test.go b/backend/api/mcp/tool_resolve_mrtr_test.gonew file mode 100644index 0000000000..56b25be44f--- /dev/null+++ b/backend/api/mcp/tool_resolve_mrtr_test.go@@ -0,0 +1,469 @@+package mcp++import (+ "bufio"+ "context"+ "encoding/json"+ "io"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync/atomic"+ "testing"+ "time"++ "github.com/labstack/echo/v5"+ mcpauth "github.com/modelcontextprotocol/go-sdk/auth"+ "github.com/modelcontextprotocol/go-sdk/mcp"+ "github.com/stretchr/testify/require"++ "github.com/bytebase/bytebase/backend/common"+ "github.com/bytebase/bytebase/backend/component/config"+)++// The ambiguous-database flow is a multi round-trip request (SEP-2322): the+// tool returns an input request instead of an answer, and the client calls+// again carrying the response. These tests drive it end to end over HTTP,+// because the picking code reads the live session's advertised capabilities and+// a *mcp.ServerSession cannot be constructed outside the SDK.+//+// Two client generations reach the same handler:+//+// - Clients on protocol <= 2025-11-25 never see the input request. The SDK's+// own server middleware fulfills it by eliciting and re-invoking the+// handler with the answer. This is every client Bytebase serves today: the+// production handler is stateful, and the SDK caps the initialize handshake+// at 2025-11-25 (mcp/shared.go negotiatedVersion), so 2026-07-28 is not+// reachable there — see mrtrHandler.+// - Clients on 2026-07-28 receive the input request themselves and retry.++const ambiguousShortName = "employee_db"++// ambiguousDatabases are two databases that share a short name on different+// instances, so resolving by short name alone is ambiguous.+func ambiguousDatabases() []map[string]any {+ return []map[string]any{+ makeDatabase("instances/prod-pg/databases/employee_db", "instances/prod-pg", "projects/hr", "POSTGRES", "ds-1"),+ makeDatabase("instances/staging-pg/databases/employee_db", "instances/staging-pg", "projects/hr", "POSTGRES", "ds-2"),+ }+}++// prodLabel is the elicitation label for the prod-pg candidate, built the same+// way candidateLabels builds it.+const prodLabel = "instances/prod-pg/databases/employee_db (prod-pg, POSTGRES)"++// newAmbiguousServer stands up the real /mcp route over an internal API that+// resolves ambiguously and answers any query. It returns the server plus the+// endpoint and a bearer for it.+func newAmbiguousServer(t *testing.T, databases []map[string]any) (*Server, string, string) {+ t.Helper()+ profile := &config.Profile{Mode: common.ReleaseModeDev, ExternalURL: "https://bb.example.com"}+ queryResp := makeQueryResponse([]string{"id"}, []string{"int4"}, [][]any{{"1"}}, "0.001s")++ s, err := newServerWithStore(newTestServerStore(), profile, revalidationSecret,+ mockQueryServer(databases, queryResp))+ require.NoError(t, err)++ e := echo.New()+ s.RegisterRoutes(e)+ ts := httptest.NewServer(e)+ t.Cleanup(ts.Close)++ return s, ts.URL + "/mcp", mintMCPToken(t, "[email protected]", "client-A", "ws-test", "mcp:read-only", time.Hour)+}++// bearerTransport presents a fixed bearer on every request.+type bearerTransport struct{ token string }++func (t *bearerTransport) RoundTrip(req *http.Request) (*http.Response, error) {+ req = req.Clone(req.Context())+ req.Header.Set("Authorization", "Bearer "+t.token)+ return http.DefaultTransport.RoundTrip(req)+}++// connectLegacy opens a session against the production /mcp route.+func connectLegacy(t *testing.T, endpoint, token string, opts *mcp.ClientOptions) *mcp.ClientSession {+ t.Helper()+ client := mcp.NewClient(&mcp.Implementation{Name: "probe", Version: "0"}, opts)+ session, err := client.Connect(context.Background(), &mcp.StreamableClientTransport{+ Endpoint: endpoint,+ HTTPClient: &http.Client{Transport: &bearerTransport{token: token}},+ MaxRetries: -1,+ }, nil)+ require.NoError(t, err)+ t.Cleanup(func() { _ = session.Close() })+ return session+}++func queryAmbiguous(t *testing.T, session *mcp.ClientSession) (*mcp.CallToolResult, error) {+ t.Helper()+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)+ defer cancel()+ return session.CallTool(ctx, &mcp.CallToolParams{+ Name: "query_database",+ Arguments: map[string]any{"database": ambiguousShortName, "statement": "SELECT 1"},+ })+}++func resultText(t *testing.T, res *mcp.CallToolResult) string {+ t.Helper()+ require.NotEmpty(t, res.Content, "a completed call must carry content")+ text, ok := res.Content[0].(*mcp.TextContent)+ require.True(t, ok)+ return text.Text+}++// TestAmbiguousDatabaseElicitsUnderLegacyClient is the pin that the migrated+// handler needs no protocol branch. A client that predates multi round-trip+// still gets a real elicitation, because the SDK's server middleware answers+// the input request on its behalf and re-invokes the handler; the call then+// completes against the database the user picked.+func TestAmbiguousDatabaseElicitsUnderLegacyClient(t *testing.T) {+ _, endpoint, token := newAmbiguousServer(t, ambiguousDatabases())++ var elicited atomic.Int32+ session := connectLegacy(t, endpoint, token, &mcp.ClientOptions{+ ElicitationHandler: func(_ context.Context, req *mcp.ElicitRequest) (*mcp.ElicitResult, error) {+ elicited.Add(1)+ require.Contains(t, req.Params.Message, "Multiple databases match")+ return &mcp.ElicitResult{Action: "accept", Content: map[string]any{"database": prodLabel}}, nil+ },+ })+ require.Less(t, session.InitializeResult().ProtocolVersion, "2026-07-28",+ "the production handler is stateful, so the handshake stays below the multi round-trip revision")++ res, err := queryAmbiguous(t, session)+ require.NoError(t, err)+ require.False(t, res.IsError, resultText(t, res))+ require.Equal(t, int32(1), elicited.Load(), "the legacy client must still be asked")+ require.Contains(t, resultText(t, res), "instances/prod-pg/databases/employee_db")+}++// TestAmbiguousDatabaseFallsBackWithoutElicitationCapability pins the guard on+// the client's advertised capability. Most MCP clients advertise no+// elicitation, and returning an input request to one fails the whole tool call+// with a JSON-RPC error the model cannot act on+// (mcp/mrtr.go fulfillServerInputRequests). Such a client must keep getting the+// candidate listing it got before multi round-trip.+func TestAmbiguousDatabaseFallsBackWithoutElicitationCapability(t *testing.T) {+ _, endpoint, token := newAmbiguousServer(t, ambiguousDatabases())+ session := connectLegacy(t, endpoint, token, nil)++ res, err := queryAmbiguous(t, session)+ require.NoError(t, err, "a client that cannot be asked must still get a result, not a protocol error")+ require.True(t, res.IsError)+ text := resultText(t, res)+ require.Contains(t, text, "AMBIGUOUS_TARGET")+ require.Contains(t, text, "prod-pg")+ require.Contains(t, text, "staging-pg")+}++// TestAmbiguousDatabaseFallsBackForURLOnlyElicitation pins the other half of the+// capability guard. The input request asks for a form, and the SDK refuses form+// mode to a client that advertised URL elicitation without it, failing the whole+// tool call. Advertising some elicitation is therefore not enough to be asked.+func TestAmbiguousDatabaseFallsBackForURLOnlyElicitation(t *testing.T) {+ _, endpoint, token := newAmbiguousServer(t, ambiguousDatabases())+ session := connectLegacy(t, endpoint, token, &mcp.ClientOptions{+ Capabilities: &mcp.ClientCapabilities{+ Elicitation: &mcp.ElicitationCapabilities{URL: &mcp.URLElicitationCapabilities{}},+ },+ ElicitationHandler: func(context.Context, *mcp.ElicitRequest) (*mcp.ElicitResult, error) {+ return nil, nil // never reached; a form request is refused before it+ },+ })++ res, err := queryAmbiguous(t, session)+ require.NoError(t, err, "a client that cannot answer a form must still get a result")+ require.True(t, res.IsError)+ require.Contains(t, resultText(t, res), "AMBIGUOUS_TARGET")+}++// TestAmbiguousDatabaseElicitsWhenNeitherModeAdvertised pins the backward-compat+// case: a client that advertises elicitation without naming a mode is assumed to+// support forms, so it must still be asked.+func TestAmbiguousDatabaseElicitsWhenNeitherModeAdvertised(t *testing.T) {+ _, endpoint, token := newAmbiguousServer(t, ambiguousDatabases())+ var elicited atomic.Int32+ session := connectLegacy(t, endpoint, token, &mcp.ClientOptions{+ Capabilities: &mcp.ClientCapabilities{Elicitation: &mcp.ElicitationCapabilities{}},+ ElicitationHandler: func(context.Context, *mcp.ElicitRequest) (*mcp.ElicitResult, error) {+ elicited.Add(1)+ return &mcp.ElicitResult{Action: "accept", Content: map[string]any{"database": prodLabel}}, nil+ },+ })++ res, err := queryAmbiguous(t, session)+ require.NoError(t, err)+ require.False(t, res.IsError, resultText(t, res))+ require.Equal(t, int32(1), elicited.Load())+}++// TestAmbiguousDatabaseDeclinedFallsBack pins that declining still fails the+// call the way it did before the migration: with the candidate listing, not a+// silent pick.+func TestAmbiguousDatabaseDeclinedFallsBack(t *testing.T) {+ _, endpoint, token := newAmbiguousServer(t, ambiguousDatabases())+ session := connectLegacy(t, endpoint, token, &mcp.ClientOptions{+ ElicitationHandler: func(context.Context, *mcp.ElicitRequest) (*mcp.ElicitResult, error) {+ return &mcp.ElicitResult{Action: "decline"}, nil+ },+ })++ res, err := queryAmbiguous(t, session)+ require.NoError(t, err)+ require.True(t, res.IsError)+ require.Contains(t, resultText(t, res), "AMBIGUOUS_TARGET")+}++// TestAmbiguousDatabaseCompletesForAClientAskingBeyondTheCeiling is the pin on+// what a client actually negotiated.+//+// An initialize request carries no MCP-Protocol-Version header, so+// refuseSessionlessProtocol does not see it, and a client asking for the+// sessionless revision is admitted and answered 2025-11-25. Its session must+// record what it was answered: served the newer revision's input-required+// result instead, a client that honoured the downgrade would be handed a shape+// it never agreed to and had no obligation to retry, and the call could never+// finish. It gets a plain elicitation and the query runs.+func TestAmbiguousDatabaseCompletesForAClientAskingBeyondTheCeiling(t *testing.T) {+ _, endpoint, token := newAmbiguousServer(t, ambiguousDatabases())++ post := func(sessionID, body string) (*http.Response, error) {+ req, err := http.NewRequest(http.MethodPost, endpoint, strings.NewReader(body))+ require.NoError(t, err)+ req.Header.Set("Content-Type", "application/json")+ req.Header.Set("Accept", "application/json, text/event-stream")+ req.Header.Set("Authorization", "Bearer "+token)+ if sessionID != "" {+ req.Header.Set("Mcp-Session-Id", sessionID)+ }+ return (&http.Client{Timeout: 30 * time.Second}).Do(req)+ }++ resp, err := post("", `{"jsonrpc":"2.0","id":1,"method":"initialize","params":`++ `{"protocolVersion":"`+sessionlessProtocolVersion+`","capabilities":{"elicitation":{}},`++ `"clientInfo":{"name":"probe","version":"0"}}}`)+ require.NoError(t, err)+ sessionID := resp.Header.Get("Mcp-Session-Id")+ handshake, err := io.ReadAll(resp.Body)+ require.NoError(t, resp.Body.Close())+ require.NoError(t, err)+ require.NotEmpty(t, sessionID)+ require.Contains(t, string(handshake), `"protocolVersion":"`+legacyProtocolCeiling+`"`,+ "the handshake answers the ceiling this transport can serve")++ resp, err = post(sessionID, `{"jsonrpc":"2.0","method":"notifications/initialized"}`)+ require.NoError(t, err)+ require.NoError(t, resp.Body.Close())++ // The tool call's own stream carries the server's elicitation and, once it is+ // answered on a second POST, the result.+ call, err := post(sessionID, `{"jsonrpc":"2.0","id":2,"method":"tools/call","params":`++ `{"name":"query_database","arguments":{"database":"`+ambiguousShortName+`","statement":"SELECT 1"}}}`)+ require.NoError(t, err)+ defer call.Body.Close()++ var answered bool+ var final string+ scanner := bufio.NewScanner(call.Body)+ scanner.Buffer(make([]byte, 0, 64*1024), 1<<20)+ for scanner.Scan() {+ payload, found := strings.CutPrefix(scanner.Text(), "data: ")+ if !found {+ continue+ }+ var message struct {+ ID json.RawMessage `json:"id"`+ Method string `json:"method"`+ }+ require.NoError(t, json.Unmarshal([]byte(payload), &message))+ if message.Method == "elicitation/create" {+ require.Contains(t, payload, "Multiple databases match")+ answer, err := post(sessionID, `{"jsonrpc":"2.0","id":`+string(message.ID)++ `,"result":{"action":"accept","content":{"database":"`+prodLabel+`"}}}`)+ require.NoError(t, err)+ require.NoError(t, answer.Body.Close())+ answered = true+ continue+ }+ final = payload+ break+ }+ require.True(t, answered, "the client must be asked, not handed an input-required result")+ require.NotContains(t, final, "input_required")+ require.NotContains(t, final, "AMBIGUOUS_TARGET")+ require.Contains(t, final, "instances/prod-pg/databases/employee_db",+ "the call must complete against the database the client picked")+}++// shrinkingDatabases serves the full set on the first ListDatabases call and the+// reduced one after, so a tool call's two resolves disagree.+func shrinkingDatabases(t *testing.T, first, rest []map[string]any) (http.Handler, *atomic.Int32) {+ t.Helper()+ var calls atomic.Int32+ queryResp := makeQueryResponse([]string{"id"}, []string{"int4"}, [][]any{{"1"}}, "0.001s")+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusOK)+ if !strings.Contains(r.URL.Path, "ListDatabases") {+ _ = json.NewEncoder(w).Encode(queryResp)+ return+ }+ set := first+ if calls.Add(1) > 1 {+ set = rest+ }+ _ = json.NewEncoder(w).Encode(map[string]any{"databases": set})+ }), &calls+}++// TestAmbiguousDatabaseNeverRunsAnUnchosenDatabase is the correctness pin behind+// the whole round trip. The handler resolves once to ask and once to act, so the+// two resolves can disagree: here the database the user picked stops matching+// between them, leaving exactly one other match. The answer still decides, so+// the call must refuse rather than run the statement against the database that+// happens to be left.+func TestAmbiguousDatabaseNeverRunsAnUnchosenDatabase(t *testing.T) {+ both := ambiguousDatabases()+ handler, listCalls := shrinkingDatabases(t, both, both[1:]) // staging survives, prod does not++ profile := &config.Profile{Mode: common.ReleaseModeDev, ExternalURL: "https://bb.example.com"}+ s, err := newServerWithStore(newTestServerStore(), profile, revalidationSecret, handler)+ require.NoError(t, err)+ e := echo.New()+ s.RegisterRoutes(e)+ ts := httptest.NewServer(e)+ t.Cleanup(ts.Close)++ token := mintMCPToken(t, "[email protected]", "client-A", "ws-test", "mcp:read-only", time.Hour)+ session := connectLegacy(t, ts.URL+mcpResourcePath, token, &mcp.ClientOptions{+ ElicitationHandler: func(context.Context, *mcp.ElicitRequest) (*mcp.ElicitResult, error) {+ return &mcp.ElicitResult{Action: "accept", Content: map[string]any{"database": prodLabel}}, nil+ },+ })++ res, err := queryAmbiguous(t, session)+ require.NoError(t, err)+ require.Equal(t, int32(2), listCalls.Load(), "the retry must resolve again")+ require.True(t, res.IsError, "picking a database that no longer matches must not run somewhere else")+ text := resultText(t, res)+ require.Contains(t, text, "STALE_TARGET")+ require.NotContains(t, text, "Query:", "no statement may run")+ require.NotContains(t, text, "Specify instance or project to narrow",+ "the ambiguous remedy would send the caller straight back to the database it did not pick")+}++// mrtrEndpoint serves the same tools behind the same auth chain, over a+// STATELESS transport. That is the only way to reach a 2026-07-28 client: the+// SDK refuses the revision on a stateful transport+// (mcp/streamable.go SupportsProtocolVersion) and caps the initialize handshake+// at 2025-11-25 regardless (mcp/shared.go negotiatedVersion). Production stays+// stateful, so these tests pin the tool handler under the newer protocol, not+// the /mcp wiring: refuseSessionlessProtocol is deliberately left off here,+// since on the real route it refuses exactly what these tests need to send.+func mrtrEndpoint(t *testing.T, s *Server) string {+ t.Helper()+ streamable := mcp.NewStreamableHTTPHandler(+ func(*http.Request) *mcp.Server { return s.mcpServer },+ &mcp.StreamableHTTPOptions{+ DisableLocalhostProtection: true,+ MaxRequestBodyBytes: maxMCPRequestBodyBytes,+ Stateless: true,+ })+ e := echo.New()+ e.Any(mcpResourcePath,+ echo.WrapHandler(mcpauth.RequireBearerToken(s.verifySessionBinding, nil)(streamable)),+ s.authMiddleware)+ ts := httptest.NewServer(e)+ t.Cleanup(ts.Close)+ return ts.URL + mcpResourcePath+}++// connectMRTR opens a session that speaks the 2026-07-28 protocol and does not+// auto-answer input requests, so the test sees both round trips.+func connectMRTR(t *testing.T, endpoint, token string) *mcp.ClientSession {+ t.Helper()+ client := mcp.NewClient(&mcp.Implementation{Name: "probe", Version: "0"}, &mcp.ClientOptions{+ MultiRoundTrip: &mcp.MultiRoundTripOptions{Disabled: true},+ ElicitationHandler: func(context.Context, *mcp.ElicitRequest) (*mcp.ElicitResult, error) {+ return nil, nil // never called; declared so the capability is advertised+ },+ })+ session, err := client.Connect(context.Background(), &mcp.StreamableClientTransport{+ Endpoint: endpoint,+ HTTPClient: &http.Client{Transport: &bearerTransport{token: token}},+ MaxRetries: -1,+ }, nil)+ require.NoError(t, err)+ t.Cleanup(func() { _ = session.Close() })+ require.Equal(t, "2026-07-28", session.InitializeResult().ProtocolVersion)+ return session+}++func callMRTR(t *testing.T, session *mcp.ClientSession, responses mcp.InputResponseMap, state string) *mcp.CallToolResult {+ t.Helper()+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)+ defer cancel()+ res, err := session.CallTool(ctx, &mcp.CallToolParams{+ Name: "query_database",+ Arguments: map[string]any{"database": ambiguousShortName, "statement": "SELECT 1"},+ InputResponses: responses,+ RequestState: state,+ })+ require.NoError(t, err)+ return res+}++// TestAmbiguousDatabaseReturnsInputRequestUnderMRTRClient pins the shape a+// 2026-07-28 client sees: the first call answers with an input request instead+// of content, and the retry carrying the response completes the query.+func TestAmbiguousDatabaseReturnsInputRequestUnderMRTRClient(t *testing.T) {+ s, _, token := newAmbiguousServer(t, ambiguousDatabases())+ session := connectMRTR(t, mrtrEndpoint(t, s), token)++ first := callMRTR(t, session, nil, "")+ require.True(t, first.NeedsInput(), "an ambiguous match must ask, not guess")+ require.Empty(t, first.Content, "content and input requests are mutually exclusive")+ elicit, ok := first.InputRequests[databaseChoiceRequestID].(*mcp.ElicitParams)+ require.True(t, ok, "the input request must be an elicitation")+ require.Contains(t, elicit.Message, "Multiple databases match")++ second := callMRTR(t, session, mcp.InputResponseMap{+ databaseChoiceRequestID: &mcp.ElicitResult{+ Action: "accept",+ Content: map[string]any{"database": prodLabel},+ },+ }, first.RequestState)+ require.False(t, second.NeedsInput())+ require.False(t, second.IsError, resultText(t, second))+ require.Contains(t, resultText(t, second), "instances/prod-pg/databases/employee_db")+}++// TestAmbiguousDatabaseStaleSelectionFallsBack pins what happens when the+// candidate set changes between the two halves of a call. The selection is+// matched against the candidates resolved on the retry, so a label that no+// longer names a candidate resolves to nothing.+//+// It answers STALE_TARGET rather than asking again: a handler that returns a+// second input request is retried until the SDK gives up ("multi-round-trip:+// exceeded maximum retries"), which fails the call with a protocol error+// instead of telling the model what it can pick from.+func TestAmbiguousDatabaseStaleSelectionFallsBack(t *testing.T) {+ s, _, token := newAmbiguousServer(t, ambiguousDatabases())+ session := connectMRTR(t, mrtrEndpoint(t, s), token)++ first := callMRTR(t, session, nil, "")+ require.True(t, first.NeedsInput())++ // The retry names a database that is not among the candidates any more.+ second := callMRTR(t, session, mcp.InputResponseMap{+ databaseChoiceRequestID: &mcp.ElicitResult{+ Action: "accept",+ Content: map[string]any{"database": "instances/gone/databases/employee_db (gone, POSTGRES)"},+ },+ }, first.RequestState)+ require.False(t, second.NeedsInput(), "a stale selection must not start another round trip")+ require.True(t, second.IsError)+ require.Contains(t, resultText(t, second), "STALE_TARGET")+}diff --git a/backend/api/mcp/tool_schema.go b/backend/api/mcp/tool_schema.goindex 7c7528e189..0ce6e42b96 100644--- a/backend/api/mcp/tool_schema.go+++ b/backend/api/mcp/tool_schema.go@@ -240,7 +240,7 @@ func (s *Server) handleGetSchema(ctx context.Context, req *mcp.CallToolRequest,return nil, nil, err}- resolved, resolveResult := s.resolveSchemaTarget(ctx, req, input)+ resolved, resolveResult := s.resolveTarget(ctx, req, input.Database, input.Instance, input.Project)if resolveResult != nil {return resolveResult, nil, nil}@@ -290,27 +290,6 @@ func resolveIncludeLevel(input SchemaInput) (string, error) {return include, nil}-// resolveSchemaTarget runs the shared database resolver and handles the ambiguous-// case with elicitation fallback. Returns either a resolved database (on success)-// or a non-nil CallToolResult describing the error for the caller to return.-func (s *Server) resolveSchemaTarget(ctx context.Context, req *mcp.CallToolRequest, input SchemaInput) (*resolvedDatabase, *mcp.CallToolResult) {- resolveCtx, resolveCancel := context.WithTimeout(ctx, resolveTimeout)- defer resolveCancel()-- resolved, err := s.resolveDatabase(resolveCtx, input.Database, input.Instance, input.Project)- if err != nil {- return nil, formatToolError(err)- }- if !resolved.ambiguous {- return resolved, nil- }- picked, elicitErr := s.elicitDatabaseChoice(ctx, req, resolved)- if elicitErr != nil {- return nil, formatAmbiguousResult(input.Database, resolved.candidates)- }- return picked, nil-}-// renderTableResult dispatches the `table=` drill-down path: it picks the unique// match (or returns an appropriate error result) and renders it as TableDetail.// schemaHint is the engine-adjusted schema filter (empty when dropped fordiff --git a/go.mod b/go.modindex f4dcf75eec..946c6edd1a 100644--- a/go.mod+++ b/go.mod@@ -67,7 +67,7 @@ require (github.com/lor00x/goldap v0.0.0-20240304151906-8d785c64d1c8github.com/microsoft/go-mssqldb v1.10.0github.com/moby/moby/api v1.55.0- github.com/modelcontextprotocol/go-sdk v1.6.1+ github.com/modelcontextprotocol/go-sdk v1.7.0github.com/nyaruka/phonenumbers/v2 v2.0.5github.com/opensearch-project/opensearch-go/v4 v4.7.2github.com/paulmach/orb v0.13.0diff --git a/go.sum b/go.sumindex 27b07c2d09..3aef82ecd5 100644--- a/go.sum+++ b/go.sum@@ -743,8 +743,8 @@ github.com/moby/sys/userns v0.1.0 h1:tVLXkFOxVu9A64/yh59slHVv9ahO9UIev4JZusOLG/ggithub.com/moby/sys/userns v0.1.0/go.mod h1:IHUYgu/kao6N8YZlp9Cf444ySSvCmDlmzUcYfDHOl28=github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ=github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc=-github.com/modelcontextprotocol/go-sdk v1.6.1 h1:0zOSupjKUxPKSocPT1Wtago+mUHU2/uZ4xSOY0FGReU=-github.com/modelcontextprotocol/go-sdk v1.6.1/go.mod h1:kzm3kzFL1/+AziGOE0nUs3gvPoNxMCvkxokMkuFapXQ=+github.com/modelcontextprotocol/go-sdk v1.7.0 h1:yqjY2dsbKAC0LSuWZVBMrHgiG8ukXv6NRo0JiALay44=+github.com/modelcontextprotocol/go-sdk v1.7.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts=github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=