Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat(mcp): add query_database tool with database resolution (#19625)

Vincent Huangefd79bd89bf8
diff --git a/backend/api/mcp/server.go b/backend/api/mcp/server.go
index bb9a709c24..2ee57f8393 100644
--- a/backend/api/mcp/server.go
+++ b/backend/api/mcp/server.go
@@ -60,6 +60,7 @@ func (s *Server) registerTools() {
s.registerSearchTool()
s.registerCallTool()
s.registerSkillTool()
+ s.registerQueryTool()
}
// authMiddleware validates OAuth2 bearer tokens for MCP requests.
diff --git a/backend/api/mcp/tool_http.go b/backend/api/mcp/tool_http.go
index 657013ac45..62fe49d45b 100644
--- a/backend/api/mcp/tool_http.go
+++ b/backend/api/mcp/tool_http.go
@@ -80,6 +80,20 @@ func parseError(body json.RawMessage) string {
return ""
}
+// toolError is a structured error returned by MCP tools.
+type toolError struct {
+ Code string `json:"code"`
+ Message string `json:"message"`
+ Suggestion string `json:"suggestion,omitempty"`
+}
+
+func (e *toolError) Error() string {
+ if e.Suggestion != "" {
+ return fmt.Sprintf("%s: %s (%s)", e.Code, e.Message, e.Suggestion)
+ }
+ return fmt.Sprintf("%s: %s", e.Code, e.Message)
+}
+
// Context key for storing the access token.
type accessTokenKey struct{}
diff --git a/backend/api/mcp/tool_query.go b/backend/api/mcp/tool_query.go
new file mode 100644
index 0000000000..7e82b8eb27
--- /dev/null
+++ b/backend/api/mcp/tool_query.go
@@ -0,0 +1,421 @@
+package mcp
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/modelcontextprotocol/go-sdk/mcp"
+ "github.com/pkg/errors"
+)
+
+const (
+ defaultQueryLimit = 100
+ maxQueryLimit = 1000
+ queryTimeout = 30 * time.Second
+ resolveTimeout = 30 * time.Second
+)
+
+// QueryInput is the input for the query_database tool.
+type QueryInput struct {
+ // Database is the database name or substring to match.
+ Database string `json:"database"`
+ // Statement is the SQL query to execute.
+ Statement string `json:"statement"`
+ // Instance narrows database resolution to a specific instance.
+ Instance string `json:"instance,omitempty"`
+ // Project narrows database resolution to a specific project.
+ Project string `json:"project,omitempty"`
+ // Limit is the maximum number of rows to return (default: 100, max: 1000).
+ Limit int `json:"limit,omitempty"`
+}
+
+// QueryOutput is the output for the query_database tool.
+type QueryOutput struct {
+ Columns []string `json:"columns"`
+ ColumnTypes []string `json:"columnTypes"`
+ Rows [][]any `json:"rows"`
+ RowCount int `json:"rowCount"`
+ Truncated bool `json:"truncated"`
+ LatencyMs int64 `json:"latencyMs"`
+}
+
+// Candidate represents a database match for ambiguous resolution.
+type Candidate struct {
+ Database string `json:"database"`
+ Instance string `json:"instance"`
+ Project string `json:"project"`
+ Engine string `json:"engine"`
+}
+
+// resolvedDatabase holds the result of database resolution.
+type resolvedDatabase struct {
+ resourceName string
+ dataSourceID string
+ ambiguous bool
+ candidates []Candidate
+ dataSourceIDs map[string]string // resourceName -> dataSourceID (populated when ambiguous)
+}
+
+// queryDatabaseDescription is the description for the query_database tool.
+const queryDatabaseDescription = `Execute a SQL query against a Bytebase database. Resolves the database by name automatically.
+
+| Parameter | Required | Description |
+|-----------|----------|-------------|
+| database | Yes | Database name or substring (e.g., "employee_db" or "employee") |
+| statement | Yes | SQL query to execute |
+| instance | No | Instance name to narrow resolution |
+| project | No | Project name to narrow resolution |
+| limit | No | Max rows (default: 100, max: 1000) |
+
+**Examples:**
+query_database(database="employee_db", statement="SELECT * FROM users LIMIT 10")
+query_database(database="employee", instance="prod-pg", statement="SELECT count(*) FROM orders")`
+
+func (s *Server) registerQueryTool() {
+ mcp.AddTool(s.mcpServer, &mcp.Tool{
+ Name: "query_database",
+ Description: queryDatabaseDescription,
+ }, s.handleQueryDatabase)
+}
+
+func (s *Server) handleQueryDatabase(ctx context.Context, req *mcp.CallToolRequest, input QueryInput) (*mcp.CallToolResult, any, error) {
+ if input.Database == "" {
+ return nil, nil, errors.New("database is required")
+ }
+ if input.Statement == "" {
+ return nil, nil, errors.New("statement is required")
+ }
+
+ // Normalize limit.
+ limit := input.Limit
+ if limit <= 0 {
+ limit = defaultQueryLimit
+ }
+ if limit > maxQueryLimit {
+ limit = maxQueryLimit
+ }
+
+ // Resolve database.
+ resolveCtx, resolveCancel := context.WithTimeout(ctx, resolveTimeout)
+ defer resolveCancel()
+
+ resolved, err := s.resolveDatabase(resolveCtx, input)
+ 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
+ }
+
+ // Execute query.
+ queryCtx, queryCancel := context.WithTimeout(ctx, queryTimeout)
+ defer queryCancel()
+
+ output, err := s.executeQuery(queryCtx, resolved, input.Statement, limit)
+ if err != nil {
+ return formatToolError(err), nil, nil
+ }
+
+ text := formatQueryOutput(input.Statement, resolved.resourceName, output)
+ return &mcp.CallToolResult{
+ Content: []mcp.Content{&mcp.TextContent{Text: text}},
+ }, output, nil
+}
+
+// listDatabasesResponse is the typed response from ListDatabases API.
+type listDatabasesResponse struct {
+ Databases []databaseEntry `json:"databases"`
+}
+
+// databaseEntry represents a database in the ListDatabases response.
+type databaseEntry struct {
+ Name string `json:"name"`
+ Project string `json:"project"`
+ InstanceResource instanceResource `json:"instanceResource"`
+}
+
+// instanceResource holds instance details including data sources.
+type instanceResource struct {
+ Name string `json:"name"`
+ Engine string `json:"engine"`
+ DataSources []dataSource `json:"dataSources"`
+}
+
+// dataSource represents a database data source.
+type dataSource struct {
+ ID string `json:"id"`
+ Type string `json:"type"`
+}
+
+// buildDatabaseFilter builds a CEL filter expression for ListDatabases.
+func buildDatabaseFilter(input QueryInput) string {
+ // name.matches does substring matching server-side.
+ filter := fmt.Sprintf("name.matches(%q)", input.Database)
+ if input.Instance != "" {
+ filter += fmt.Sprintf(" && instance == %q", "instances/"+input.Instance)
+ }
+ if input.Project != "" {
+ filter += fmt.Sprintf(" && project == %q", "projects/"+input.Project)
+ }
+ return filter
+}
+
+// resolveDatabase resolves a database name to a unique resource using tiered matching.
+func (s *Server) resolveDatabase(ctx context.Context, input QueryInput) (*resolvedDatabase, error) {
+ body := map[string]any{
+ "parent": "workspaces/-",
+ "filter": buildDatabaseFilter(input),
+ "pageSize": 1000,
+ }
+ resp, err := s.apiRequest(ctx, "/bytebase.v1.DatabaseService/ListDatabases", body)
+ if err != nil {
+ return nil, errors.Wrap(err, "failed to list databases")
+ }
+ if resp.Status >= 400 {
+ return nil, errors.Errorf("failed to list databases: HTTP %d: %s", resp.Status, parseError(resp.Body))
+ }
+
+ var listResp listDatabasesResponse
+ if err := json.Unmarshal(resp.Body, &listResp); err != nil {
+ return nil, errors.Wrap(err, "failed to parse database list")
+ }
+
+ // Server-side filter already narrows by name substring and instance/project.
+ // Apply client-side tiered matching to pick the best result.
+ databases := listResp.Databases
+
+ // Tiered matching: exact -> case-insensitive exact -> substring.
+ matches := matchExact(databases, input.Database)
+ if len(matches) == 0 {
+ matches = matchCaseInsensitive(databases, input.Database)
+ }
+ if len(matches) == 0 {
+ matches = matchSubstring(databases, input.Database)
+ }
+
+ if len(matches) == 0 {
+ suggestion := "check the database name or use search_api to list available databases"
+ if input.Instance != "" || input.Project != "" {
+ suggestion = "try without instance/project filters, or use search_api to list available databases"
+ }
+ return nil, &toolError{
+ Code: "DATABASE_NOT_FOUND",
+ Message: fmt.Sprintf("no database matching %q", input.Database),
+ Suggestion: suggestion,
+ }
+ }
+
+ if len(matches) > 1 {
+ candidates := make([]Candidate, 0, len(matches))
+ dsIDs := make(map[string]string, len(matches))
+ for _, db := range matches {
+ candidates = append(candidates, Candidate{
+ Database: db.Name,
+ Instance: extractShortName(db.InstanceResource.Name),
+ Project: extractShortName(db.Project),
+ Engine: db.InstanceResource.Engine,
+ })
+ dsIDs[db.Name] = selectDataSource(db.InstanceResource.DataSources)
+ }
+ return &resolvedDatabase{ambiguous: true, candidates: candidates, dataSourceIDs: dsIDs}, nil
+ }
+
+ // Single match.
+ db := matches[0]
+ return &resolvedDatabase{
+ resourceName: db.Name,
+ dataSourceID: selectDataSource(db.InstanceResource.DataSources),
+ }, nil
+}
+
+// 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) {
+ // 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
+ }
+
+ 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",
+ },
+ },
+ "required": []string{"database"},
+ },
+ })
+ if err != nil {
+ return nil, err
+ }
+ if result.Action != "accept" {
+ return nil, errors.Errorf("user %sd database selection", result.Action)
+ }
+
+ selected, ok := result.Content["database"].(string)
+ if !ok {
+ return nil, errors.New("invalid database selection")
+ }
+
+ resourceName, ok := resourceByLabel[selected]
+ if !ok {
+ return nil, errors.Errorf("unknown database selection: %s", selected)
+ }
+
+ return &resolvedDatabase{
+ resourceName: resourceName,
+ dataSourceID: resolved.dataSourceIDs[resourceName],
+ }, nil
+}
+
+// matchExact returns databases whose short name exactly matches the input.
+func matchExact(databases []databaseEntry, name string) []databaseEntry {
+ var result []databaseEntry
+ for _, db := range databases {
+ if extractDatabaseName(db.Name) == name {
+ result = append(result, db)
+ }
+ }
+ return result
+}
+
+// matchCaseInsensitive returns databases whose short name matches case-insensitively.
+func matchCaseInsensitive(databases []databaseEntry, name string) []databaseEntry {
+ var result []databaseEntry
+ lower := strings.ToLower(name)
+ for _, db := range databases {
+ if strings.ToLower(extractDatabaseName(db.Name)) == lower {
+ result = append(result, db)
+ }
+ }
+ return result
+}
+
+// matchSubstring returns databases whose short name contains the input as a substring.
+func matchSubstring(databases []databaseEntry, name string) []databaseEntry {
+ var result []databaseEntry
+ lower := strings.ToLower(name)
+ for _, db := range databases {
+ if strings.Contains(strings.ToLower(extractDatabaseName(db.Name)), lower) {
+ result = append(result, db)
+ }
+ }
+ return result
+}
+
+// extractDatabaseName extracts the database name from a resource name like "instances/prod-pg/databases/employee_db".
+func extractDatabaseName(resourceName string) string {
+ parts := strings.Split(resourceName, "/")
+ if len(parts) >= 4 {
+ return parts[3]
+ }
+ return resourceName
+}
+
+// extractShortName extracts the last segment from a resource name like "instances/prod-pg" or "projects/hr-system".
+func extractShortName(resourceName string) string {
+ parts := strings.Split(resourceName, "/")
+ if len(parts) >= 2 {
+ return parts[len(parts)-1]
+ }
+ return resourceName
+}
+
+// selectDataSource picks READ_ONLY if available, otherwise ADMIN.
+func selectDataSource(dataSources []dataSource) string {
+ var adminID string
+ for _, ds := range dataSources {
+ if ds.Type == "READ_ONLY" {
+ return ds.ID
+ }
+ if ds.Type == "ADMIN" {
+ adminID = ds.ID
+ }
+ }
+ return adminID
+}
+
+// formatQueryOutput formats a successful query result as text header + JSON body.
+func formatQueryOutput(statement, resourceName string, output *QueryOutput) string {
+ var sb strings.Builder
+
+ fmt.Fprintf(&sb, "Query: %s\n", statement)
+ fmt.Fprintf(&sb, "Database: %s\n", resourceName)
+
+ columnList := strings.Join(output.Columns, ", ")
+ if output.Truncated {
+ fmt.Fprintf(&sb, "Result: Showing %d of unknown total rows, %d columns (%s) | %dms\n",
+ output.RowCount, len(output.Columns), columnList, output.LatencyMs)
+ sb.WriteString("Truncated: use limit param for more (max 1000).\n")
+ } else {
+ fmt.Fprintf(&sb, "Result: %d rows, %d columns (%s) | %dms\n",
+ output.RowCount, len(output.Columns), columnList, output.LatencyMs)
+ }
+
+ sb.WriteString("\n")
+ jsonBytes, _ := json.Marshal(output)
+ sb.Write(jsonBytes)
+
+ return sb.String()
+}
+
+// formatToolError converts an error into an MCP error result.
+// If the error is a *toolError, it returns structured JSON with code/message/suggestion.
+// Otherwise, it returns the error message as plain text.
+func formatToolError(err error) *mcp.CallToolResult {
+ var te *toolError
+ if errors.As(err, &te) {
+ jsonBytes, _ := json.MarshalIndent(te, "", " ")
+ return &mcp.CallToolResult{
+ Content: []mcp.Content{&mcp.TextContent{Text: string(jsonBytes)}},
+ IsError: true,
+ }
+ }
+ return &mcp.CallToolResult{
+ Content: []mcp.Content{&mcp.TextContent{Text: err.Error()}},
+ IsError: true,
+ }
+}
+
+// formatAmbiguousResult returns an MCP result for ambiguous database matches.
+func formatAmbiguousResult(database string, candidates []Candidate) *mcp.CallToolResult {
+ result := struct {
+ Code string `json:"code"`
+ Message string `json:"message"`
+ Candidates []Candidate `json:"candidates"`
+ }{
+ Code: "AMBIGUOUS_TARGET",
+ Message: fmt.Sprintf("Multiple databases match %q. Specify instance or project to narrow.", database),
+ Candidates: candidates,
+ }
+
+ jsonBytes, _ := json.MarshalIndent(result, "", " ")
+ return &mcp.CallToolResult{
+ Content: []mcp.Content{&mcp.TextContent{Text: string(jsonBytes)}},
+ IsError: true,
+ }
+}
+
+// executeQuery executes a SQL query against the resolved database.
+func (*Server) executeQuery(_ context.Context, _ *resolvedDatabase, _ string, _ int) (*QueryOutput, error) {
+ return nil, errors.New("not implemented")
+}
diff --git a/backend/api/mcp/tool_query_test.go b/backend/api/mcp/tool_query_test.go
new file mode 100644
index 0000000000..14c278c6fc
--- /dev/null
+++ b/backend/api/mcp/tool_query_test.go
@@ -0,0 +1,337 @@
+package mcp
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "strings"
+ "testing"
+
+ mcpsdk "github.com/modelcontextprotocol/go-sdk/mcp"
+ "github.com/stretchr/testify/require"
+)
+
+// makeDatabase builds a database entry with an ADMIN datasource for mock responses.
+func makeDatabase(name, instanceName, project, engine, dsID string) map[string]any {
+ return map[string]any{
+ "name": name,
+ "project": project,
+ "instanceResource": map[string]any{
+ "name": instanceName,
+ "engine": engine,
+ "dataSources": []any{
+ map[string]any{"id": dsID, "type": "ADMIN"},
+ },
+ },
+ }
+}
+
+// makeDatabaseWithDualDS builds a database entry with both ADMIN and READ_ONLY data sources.
+func makeDatabaseWithDualDS(name, instanceName, project, engine, adminDSID, readOnlyDSID string) map[string]any {
+ return map[string]any{
+ "name": name,
+ "project": project,
+ "instanceResource": map[string]any{
+ "name": instanceName,
+ "engine": engine,
+ "dataSources": []any{
+ map[string]any{"id": adminDSID, "type": "ADMIN"},
+ map[string]any{"id": readOnlyDSID, "type": "READ_ONLY"},
+ },
+ },
+ }
+}
+
+// mockListDatabases returns an HTTP handler that serves a ListDatabases response.
+// It applies basic filter awareness: if the request contains a "filter" field with
+// an instance constraint, only matching databases are returned.
+func mockListDatabases(databases []map[string]any) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ var reqBody struct {
+ Filter string `json:"filter"`
+ }
+ _ = json.NewDecoder(r.Body).Decode(&reqBody)
+
+ result := databases
+ if reqBody.Filter != "" {
+ result = applyMockFilter(databases, reqBody.Filter)
+ }
+
+ resp := map[string]any{"databases": result}
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ _ = json.NewEncoder(w).Encode(resp)
+ })
+}
+
+// applyMockFilter applies a simplified filter to mock databases.
+// Supports: name.matches("x"), instance == "instances/x", project == "projects/x"
+func applyMockFilter(databases []map[string]any, filter string) []map[string]any {
+ var result []map[string]any
+ for _, db := range databases {
+ name, ok := db["name"].(string)
+ if !ok {
+ continue
+ }
+ ir, ok := db["instanceResource"].(map[string]any)
+ if !ok {
+ continue
+ }
+ instanceName, ok := ir["name"].(string)
+ if !ok {
+ continue
+ }
+ project, ok := db["project"].(string)
+ if !ok {
+ continue
+ }
+
+ match := true
+ // Check name.matches("x") — substring match
+ if idx := strings.Index(filter, `name.matches(`); idx >= 0 {
+ start := idx + len(`name.matches("`)
+ end := strings.Index(filter[start:], `"`)
+ if end > 0 {
+ substr := filter[start : start+end]
+ if !strings.Contains(strings.ToLower(name), strings.ToLower(substr)) {
+ match = false
+ }
+ }
+ }
+ // Check instance == "instances/x"
+ if idx := strings.Index(filter, `instance == "`); idx >= 0 {
+ start := idx + len(`instance == "`)
+ end := strings.Index(filter[start:], `"`)
+ if end > 0 {
+ expected := filter[start : start+end]
+ if instanceName != expected {
+ match = false
+ }
+ }
+ }
+ // Check project == "projects/x"
+ if idx := strings.Index(filter, `project == "`); idx >= 0 {
+ start := idx + len(`project == "`)
+ end := strings.Index(filter[start:], `"`)
+ if end > 0 {
+ expected := filter[start : start+end]
+ if project != expected {
+ match = false
+ }
+ }
+ }
+ if match {
+ result = append(result, db)
+ }
+ }
+ return result
+}
+
+func TestQueryDatabase_SingleMatch(t *testing.T) {
+ databases := []map[string]any{
+ makeDatabase("instances/prod-pg/databases/employee_db", "instances/prod-pg", "projects/hr-system", "POSTGRES", "ds-admin-1"),
+ makeDatabase("instances/prod-pg/databases/orders_db", "instances/prod-pg", "projects/commerce", "POSTGRES", "ds-admin-2"),
+ }
+ s := newTestServerWithMock(t, mockListDatabases(databases))
+
+ resolved, err := s.resolveDatabase(context.Background(), QueryInput{Database: "employee_db"})
+ require.NoError(t, err)
+ require.False(t, resolved.ambiguous)
+ require.Equal(t, "instances/prod-pg/databases/employee_db", resolved.resourceName)
+ require.Equal(t, "ds-admin-1", resolved.dataSourceID)
+}
+
+func TestQueryDatabase_CaseInsensitiveMatch(t *testing.T) {
+ databases := []map[string]any{
+ makeDatabase("instances/prod-pg/databases/employee_db", "instances/prod-pg", "projects/hr-system", "POSTGRES", "ds-admin-1"),
+ }
+ s := newTestServerWithMock(t, mockListDatabases(databases))
+
+ resolved, err := s.resolveDatabase(context.Background(), QueryInput{Database: "Employee_DB"})
+ require.NoError(t, err)
+ require.False(t, resolved.ambiguous)
+ require.Equal(t, "instances/prod-pg/databases/employee_db", resolved.resourceName)
+}
+
+func TestQueryDatabase_SubstringMatch(t *testing.T) {
+ databases := []map[string]any{
+ makeDatabase("instances/prod-pg/databases/employee_db", "instances/prod-pg", "projects/hr-system", "POSTGRES", "ds-admin-1"),
+ }
+ s := newTestServerWithMock(t, mockListDatabases(databases))
+
+ resolved, err := s.resolveDatabase(context.Background(), QueryInput{Database: "employee"})
+ require.NoError(t, err)
+ require.False(t, resolved.ambiguous)
+ require.Equal(t, "instances/prod-pg/databases/employee_db", resolved.resourceName)
+}
+
+func TestQueryDatabase_NotFound(t *testing.T) {
+ databases := []map[string]any{
+ makeDatabase("instances/prod-pg/databases/employee_db", "instances/prod-pg", "projects/hr-system", "POSTGRES", "ds-admin-1"),
+ }
+ s := newTestServerWithMock(t, mockListDatabases(databases))
+
+ _, err := s.resolveDatabase(context.Background(), QueryInput{Database: "nonexistent"})
+ require.Error(t, err)
+
+ var te *toolError
+ require.ErrorAs(t, err, &te)
+ require.Equal(t, "DATABASE_NOT_FOUND", te.Code)
+ require.Contains(t, te.Suggestion, "search_api")
+}
+
+func TestQueryDatabase_NotFoundWithFilters(t *testing.T) {
+ databases := []map[string]any{
+ makeDatabase("instances/prod-pg/databases/employee_db", "instances/prod-pg", "projects/hr-system", "POSTGRES", "ds-admin-1"),
+ }
+ s := newTestServerWithMock(t, mockListDatabases(databases))
+
+ _, err := s.resolveDatabase(context.Background(), QueryInput{
+ Database: "employee_db",
+ Instance: "nonexistent-instance",
+ })
+ require.Error(t, err)
+
+ var te *toolError
+ require.ErrorAs(t, err, &te)
+ require.Equal(t, "DATABASE_NOT_FOUND", te.Code)
+ require.Contains(t, te.Suggestion, "without instance/project filters")
+}
+
+func TestQueryDatabase_Ambiguous(t *testing.T) {
+ databases := []map[string]any{
+ makeDatabase("instances/prod-pg/databases/employee_db", "instances/prod-pg", "projects/hr-system", "POSTGRES", "ds-admin-1"),
+ makeDatabase("instances/staging-mysql/databases/employee_db", "instances/staging-mysql", "projects/hr-system", "MYSQL", "ds-admin-2"),
+ }
+ s := newTestServerWithMock(t, mockListDatabases(databases))
+
+ resolved, err := s.resolveDatabase(context.Background(), QueryInput{Database: "employee_db"})
+ require.NoError(t, err)
+ require.True(t, resolved.ambiguous)
+ require.Len(t, resolved.candidates, 2)
+ require.Equal(t, "instances/prod-pg/databases/employee_db", resolved.candidates[0].Database)
+ require.Equal(t, "POSTGRES", resolved.candidates[0].Engine)
+ require.Equal(t, "instances/staging-mysql/databases/employee_db", resolved.candidates[1].Database)
+ require.Equal(t, "MYSQL", resolved.candidates[1].Engine)
+}
+
+func TestQueryDatabase_AmbiguousWithInstance(t *testing.T) {
+ databases := []map[string]any{
+ makeDatabase("instances/prod-pg/databases/employee_db", "instances/prod-pg", "projects/hr-system", "POSTGRES", "ds-admin-1"),
+ makeDatabase("instances/staging/databases/employee_db", "instances/staging", "projects/hr-system", "POSTGRES", "ds-admin-2"),
+ }
+ s := newTestServerWithMock(t, mockListDatabases(databases))
+
+ resolved, err := s.resolveDatabase(context.Background(), QueryInput{
+ Database: "employee_db",
+ Instance: "prod-pg",
+ })
+ require.NoError(t, err)
+ require.False(t, resolved.ambiguous)
+ require.Equal(t, "instances/prod-pg/databases/employee_db", resolved.resourceName)
+ require.Equal(t, "ds-admin-1", resolved.dataSourceID)
+}
+
+func TestQueryDatabase_ReadOnlyDatasource(t *testing.T) {
+ databases := []map[string]any{
+ makeDatabaseWithDualDS("instances/prod-pg/databases/employee_db", "instances/prod-pg", "projects/hr-system", "POSTGRES", "ds-admin-1", "ds-ro-1"),
+ }
+ s := newTestServerWithMock(t, mockListDatabases(databases))
+
+ resolved, err := s.resolveDatabase(context.Background(), QueryInput{Database: "employee_db"})
+ require.NoError(t, err)
+ require.False(t, resolved.ambiguous)
+ require.Equal(t, "ds-ro-1", resolved.dataSourceID)
+}
+
+func TestQueryDatabase_AdminFallback(t *testing.T) {
+ databases := []map[string]any{
+ makeDatabase("instances/prod-pg/databases/employee_db", "instances/prod-pg", "projects/hr-system", "POSTGRES", "ds-admin-1"),
+ }
+ s := newTestServerWithMock(t, mockListDatabases(databases))
+
+ resolved, err := s.resolveDatabase(context.Background(), QueryInput{Database: "employee_db"})
+ require.NoError(t, err)
+ require.False(t, resolved.ambiguous)
+ require.Equal(t, "ds-admin-1", resolved.dataSourceID)
+}
+
+func TestQueryDatabase_FormatAmbiguousResult(t *testing.T) {
+ candidates := []Candidate{
+ {Database: "instances/prod-pg/databases/employee_db", Instance: "prod-pg", Project: "hr-system", Engine: "POSTGRES"},
+ {Database: "instances/staging/databases/employee_db", Instance: "staging", Project: "hr-system", Engine: "POSTGRES"},
+ }
+
+ result := formatAmbiguousResult("employee_db", candidates)
+ require.True(t, result.IsError)
+ require.Len(t, result.Content, 1)
+
+ textContent, ok := result.Content[0].(*mcpsdk.TextContent)
+ require.True(t, ok)
+
+ var parsed struct {
+ Code string `json:"code"`
+ Message string `json:"message"`
+ Candidates []Candidate `json:"candidates"`
+ }
+ err := json.Unmarshal([]byte(textContent.Text), &parsed)
+ require.NoError(t, err)
+ require.Equal(t, "AMBIGUOUS_TARGET", parsed.Code)
+ require.Len(t, parsed.Candidates, 2)
+}
+
+func TestQueryDatabase_HandleValidation(t *testing.T) {
+ s := newTestServerWithMock(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ fmt.Fprint(w, `{"databases": []}`)
+ }))
+
+ // Missing database.
+ _, _, err := s.handleQueryDatabase(context.Background(), nil, QueryInput{Statement: "SELECT 1"})
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "database is required")
+
+ // Missing statement.
+ _, _, err = s.handleQueryDatabase(context.Background(), nil, QueryInput{Database: "employee_db"})
+ require.Error(t, err)
+ require.Contains(t, err.Error(), "statement is required")
+}
+
+func TestQueryDatabase_LimitNormalization(t *testing.T) {
+ // Verify limit is capped at maxQueryLimit via the handler.
+ // We test the handler which calls resolveDatabase, so the database must not be found
+ // to avoid hitting the executeQuery stub. We just verify the handler doesn't panic.
+ databases := []map[string]any{
+ makeDatabase("instances/prod-pg/databases/employee_db", "instances/prod-pg", "projects/hr-system", "POSTGRES", "ds-admin-1"),
+ }
+ s := newTestServerWithMock(t, mockListDatabases(databases))
+
+ // The handler resolves the database, then calls executeQuery which returns "not implemented".
+ // That's expected — we verify the handler doesn't error on limit normalization.
+ result, _, err := s.handleQueryDatabase(context.Background(), nil, QueryInput{
+ Database: "employee_db",
+ Statement: "SELECT 1",
+ Limit: 2000,
+ })
+ // Should return IsError result from executeQuery stub, not a limit error.
+ require.NoError(t, err)
+ require.True(t, result.IsError)
+ text := result.Content[0].(*mcpsdk.TextContent).Text
+ require.Contains(t, text, "not implemented")
+}
+
+func TestQueryDatabase_ExactMatchPriority(t *testing.T) {
+ // When both exact and substring matches exist, exact should win.
+ databases := []map[string]any{
+ makeDatabase("instances/prod-pg/databases/employee", "instances/prod-pg", "projects/hr-system", "POSTGRES", "ds-1"),
+ makeDatabase("instances/prod-pg/databases/employee_db", "instances/prod-pg", "projects/hr-system", "POSTGRES", "ds-2"),
+ }
+ s := newTestServerWithMock(t, mockListDatabases(databases))
+
+ resolved, err := s.resolveDatabase(context.Background(), QueryInput{Database: "employee"})
+ require.NoError(t, err)
+ require.False(t, resolved.ambiguous)
+ require.Equal(t, "instances/prod-pg/databases/employee", resolved.resourceName)
+ require.Equal(t, "ds-1", resolved.dataSourceID)
+}