chore: import upstream snapshot with attribution
CF: Deploy Dev Docs / deploy (push) Has been cancelled
Sync Labels / build (push) Has been cancelled
tests / unit tests (macos-latest) (push) Has been cancelled
tests / unit tests (windows-latest) (push) Has been cancelled
tests / unit tests (ubuntu-latest) (push) Has been cancelled

This commit is contained in:
wehub-resource-sync
2026-07-13 13:32:45 +08:00
commit e04ed9c211
1798 changed files with 307905 additions and 0 deletions
@@ -0,0 +1,277 @@
// Copyright 2025 Google LLC
//
// Licensed 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 cloudsqlmysql_test
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"reflect"
"regexp"
"strings"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"github.com/googleapis/mcp-toolbox/internal/testutils"
"github.com/googleapis/mcp-toolbox/tests"
"google.golang.org/api/sqladmin/v1"
)
var (
createInstanceToolType = "cloud-sql-mysql-create-instance"
)
type createInstanceTransport struct {
transport http.RoundTripper
url *url.URL
}
func (t *createInstanceTransport) RoundTrip(req *http.Request) (*http.Response, error) {
if strings.HasPrefix(req.URL.String(), "https://sqladmin.googleapis.com") {
req.URL.Scheme = t.url.Scheme
req.URL.Host = t.url.Host
}
return t.transport.RoundTrip(req)
}
type masterHandler struct {
t *testing.T
}
func (h *masterHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.UserAgent(), "genai-toolbox/") {
h.t.Errorf("User-Agent header not found")
}
var body sqladmin.DatabaseInstance
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
h.t.Fatalf("failed to decode request body: %v", err)
}
instanceName := body.Name
if instanceName == "" {
http.Error(w, "missing instance name", http.StatusBadRequest)
return
}
var expectedBody sqladmin.DatabaseInstance
var response any
var statusCode int
switch instanceName {
case "instance1":
expectedBody = sqladmin.DatabaseInstance{
Project: "p1",
Name: "instance1",
DatabaseVersion: "MYSQL_8_0",
RootPassword: "password123",
Settings: &sqladmin.Settings{
AvailabilityType: "REGIONAL",
Edition: "ENTERPRISE_PLUS",
Tier: "db-perf-optimized-N-8",
DataDiskSizeGb: 250,
DataDiskType: "PD_SSD",
},
}
response = map[string]any{"name": "op1", "status": "PENDING"}
statusCode = http.StatusOK
case "instance2":
expectedBody = sqladmin.DatabaseInstance{
Project: "p2",
Name: "instance2",
DatabaseVersion: "MYSQL_8_4",
RootPassword: "password456",
Settings: &sqladmin.Settings{
AvailabilityType: "ZONAL",
Edition: "ENTERPRISE_PLUS",
Tier: "db-perf-optimized-N-2",
DataDiskSizeGb: 100,
DataDiskType: "PD_SSD",
},
}
response = map[string]any{"name": "op2", "status": "RUNNING"}
statusCode = http.StatusOK
default:
http.Error(w, fmt.Sprintf("unhandled instance name: %s", instanceName), http.StatusInternalServerError)
return
}
if expectedBody.Project != body.Project {
h.t.Errorf("unexpected project: got %q, want %q", body.Project, expectedBody.Project)
}
if expectedBody.Name != body.Name {
h.t.Errorf("unexpected name: got %q, want %q", body.Name, expectedBody.Name)
}
if expectedBody.DatabaseVersion != body.DatabaseVersion {
h.t.Errorf("unexpected databaseVersion: got %q, want %q", body.DatabaseVersion, expectedBody.DatabaseVersion)
}
if expectedBody.RootPassword != body.RootPassword {
h.t.Errorf("unexpected rootPassword: got %q, want %q", body.RootPassword, expectedBody.RootPassword)
}
if diff := cmp.Diff(expectedBody.Settings, body.Settings); diff != "" {
h.t.Errorf("unexpected request body settings (-want +got):\n%s", diff)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
if err := json.NewEncoder(w).Encode(response); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func TestCreateInstanceToolEndpoints(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
handler := &masterHandler{t: t}
server := httptest.NewServer(handler)
defer server.Close()
serverURL, err := url.Parse(server.URL)
if err != nil {
t.Fatalf("failed to parse server URL: %v", err)
}
originalTransport := http.DefaultClient.Transport
if originalTransport == nil {
originalTransport = http.DefaultTransport
}
http.DefaultClient.Transport = &createInstanceTransport{
transport: originalTransport,
url: serverURL,
}
t.Cleanup(func() {
http.DefaultClient.Transport = originalTransport
})
args := []string{"--enable-api"}
toolsFile := getCreateInstanceToolsConfig()
cmd, cleanup, err := tests.StartCmd(ctx, toolsFile, args...)
if err != nil {
t.Fatalf("command initialization returned an error: %s", err)
}
defer cleanup()
waitCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
out, err := testutils.WaitForString(waitCtx, regexp.MustCompile(`Server ready to serve`), cmd.Out)
if err != nil {
t.Logf("toolbox command logs: \n%s", out)
t.Fatalf("toolbox didn't start successfully: %s", err)
}
tcs := []struct {
name string
toolName string
body string
want string
expectError bool
errorStatus int
}{
{
name: "successful creation - production",
toolName: "create-instance-prod",
body: `{"project": "p1", "name": "instance1", "databaseVersion": "MYSQL_8_0", "rootPassword": "password123", "editionPreset": "Production"}`,
want: `{"name":"op1","status":"PENDING"}`,
},
{
name: "successful creation - development",
toolName: "create-instance-dev",
body: `{"project": "p2", "name": "instance2", "rootPassword": "password456", "editionPreset": "Development"}`,
want: `{"name":"op2","status":"RUNNING"}`,
},
{
name: "missing required parameter",
toolName: "create-instance-prod",
body: `{"name": "instance1"}`,
want: `{"error":"parameter \"project\" is required"}`,
},
}
for _, tc := range tcs {
tc := tc
t.Run(tc.name, func(t *testing.T) {
api := fmt.Sprintf("http://127.0.0.1:5000/api/tool/%s/invoke", tc.toolName)
req, err := http.NewRequest(http.MethodPost, api, bytes.NewBufferString(tc.body))
if err != nil {
t.Fatalf("unable to create request: %s", err)
}
req.Header.Add("Content-type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatalf("unable to send request: %s", err)
}
defer resp.Body.Close()
if tc.expectError {
if resp.StatusCode != tc.errorStatus {
bodyBytes, _ := io.ReadAll(resp.Body)
t.Fatalf("expected status %d but got %d: %s", tc.errorStatus, resp.StatusCode, string(bodyBytes))
}
return
}
if resp.StatusCode != http.StatusOK {
bodyBytes, _ := io.ReadAll(resp.Body)
t.Fatalf("response status code is not 200, got %d: %s", resp.StatusCode, string(bodyBytes))
}
var result struct {
Result string `json:"result"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
t.Fatalf("failed to decode response: %v", err)
}
var got, want map[string]any
if err := json.Unmarshal([]byte(result.Result), &got); err != nil {
t.Fatalf("failed to unmarshal result: %v", err)
}
if err := json.Unmarshal([]byte(tc.want), &want); err != nil {
t.Fatalf("failed to unmarshal want: %v", err)
}
if !reflect.DeepEqual(got, want) {
t.Fatalf("unexpected result: got %+v, want %+v", got, want)
}
})
}
}
func getCreateInstanceToolsConfig() map[string]any {
return map[string]any{
"sources": map[string]any{
"my-cloud-sql-source": map[string]any{
"type": "cloud-sql-admin",
},
},
"tools": map[string]any{
"create-instance-prod": map[string]any{
"type": createInstanceToolType,
"source": "my-cloud-sql-source",
},
"create-instance-dev": map[string]any{
"type": createInstanceToolType,
"source": "my-cloud-sql-source",
},
},
}
}
@@ -0,0 +1,261 @@
// Copyright 2026 Google LLC
//
// Licensed 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 cloudsqlmysql_test
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"regexp"
"strings"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"github.com/googleapis/mcp-toolbox/internal/testutils"
"github.com/googleapis/mcp-toolbox/tests"
"google.golang.org/api/sqladmin/v1"
)
const createInstanceToolTypeMCP = "cloud-sql-mysql-create-instance"
type createInstanceTransportMCP struct {
transport http.RoundTripper
url *url.URL
}
func (t *createInstanceTransportMCP) RoundTrip(req *http.Request) (*http.Response, error) {
if strings.HasPrefix(req.URL.String(), "https://sqladmin.googleapis.com") {
req.URL.Scheme = t.url.Scheme
req.URL.Host = t.url.Host
}
return t.transport.RoundTrip(req)
}
type masterHandlerMCP struct {
t *testing.T
}
func (h *masterHandlerMCP) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.UserAgent(), "genai-toolbox/") {
h.t.Errorf("User-Agent header not found")
}
var body sqladmin.DatabaseInstance
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
h.t.Fatalf("failed to decode request body: %v", err)
}
instanceName := body.Name
if instanceName == "" {
http.Error(w, "missing instance name", http.StatusBadRequest)
return
}
var expectedBody sqladmin.DatabaseInstance
var response any
var statusCode int
switch instanceName {
case "instance1":
expectedBody = sqladmin.DatabaseInstance{
Project: "p1",
Name: "instance1",
DatabaseVersion: "MYSQL_8_0",
RootPassword: "password123",
Settings: &sqladmin.Settings{
AvailabilityType: "REGIONAL",
Edition: "ENTERPRISE_PLUS",
Tier: "db-perf-optimized-N-8",
DataDiskSizeGb: 250,
DataDiskType: "PD_SSD",
},
}
response = map[string]any{"name": "op1", "status": "PENDING"}
statusCode = http.StatusOK
case "instance2":
expectedBody = sqladmin.DatabaseInstance{
Project: "p2",
Name: "instance2",
DatabaseVersion: "MYSQL_8_4",
RootPassword: "password456",
Settings: &sqladmin.Settings{
AvailabilityType: "ZONAL",
Edition: "ENTERPRISE_PLUS",
Tier: "db-perf-optimized-N-2",
DataDiskSizeGb: 100,
DataDiskType: "PD_SSD",
},
}
response = map[string]any{"name": "op2", "status": "RUNNING"}
statusCode = http.StatusOK
default:
http.Error(w, fmt.Sprintf("unhandled instance name: %s", instanceName), http.StatusInternalServerError)
return
}
if expectedBody.Project != body.Project {
h.t.Errorf("unexpected project: got %q, want %q", body.Project, expectedBody.Project)
}
if expectedBody.Name != body.Name {
h.t.Errorf("unexpected name: got %q, want %q", body.Name, expectedBody.Name)
}
if expectedBody.DatabaseVersion != body.DatabaseVersion {
h.t.Errorf("unexpected databaseVersion: got %q, want %q", body.DatabaseVersion, expectedBody.DatabaseVersion)
}
if expectedBody.RootPassword != body.RootPassword {
h.t.Errorf("unexpected rootPassword: got %q, want %q", body.RootPassword, expectedBody.RootPassword)
}
if diff := cmp.Diff(expectedBody.Settings, body.Settings); diff != "" {
h.t.Errorf("unexpected request body settings (-want +got):\n%s", diff)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
if err := json.NewEncoder(w).Encode(response); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func TestCreateInstanceToolEndpointsMCP(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
handler := &masterHandlerMCP{t: t}
server := httptest.NewServer(handler)
defer server.Close()
serverURL, err := url.Parse(server.URL)
if err != nil {
t.Fatalf("failed to parse server URL: %v", err)
}
originalTransport := http.DefaultClient.Transport
if originalTransport == nil {
originalTransport = http.DefaultTransport
}
http.DefaultClient.Transport = &createInstanceTransportMCP{
transport: originalTransport,
url: serverURL,
}
t.Cleanup(func() {
http.DefaultClient.Transport = originalTransport
})
toolsFile := getCreateInstanceToolsConfigMCP()
cmd, cleanup, err := tests.StartCmd(ctx, toolsFile)
if err != nil {
t.Fatalf("command initialization returned an error: %v", err)
}
defer cleanup()
waitCtx, cancelWait := context.WithTimeout(ctx, 10*time.Second)
defer cancelWait()
out, err := testutils.WaitForString(waitCtx, regexp.MustCompile(`Server ready to serve`), cmd.Out)
if err != nil {
t.Logf("toolbox command logs: \n%s", out)
t.Fatalf("toolbox didn't start successfully: %v", err)
}
tcs := []struct {
name string
toolName string
body string
want string
expectError bool
}{
{
name: "verify successful instance creation with production preset",
toolName: "create-instance-prod",
body: `{"project": "p1", "name": "instance1", "databaseVersion": "MYSQL_8_0", "rootPassword": "password123", "editionPreset": "Production"}`,
want: `{"name":"op1","status":"PENDING"}`,
expectError: false,
},
{
name: "verify successful instance creation with development preset",
toolName: "create-instance-dev",
body: `{"project": "p2", "name": "instance2", "rootPassword": "password456", "editionPreset": "Development"}`,
want: `{"name":"op2","status":"RUNNING"}`,
expectError: false,
},
{
name: "verify missing required parameter returns schema error",
toolName: "create-instance-prod",
body: `{"name": "instance1"}`,
want: `parameter "project" is required`,
expectError: true,
},
}
for _, tc := range tcs {
t.Run(tc.name, func(t *testing.T) {
var args map[string]any
if err := json.Unmarshal([]byte(tc.body), &args); err != nil {
t.Fatalf("failed to unmarshal body: %v", err)
}
statusCode, mcpResp, err := tests.InvokeMCPTool(t, tc.toolName, args, nil)
if err != nil {
t.Fatalf("native error executing %s: %v", tc.toolName, err)
}
if statusCode != http.StatusOK {
t.Fatalf("expected status 200, got %d", statusCode)
}
if tc.expectError {
tests.AssertMCPError(t, mcpResp, tc.want)
} else {
if mcpResp.Result.IsError {
t.Fatalf("expected success, got error result: %v", mcpResp.Result)
}
gotStr := mcpResp.Result.Content[0].Text
var got, want map[string]any
if err := json.Unmarshal([]byte(gotStr), &got); err != nil {
t.Fatalf("failed to unmarshal result: %v", err)
}
if err := json.Unmarshal([]byte(tc.want), &want); err != nil {
t.Fatalf("failed to unmarshal want: %v", err)
}
if diff := cmp.Diff(want, got); diff != "" {
t.Errorf("unexpected result (-want +got):\n%s", diff)
}
}
})
}
}
func getCreateInstanceToolsConfigMCP() map[string]any {
return map[string]any{
"sources": map[string]any{
"my-cloud-sql-source": map[string]any{
"type": "cloud-sql-admin",
},
},
"tools": map[string]any{
"create-instance-prod": map[string]any{
"type": createInstanceToolTypeMCP,
"source": "my-cloud-sql-source",
},
"create-instance-dev": map[string]any{
"type": createInstanceToolTypeMCP,
"source": "my-cloud-sql-source",
},
},
}
}
@@ -0,0 +1,300 @@
// Copyright 2024 Google LLC
//
// Licensed 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 cloudsqlmysql
import (
"context"
"database/sql"
"fmt"
"os"
"regexp"
"slices"
"strings"
"testing"
"time"
"cloud.google.com/go/cloudsqlconn"
"cloud.google.com/go/cloudsqlconn/mysql/mysql"
"github.com/google/uuid"
"github.com/googleapis/mcp-toolbox/internal/testutils"
"github.com/googleapis/mcp-toolbox/tests"
)
var (
CloudSQLMySQLSourceType = "cloud-sql-mysql"
CloudSQLMySQLToolType = "mysql-sql"
CloudSQLMySQLProject = os.Getenv("CLOUD_SQL_MYSQL_PROJECT")
CloudSQLMySQLRegion = os.Getenv("CLOUD_SQL_MYSQL_REGION")
CloudSQLMySQLInstance = os.Getenv("CLOUD_SQL_MYSQL_INSTANCE")
CloudSQLMySQLDatabase = os.Getenv("CLOUD_SQL_MYSQL_DATABASE")
CloudSQLMySQLUser = os.Getenv("CLOUD_SQL_MYSQL_USER")
CloudSQLMySQLPass = os.Getenv("CLOUD_SQL_MYSQL_PASS")
)
func getCloudSQLMySQLVars(t *testing.T) map[string]any {
switch "" {
case CloudSQLMySQLProject:
t.Fatal("'CLOUD_SQL_MYSQL_PROJECT' not set")
case CloudSQLMySQLRegion:
t.Fatal("'CLOUD_SQL_MYSQL_REGION' not set")
case CloudSQLMySQLInstance:
t.Fatal("'CLOUD_SQL_MYSQL_INSTANCE' not set")
case CloudSQLMySQLDatabase:
t.Fatal("'CLOUD_SQL_MYSQL_DATABASE' not set")
case CloudSQLMySQLUser:
t.Fatal("'CLOUD_SQL_MYSQL_USER' not set")
case CloudSQLMySQLPass:
t.Fatal("'CLOUD_SQL_MYSQL_PASS' not set")
}
return map[string]any{
"type": CloudSQLMySQLSourceType,
"project": CloudSQLMySQLProject,
"instance": CloudSQLMySQLInstance,
"region": CloudSQLMySQLRegion,
"database": CloudSQLMySQLDatabase,
"user": CloudSQLMySQLUser,
"password": CloudSQLMySQLPass,
}
}
// Copied over from cloud_sql_mysql.go
func initCloudSQLMySQLConnectionPool(project, region, instance, ipType, user, pass, dbname string) (*sql.DB, error) {
// Create a new dialer with options
dialOpts, err := tests.GetCloudSQLDialOpts(ipType)
if err != nil {
return nil, err
}
if !slices.Contains(sql.Drivers(), "cloudsql-mysql") {
_, err = mysql.RegisterDriver("cloudsql-mysql", cloudsqlconn.WithDefaultDialOptions(dialOpts...))
if err != nil {
return nil, fmt.Errorf("unable to register driver: %w", err)
}
}
// Tell the driver to use the Cloud SQL Go Connector to create connections
dsn := fmt.Sprintf("%s:%s@cloudsql-mysql(%s:%s:%s)/%s", user, pass, project, region, instance, dbname)
db, err := sql.Open(
"cloudsql-mysql",
dsn,
)
if err != nil {
return nil, err
}
return db, nil
}
func TestCloudSQLMySQLToolEndpoints(t *testing.T) {
sourceConfig := getCloudSQLMySQLVars(t)
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
args := []string{"--enable-api"}
pool, err := initCloudSQLMySQLConnectionPool(CloudSQLMySQLProject, CloudSQLMySQLRegion, CloudSQLMySQLInstance, "public", CloudSQLMySQLUser, CloudSQLMySQLPass, CloudSQLMySQLDatabase)
if err != nil {
t.Fatalf("unable to create Cloud SQL connection pool: %s", err)
}
// cleanup test environment
tests.CleanupMySQLTables(t, ctx, pool)
// create table name with UUID
tableNameParam := "param_table_" + strings.ReplaceAll(uuid.New().String(), "-", "")
tableNameAuth := "auth_table_" + strings.ReplaceAll(uuid.New().String(), "-", "")
tableNameTemplateParam := "template_param_table_" + strings.ReplaceAll(uuid.New().String(), "-", "")
// set up data for param tool
createParamTableStmt, insertParamTableStmt, paramToolStmt, idParamToolStmt, nameParamToolStmt, arrayToolStmt, paramTestParams := tests.GetMySQLParamToolInfo(tableNameParam)
teardownTable1 := tests.SetupMySQLTable(t, ctx, pool, createParamTableStmt, insertParamTableStmt, tableNameParam, paramTestParams)
defer teardownTable1(t)
// set up data for auth tool
createAuthTableStmt, insertAuthTableStmt, authToolStmt, authTestParams := tests.GetMySQLAuthToolInfo(tableNameAuth)
teardownTable2 := tests.SetupMySQLTable(t, ctx, pool, createAuthTableStmt, insertAuthTableStmt, tableNameAuth, authTestParams)
defer teardownTable2(t)
// Write config into a file and pass it to command
toolsFile := tests.GetToolsConfig(sourceConfig, CloudSQLMySQLToolType, paramToolStmt, idParamToolStmt, nameParamToolStmt, arrayToolStmt, authToolStmt)
toolsFile = tests.AddMySqlExecuteSqlConfig(t, toolsFile)
tmplSelectCombined, tmplSelectFilterCombined := tests.GetMySQLTmplToolStatement()
toolsFile = tests.AddTemplateParamConfig(t, toolsFile, CloudSQLMySQLToolType, tmplSelectCombined, tmplSelectFilterCombined, "")
toolsFile = tests.AddMySQLPrebuiltToolConfig(t, toolsFile)
cmd, cleanup, err := tests.StartCmd(ctx, toolsFile, args...)
if err != nil {
t.Fatalf("command initialization returned an error: %s", err)
}
defer cleanup()
waitCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
out, err := testutils.WaitForString(waitCtx, regexp.MustCompile(`Server ready to serve`), cmd.Out)
if err != nil {
t.Logf("toolbox command logs: \n%s", out)
t.Fatalf("toolbox didn't start successfully: %s", err)
}
// Get configs for tests
select1Want, mcpMyFailToolWant, createTableStatement, mcpSelect1Want := tests.GetMySQLWants()
// Run tests
tests.RunToolGetTest(t)
tests.RunToolInvokeTest(t, select1Want, tests.DisableArrayTest())
tests.RunMCPToolCallMethod(t, mcpMyFailToolWant, mcpSelect1Want)
tests.RunExecuteSqlToolInvokeTest(t, createTableStatement, select1Want)
tests.RunToolInvokeWithTemplateParameters(t, tableNameTemplateParam)
// Run specific MySQL tool tests
const expectedOwner = "'toolbox-identity'@'%'"
tests.RunMySQLListTablesTest(t, CloudSQLMySQLDatabase, tableNameParam, tableNameAuth, expectedOwner)
tests.RunMySQLListActiveQueriesTest(t, ctx, pool)
tests.RunMySQLGetQueryPlanTest(t, ctx, pool, CloudSQLMySQLDatabase, tableNameParam)
tests.RunMySQLListAllLocks(t, ctx, pool, CloudSQLMySQLDatabase)
tests.RunMySQLShowQueryStats(t, ctx, pool, CloudSQLMySQLDatabase)
tests.RunMySQLListTableStatsTest(t, ctx, pool, CloudSQLMySQLDatabase, tableNameParam, tableNameAuth)
}
// Test connection with different IP type
func TestCloudSQLMySQLIpConnection(t *testing.T) {
sourceConfig := getCloudSQLMySQLVars(t)
tcs := []struct {
name string
ipType string
}{
{
name: "public ip",
ipType: "public",
},
{
name: "private ip",
ipType: "private",
},
}
for _, tc := range tcs {
t.Run(tc.name, func(t *testing.T) {
sourceConfig["ipType"] = tc.ipType
err := tests.RunSourceConnectionTest(t, sourceConfig, CloudSQLMySQLToolType)
if err != nil {
t.Fatalf("Connection test failure: %s", err)
}
})
}
}
func TestCloudSQLMySQLIAMConnection(t *testing.T) {
getCloudSQLMySQLVars(t)
// service account email used for IAM should trim the suffix
serviceAccountEmail, _, _ := strings.Cut(tests.ServiceAccountEmail, "@")
noPassSourceConfig := map[string]any{
"type": CloudSQLMySQLSourceType,
"project": CloudSQLMySQLProject,
"instance": CloudSQLMySQLInstance,
"region": CloudSQLMySQLRegion,
"database": CloudSQLMySQLDatabase,
"user": serviceAccountEmail,
}
noUserSourceConfig := map[string]any{
"type": CloudSQLMySQLSourceType,
"project": CloudSQLMySQLProject,
"instance": CloudSQLMySQLInstance,
"region": CloudSQLMySQLRegion,
"database": CloudSQLMySQLDatabase,
"password": "random",
}
noUserNoPassSourceConfig := map[string]any{
"type": CloudSQLMySQLSourceType,
"project": CloudSQLMySQLProject,
"instance": CloudSQLMySQLInstance,
"region": CloudSQLMySQLRegion,
"database": CloudSQLMySQLDatabase,
}
tcs := []struct {
name string
sourceConfig map[string]any
isErr bool
}{
{
name: "no user no pass",
sourceConfig: noUserNoPassSourceConfig,
isErr: false,
},
{
name: "no password",
sourceConfig: noPassSourceConfig,
isErr: false,
},
{
name: "no user",
sourceConfig: noUserSourceConfig,
isErr: true,
},
}
for i, tc := range tcs {
t.Run(tc.name, func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
// Generate a UNIQUE source name for this test case.
// It ensures the app registers a unique driver name
// like "cloudsql-mysql-iam-test-0", preventing conflicts.
uniqueSourceName := fmt.Sprintf("iam-test-%d", i)
// Construct the tools config manually (Copied from RunSourceConnectionTest)
toolsFile := map[string]any{
"sources": map[string]any{
uniqueSourceName: tc.sourceConfig,
},
"tools": map[string]any{
"my-simple-tool": map[string]any{
"type": CloudSQLMySQLToolType,
"source": uniqueSourceName,
"description": "Simple tool to test end to end functionality.",
"statement": "SELECT 1;",
},
},
}
// Start the Toolbox Command
args := []string{"--enable-api"}
cmd, cleanup, err := tests.StartCmd(ctx, toolsFile, args...)
if err != nil {
t.Fatalf("command initialization returned an error: %s", err)
}
defer cleanup()
// Wait for the server to be ready
waitCtx, waitCancel := context.WithTimeout(ctx, 10*time.Second)
defer waitCancel()
out, err := testutils.WaitForString(waitCtx, regexp.MustCompile(`Server ready to serve`), cmd.Out)
if err != nil {
if tc.isErr {
return
}
t.Logf("toolbox command logs: \n%s", out)
t.Fatalf("Connection test failure: toolbox didn't start successfully: %s", err)
}
if tc.isErr {
t.Fatalf("Expected error but test passed.")
}
})
}
}
@@ -0,0 +1,253 @@
// Copyright 2026 Google LLC
//
// Licensed 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 cloudsqlmysql
import (
"context"
"regexp"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/googleapis/mcp-toolbox/internal/testutils"
"github.com/googleapis/mcp-toolbox/tests"
)
func TestCloudSQLMySQLMCPListTools(t *testing.T) {
sourceConfig := getCloudSQLMySQLVars(t)
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
pool, err := initCloudSQLMySQLConnectionPool(CloudSQLMySQLProject, CloudSQLMySQLRegion, CloudSQLMySQLInstance, "public", CloudSQLMySQLUser, CloudSQLMySQLPass, CloudSQLMySQLDatabase)
if err != nil {
t.Fatalf("unable to create Cloud SQL connection pool: %s", err)
}
// cleanup test environment
tests.CleanupMySQLTables(t, ctx, pool)
// create table name with UUID
tableNameParam := "param_table_" + strings.ReplaceAll(uuid.New().String(), "-", "")
tableNameAuth := "auth_table_" + strings.ReplaceAll(uuid.New().String(), "-", "")
// set up data for param tool
createParamTableStmt, insertParamTableStmt, paramToolStmt, idParamToolStmt, nameParamToolStmt, arrayToolStmt, paramTestParams := tests.GetMySQLParamToolInfo(tableNameParam)
teardownTable1 := tests.SetupMySQLTable(t, ctx, pool, createParamTableStmt, insertParamTableStmt, tableNameParam, paramTestParams)
defer teardownTable1(t)
// set up data for auth tool
createAuthTableStmt, insertAuthTableStmt, authToolStmt, authTestParams := tests.GetMySQLAuthToolInfo(tableNameAuth)
teardownTable2 := tests.SetupMySQLTable(t, ctx, pool, createAuthTableStmt, insertAuthTableStmt, tableNameAuth, authTestParams)
defer teardownTable2(t)
// Write config into a file and pass it to command
toolsFile := tests.GetToolsConfig(sourceConfig, CloudSQLMySQLToolType, paramToolStmt, idParamToolStmt, nameParamToolStmt, arrayToolStmt, authToolStmt)
toolsFile = tests.AddMySqlExecuteSqlConfig(t, toolsFile)
tmplSelectCombined, tmplSelectFilterCombined := tests.GetMySQLTmplToolStatement()
toolsFile = tests.AddTemplateParamConfig(t, toolsFile, CloudSQLMySQLToolType, tmplSelectCombined, tmplSelectFilterCombined, "")
toolsFile = tests.AddMySQLPrebuiltToolConfig(t, toolsFile)
cmd, cleanup, err := tests.StartCmd(ctx, toolsFile)
if err != nil {
t.Fatalf("command initialization returned an error: %s", err)
}
defer cleanup()
waitCtx, waitCancel := context.WithTimeout(ctx, 10*time.Second)
defer waitCancel()
out, err := testutils.WaitForString(waitCtx, regexp.MustCompile(`Server ready to serve`), cmd.Out)
if err != nil {
t.Logf("toolbox command logs: \n%s", out)
t.Fatalf("toolbox didn't start successfully: %s", err)
}
// Expected Manifest
expectedTools := tests.GetBaseMCPExpectedTools()
expectedTools = append(expectedTools, tests.GetExecuteSQLMCPExpectedTools()...)
expectedTools = append(expectedTools, tests.GetTemplateParamMCPExpectedTools()...)
expectedTools = append(expectedTools, []tests.MCPToolManifest{
{
Name: "list_tables",
Description: "Lists tables in the database.",
InputSchema: map[string]any{
"type": "object",
"properties": map[string]any{
"output_format": map[string]any{"default": "detailed", "description": "Optional: Use 'simple' for names only or 'detailed' for full info.", "type": "string"},
"table_names": map[string]any{"default": "", "description": "Optional: A comma-separated list of table names. If empty, details for all tables will be listed.", "type": "string"},
},
"required": []any{},
},
},
{
Name: "list_active_queries",
Description: "Lists active queries in the database.",
InputSchema: map[string]any{
"type": "object",
"properties": map[string]any{
"limit": map[string]any{"default": float64(100), "description": "Optional: The maximum number of rows to return.", "type": "integer"},
"min_duration_secs": map[string]any{"default": float64(0), "description": "Optional: Only show queries running for at least this long in seconds", "type": "integer"},
},
"required": []any{},
},
},
{
Name: "list_tables_missing_unique_indexes",
Description: "Lists tables that do not have primary or unique indexes in the database.",
InputSchema: map[string]any{
"type": "object",
"properties": map[string]any{
"limit": map[string]any{"default": float64(50), "description": "(Optional) Max rows to return, default is 50", "type": "integer"},
"table_schema": map[string]any{"default": "", "description": "(Optional) The database where the check is to be performed. Check all tables visible to the current user if not specified", "type": "string"},
},
"required": []any{},
},
},
{
Name: "list_table_fragmentation",
Description: "Lists table fragmentation in the database.",
InputSchema: map[string]any{
"type": "object",
"properties": map[string]any{
"data_free_threshold_bytes": map[string]any{"default": float64(1), "description": "(Optional) Only show tables with at least this much free space in bytes. Default is 1", "type": "integer"},
"limit": map[string]any{"default": float64(10), "description": "(Optional) Max rows to return, default is 10", "type": "integer"},
"table_name": map[string]any{"default": "", "description": "(Optional) Name of the table to be checked. Check all tables visible to the current user if not specified.", "type": "string"},
"table_schema": map[string]any{"default": "", "description": "(Optional) The database where fragmentation check is to be executed. Check all tables visible to the current user if not specified", "type": "string"},
},
"required": []any{},
},
},
{
Name: "list_table_stats",
Description: "Lists table stats in the database.",
InputSchema: map[string]any{
"type": "object",
"properties": map[string]any{
"connected_schema": map[string]any{"description": "(Optional) The connected db", "type": "string"},
"limit": map[string]any{"default": float64(10), "description": "(Optional) Max rows to return, default is 10", "type": "integer"},
"sort_by": map[string]any{"default": "", "description": "(Optional) The column to sort by", "type": "string"},
"table_name": map[string]any{"default": "", "description": "(Optional) Name of the table to be checked. Check all tables visible to the current user if not specified.", "type": "string"},
"table_schema": map[string]any{"default": "", "description": "(Optional) The database where statistics is to be executed. Check all tables visible to the current user if not specified", "type": "string"},
},
"required": []any{},
},
},
{
Name: "get_query_plan",
Description: "Gets the query plan for a SQL statement.",
InputSchema: map[string]any{
"type": "object",
"properties": map[string]any{
"sql_statement": map[string]any{"type": "string", "description": "The sql statement to explain."},
},
"required": []any{"sql_statement"},
},
},
{
Name: "show_query_stats",
Description: "Lists query statistics in the database.",
InputSchema: map[string]any{
"type": "object",
"properties": map[string]any{
"connected_schema": map[string]any{"description": "(Optional) The database user is connected to, the value is set from env variable CLOUD_SQL_MYSQL_DATABASE or MYSQL_DATABASE", "type": "string"},
"limit": map[string]any{"default": float64(10), "description": "(Optional) Max rows to return, default is 10", "type": "integer"},
"table_schema": map[string]any{"default": "", "description": "(Optional) The database where query statistics is to be executed. Check all queries visible to the current user if not specified", "type": "string"},
},
"required": []any{},
},
},
{
Name: "list_all_locks",
Description: "Lists all table, row locks in the database.",
InputSchema: map[string]any{
"type": "object",
"properties": map[string]any{
"connected_schema": map[string]any{"description": "(Optional) The database user is connected to, the value is set from env variable CLOUD_SQL_MYSQL_DATABASE or MYSQL_DATABASE", "type": "string"},
"limit": map[string]any{"default": float64(10), "description": "(Optional) Max rows to return, default is 10", "type": "integer"},
"table_name": map[string]any{"default": "", "description": "(Optional) Name of the table to be checked. Check all tables visible to the current user if not specified.", "type": "string"},
"table_schema": map[string]any{"default": "", "description": "(Optional) The database where locked object is detected. Check all databases if not specified.", "type": "string"},
},
"required": []any{},
},
},
}...)
t.Run("verify tools/list registry returns complete manifest", func(t *testing.T) {
tests.RunMCPToolsListMethod(t, expectedTools)
})
}
func TestCloudSQLMySQLMCPCallTool(t *testing.T) {
sourceConfig := getCloudSQLMySQLVars(t)
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
pool, err := initCloudSQLMySQLConnectionPool(CloudSQLMySQLProject, CloudSQLMySQLRegion, CloudSQLMySQLInstance, "public", CloudSQLMySQLUser, CloudSQLMySQLPass, CloudSQLMySQLDatabase)
if err != nil {
t.Fatalf("unable to create Cloud SQL connection pool: %s", err)
}
// cleanup test environment
tests.CleanupMySQLTables(t, ctx, pool)
// create table name with UUID
tableNameParam := "param_table_" + strings.ReplaceAll(uuid.New().String(), "-", "")
tableNameAuth := "auth_table_" + strings.ReplaceAll(uuid.New().String(), "-", "")
tableNameTemplateParam := "template_param_table_" + strings.ReplaceAll(uuid.New().String(), "-", "")
// set up data for param tool
createParamTableStmt, insertParamTableStmt, paramToolStmt, idParamToolStmt, nameParamToolStmt, arrayToolStmt, paramTestParams := tests.GetMySQLParamToolInfo(tableNameParam)
teardownTable1 := tests.SetupMySQLTable(t, ctx, pool, createParamTableStmt, insertParamTableStmt, tableNameParam, paramTestParams)
defer teardownTable1(t)
// set up data for auth tool
createAuthTableStmt, insertAuthTableStmt, authToolStmt, authTestParams := tests.GetMySQLAuthToolInfo(tableNameAuth)
teardownTable2 := tests.SetupMySQLTable(t, ctx, pool, createAuthTableStmt, insertAuthTableStmt, tableNameAuth, authTestParams)
defer teardownTable2(t)
// Write config into a file and pass it to command
toolsFile := tests.GetToolsConfig(sourceConfig, CloudSQLMySQLToolType, paramToolStmt, idParamToolStmt, nameParamToolStmt, arrayToolStmt, authToolStmt)
toolsFile = tests.AddMySqlExecuteSqlConfig(t, toolsFile)
tmplSelectCombined, tmplSelectFilterCombined := tests.GetMySQLTmplToolStatement()
toolsFile = tests.AddTemplateParamConfig(t, toolsFile, CloudSQLMySQLToolType, tmplSelectCombined, tmplSelectFilterCombined, "")
toolsFile = tests.AddMySQLPrebuiltToolConfig(t, toolsFile)
cmd, cleanup, err := tests.StartCmd(ctx, toolsFile)
if err != nil {
t.Fatalf("command initialization returned an error: %s", err)
}
defer cleanup()
waitCtx, waitCancel := context.WithTimeout(ctx, 10*time.Second)
defer waitCancel()
out, err := testutils.WaitForString(waitCtx, regexp.MustCompile(`Server ready to serve`), cmd.Out)
if err != nil {
t.Logf("toolbox command logs: \n%s", out)
t.Fatalf("toolbox didn't start successfully: %s", err)
}
select1Want, mcpMyFailToolWant, createTableStatement, mcpSelect1Want := tests.GetMySQLWants()
tests.RunToolInvokeTest(t, select1Want, tests.DisableArrayTest(), tests.WithMCP(), tests.WithNullWant("[]"))
tests.RunMCPToolCallMethod(t, mcpMyFailToolWant, mcpSelect1Want)
tests.RunExecuteSqlToolInvokeTest(t, createTableStatement, select1Want, tests.WithMCPSql(), tests.WithExecuteCreateWant("[]"), tests.WithExecuteDropWant("[]"), tests.WithExecuteSelectEmptyWant("[]"))
tests.RunToolInvokeWithTemplateParameters(t, tableNameTemplateParam, tests.WithMCPTemplate())
// Run specific MySQL tool tests over MCP
const expectedOwner = "'toolbox-identity'@'%'"
tests.RunMySQLListTablesTest(t, CloudSQLMySQLDatabase, tableNameParam, tableNameAuth, expectedOwner, tests.WithMCPExec())
tests.RunMySQLListActiveQueriesTest(t, ctx, pool, tests.WithMCPExec())
tests.RunMySQLGetQueryPlanTest(t, ctx, pool, CloudSQLMySQLDatabase, tableNameParam, tests.WithMCPExec())
}