Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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 cloudsqlmssql_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-mssql-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: "SQLSERVER_2022_ENTERPRISE",
RootPassword: "password123",
Settings: &sqladmin.Settings{
AvailabilityType: "REGIONAL",
Edition: "ENTERPRISE",
Tier: "db-custom-4-26624",
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: "SQLSERVER_2022_STANDARD",
RootPassword: "password456",
Settings: &sqladmin.Settings{
AvailabilityType: "ZONAL",
Edition: "ENTERPRISE",
Tier: "db-custom-2-8192",
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": "SQLSERVER_2022_ENTERPRISE", "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",
},
},
}
}
108 changes: 0 additions & 108 deletions tests/cloudsqlmssql/cloud_sql_mssql_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,96 +16,16 @@ package cloudsqlmssql

import (
"context"
"database/sql"
"fmt"
"net/url"
"os"
"regexp"
"slices"
"strings"
"testing"
"time"

"cloud.google.com/go/cloudsqlconn"
"cloud.google.com/go/cloudsqlconn/sqlserver/mssql"
"github.com/google/uuid"
"github.com/googleapis/mcp-toolbox/internal/testutils"
"github.com/googleapis/mcp-toolbox/tests"
)

var (
CloudSQLMSSQLSourceType = "cloud-sql-mssql"
CloudSQLMSSQLToolType = "mssql-sql"
CloudSQLMSSQLProject = os.Getenv("CLOUD_SQL_MSSQL_PROJECT")
CloudSQLMSSQLRegion = os.Getenv("CLOUD_SQL_MSSQL_REGION")
CloudSQLMSSQLInstance = os.Getenv("CLOUD_SQL_MSSQL_INSTANCE")
CloudSQLMSSQLDatabase = os.Getenv("CLOUD_SQL_MSSQL_DATABASE")
CloudSQLMSSQLUser = os.Getenv("CLOUD_SQL_MSSQL_USER")
CloudSQLMSSQLPass = os.Getenv("CLOUD_SQL_MSSQL_PASS")
)

func getCloudSQLMSSQLVars(t *testing.T) map[string]any {
switch "" {
case CloudSQLMSSQLProject:
t.Fatal("'CLOUD_SQL_MSSQL_PROJECT' not set")
case CloudSQLMSSQLRegion:
t.Fatal("'CLOUD_SQL_MSSQL_REGION' not set")
case CloudSQLMSSQLInstance:
t.Fatal("'CLOUD_SQL_MSSQL_INSTANCE' not set")
case CloudSQLMSSQLDatabase:
t.Fatal("'CLOUD_SQL_MSSQL_DATABASE' not set")
case CloudSQLMSSQLUser:
t.Fatal("'CLOUD_SQL_MSSQL_USER' not set")
case CloudSQLMSSQLPass:
t.Fatal("'CLOUD_SQL_MSSQL_PASS' not set")
}

return map[string]any{
"type": CloudSQLMSSQLSourceType,
"project": CloudSQLMSSQLProject,
"instance": CloudSQLMSSQLInstance,
"region": CloudSQLMSSQLRegion,
"database": CloudSQLMSSQLDatabase,
"user": CloudSQLMSSQLUser,
"password": CloudSQLMSSQLPass,
}
}

// Copied over from cloud_sql_mssql.go
func initCloudSQLMSSQLConnection(project, region, instance, ipType, user, pass, dbname string) (*sql.DB, error) {
// Create dsn
query := fmt.Sprintf("database=%s&cloudsql=%s:%s:%s", dbname, project, region, instance)
url := &url.URL{
Scheme: "sqlserver",
User: url.UserPassword(user, pass),
RawQuery: query,
}

// Get dial options
dialOpts, err := tests.GetCloudSQLDialOpts(ipType)
if err != nil {
return nil, err
}

// Register sql server driver
if !slices.Contains(sql.Drivers(), "cloudsql-sqlserver-driver") {
_, err := mssql.RegisterDriver("cloudsql-sqlserver-driver", cloudsqlconn.WithDefaultDialOptions(dialOpts...))
if err != nil {
return nil, err
}
}

// Open database connection
db, err := sql.Open(
"cloudsql-sqlserver-driver",
url.String(),
)
if err != nil {
return nil, err
}
return db, nil
}

func TestCloudSQLMSSQLToolEndpoints(t *testing.T) {
sourceConfig := getCloudSQLMSSQLVars(t)
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
Expand Down Expand Up @@ -170,31 +90,3 @@ func TestCloudSQLMSSQLToolEndpoints(t *testing.T) {
// Run specific MSSQL tool tests
tests.RunMSSQLListTablesTest(t, tableNameParam, tableNameAuth)
}

// Test connection with different IP type
func TestCloudSQLMSSQLIpConnection(t *testing.T) {
sourceConfig := getCloudSQLMSSQLVars(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, CloudSQLMSSQLToolType)
if err != nil {
t.Fatalf("Connection test failure: %s", err)
}
})
}
}
Loading
Loading