feat(tools/alloydb-get-instance): Add get-instance tool for alloydb (#1435)

## Description

---
This pull request introduces a new custom tool kind
`alloydb-get-instance` that retrieves detailed information for a
specific AlloyDB instance.

### Example Configuration

```yaml
tools:
  get_instance:
    kind: alloydb-get-instance
    source: alloydb-admin-source
    description: Use this tool to retrieve detailed information for a specific AlloyDB instance.
```

### Example Request
``` 
curl -X POST http://127.0.0.1:5000/api/tool/get_instance/invoke \
-H "Content-Type: application/json" \
-d '{
    "projectId": "example-project",
    "locationId": "us-central1",
    "clusterId": "my-alloydb-cluster",
    "instanceId": "my-alloydb-instance",
}'
```

## PR Checklist

---
> Thank you for opening a Pull Request! Before submitting your PR, there
are a
> few things you can do to make sure it goes smoothly:

- [x] Make sure you reviewed

[CONTRIBUTING.md](https://github.com/googleapis/genai-toolbox/blob/main/CONTRIBUTING.md)
- [ ] Make sure to open an issue as a

[bug/issue](https://github.com/googleapis/genai-toolbox/issues/new/choose)
before writing your code! That way we can discuss the change, evaluate
  designs, and agree on the general idea
- [x] Ensure the tests and linter pass
- [x] Code coverage does not decrease (if any source code was changed)
- [x] Appropriate docs were updated (if necessary)
- [x] Make sure to add `!` if this involve a breaking change

🛠️ Fixes #<issue_number_goes_here>
This commit is contained in:
Sri Varshitha
2025-09-16 11:13:03 +05:30
committed by GitHub
parent da246610e1
commit f2d9e3b579
7 changed files with 410 additions and 9 deletions

View File

@@ -43,6 +43,7 @@ import (
// Import tool packages for side effect of registration
_ "github.com/googleapis/genai-toolbox/internal/tools/alloydb/alloydbgetcluster"
_ "github.com/googleapis/genai-toolbox/internal/tools/alloydb/alloydbgetinstance"
_ "github.com/googleapis/genai-toolbox/internal/tools/alloydb/alloydblistclusters"
_ "github.com/googleapis/genai-toolbox/internal/tools/alloydb/alloydblistinstances"
_ "github.com/googleapis/genai-toolbox/internal/tools/alloydb/alloydblistusers"

View File

@@ -1342,7 +1342,7 @@ func TestPrebuiltTools(t *testing.T) {
wantToolset: server.ToolsetConfigs{
"alloydb_postgres_admin_tools": tools.ToolsetConfig{
Name: "alloydb_postgres_admin_tools",
ToolNames: []string{"create_cluster", "wait_for_operation", "create_instance", "list_clusters", "list_instances", "list_users", "create_user", "get_cluster"},
ToolNames: []string{"create_cluster", "wait_for_operation", "create_instance", "list_clusters", "list_instances", "list_users", "create_user", "get_cluster", "get_instance"},
},
},
},

View File

@@ -0,0 +1,38 @@
---
title: "alloydb-get-instance"
type: docs
weight: 1
description: >
The "alloydb-get-instance" tool retrieves details for a specific AlloyDB instance.
aliases:
- /resources/tools/alloydb-get-instance
---
## About
The `alloydb-get-instance` tool retrieves detailed information for a single, specified AlloyDB instance. It is compatible with [alloydb-admin](../../sources/alloydb-admin.md) source.
| Parameter | Type | Description | Required |
| :--------- | :----- | :--------------------------------------------------------------------------------------- | :------- |
| `project` | string | The GCP project ID to get instance for. | Yes |
| `location` | string | The location of the instance (e.g., 'us-central1'). | Yes |
| `cluster` | string | The ID of the cluster. | Yes |
| `instance` | string | The ID of the instance to retrieve. | Yes |
> **Note**
> This tool authenticates using the credentials configured in its [alloydb-admin](../../sources/alloydb-admin.md) source which can be either [Application Default Credentials](https://cloud.google.com/docs/authentication/application-default-credentials) or client-side OAuth.
## Example
```yaml
tools:
get_specific_instance:
kind: alloydb-get-instance
source: my-alloydb-admin-source
description: Use this tool to retrieve details for a specific AlloyDB instance.
```
## Reference
| **field** | **type** | **required** | **description** |
|-------------|:------------------------------------------:|:------------:|--------------------------------------------------------------------------------------------------|
| kind | string | true | Must be alloydb-get-instance. | |
| source | string | true | The name of an `alloydb-admin` source. |
| description | string | true | Description of the tool that is passed to the agent. |

View File

@@ -193,6 +193,10 @@ tools:
kind: alloydb-get-cluster
source: alloydb-admin-source
description: "Retrieves details of a specific AlloyDB cluster."
get_instance:
kind: alloydb-get-instance
source: alloydb-admin-source
description: "Retrieves details of a specific AlloyDB instance."
toolsets:
alloydb_postgres_admin_tools:
@@ -204,3 +208,4 @@ toolsets:
- list_users
- create_user
- get_cluster
- get_instance

View File

@@ -0,0 +1,170 @@
// 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 alloydbgetinstance
import (
"context"
"fmt"
yaml "github.com/goccy/go-yaml"
"github.com/googleapis/genai-toolbox/internal/sources"
alloydbadmin "github.com/googleapis/genai-toolbox/internal/sources/alloydbadmin"
"github.com/googleapis/genai-toolbox/internal/tools"
)
const kind string = "alloydb-get-instance"
func init() {
if !tools.Register(kind, newConfig) {
panic(fmt.Sprintf("tool kind %q already registered", kind))
}
}
func newConfig(ctx context.Context, name string, decoder *yaml.Decoder) (tools.ToolConfig, error) {
actual := Config{Name: name}
if err := decoder.DecodeContext(ctx, &actual); err != nil {
return nil, err
}
return actual, nil
}
// Configuration for the get-instance tool.
type Config struct {
Name string `yaml:"name" validate:"required"`
Kind string `yaml:"kind" validate:"required"`
Source string `yaml:"source" validate:"required"`
Description string `yaml:"description" validate:"required"`
AuthRequired []string `yaml:"authRequired"`
BaseURL string `yaml:"baseURL"`
}
// validate interface
var _ tools.ToolConfig = Config{}
// ToolConfigKind returns the kind of the tool.
func (cfg Config) ToolConfigKind() string {
return kind
}
// Initialize initializes the tool from the configuration.
func (cfg Config) Initialize(srcs map[string]sources.Source) (tools.Tool, error) {
rawS, ok := srcs[cfg.Source]
if !ok {
return nil, fmt.Errorf("source %q not found", cfg.Source)
}
s, ok := rawS.(*alloydbadmin.Source)
if !ok {
return nil, fmt.Errorf("invalid source for %q tool: source kind must be `%s`", kind, alloydbadmin.SourceKind)
}
allParameters := tools.Parameters{
tools.NewStringParameter("project", "The GCP project ID."),
tools.NewStringParameter("location", "The location of the instance (e.g., 'us-central1')."),
tools.NewStringParameter("cluster", "The ID of the cluster."),
tools.NewStringParameter("instance", "The ID of the instance."),
}
paramManifest := allParameters.Manifest()
inputSchema := allParameters.McpManifest()
inputSchema.Required = []string{"project", "location", "cluster", "instance"}
mcpManifest := tools.McpManifest{
Name: cfg.Name,
Description: cfg.Description,
InputSchema: inputSchema,
}
return Tool{
Name: cfg.Name,
Kind: kind,
Source: s,
AllParams: allParameters,
manifest: tools.Manifest{Description: cfg.Description, Parameters: paramManifest},
mcpManifest: mcpManifest,
}, nil
}
// Tool represents the get-instance tool.
type Tool struct {
Name string `yaml:"name"`
Kind string `yaml:"kind"`
Source *alloydbadmin.Source
AllParams tools.Parameters
manifest tools.Manifest
mcpManifest tools.McpManifest
}
// Invoke executes the tool's logic.
func (t Tool) Invoke(ctx context.Context, params tools.ParamValues, accessToken tools.AccessToken) (any, error) {
paramsMap := params.AsMap()
project, ok := paramsMap["project"].(string)
if !ok {
return nil, fmt.Errorf("invalid or missing 'project' parameter; expected a string")
}
location, ok := paramsMap["location"].(string)
if !ok {
return nil, fmt.Errorf("invalid 'location' parameter; expected a string")
}
cluster, ok := paramsMap["cluster"].(string)
if !ok {
return nil, fmt.Errorf("invalid 'cluster' parameter; expected a string")
}
instance, ok := paramsMap["instance"].(string)
if !ok {
return nil, fmt.Errorf("invalid 'instance' parameter; expected a string")
}
service, err := t.Source.GetService(ctx, string(accessToken))
if err != nil {
return nil, err
}
urlString := fmt.Sprintf("projects/%s/locations/%s/clusters/%s/instances/%s", project, location, cluster, instance)
resp, err := service.Projects.Locations.Clusters.Instances.Get(urlString).Do()
if err != nil {
return nil, fmt.Errorf("error getting AlloyDB instance: %w", err)
}
return resp, nil
}
// ParseParams parses the parameters for the tool.
func (t Tool) ParseParams(data map[string]any, claims map[string]map[string]any) (tools.ParamValues, error) {
return tools.ParseParams(t.AllParams, data, claims)
}
// Manifest returns the tool's manifest.
func (t Tool) Manifest() tools.Manifest {
return t.manifest
}
// McpManifest returns the tool's MCP manifest.
func (t Tool) McpManifest() tools.McpManifest {
return t.mcpManifest
}
// Authorized checks if the tool is authorized.
func (t Tool) Authorized(verifiedAuthServices []string) bool {
return true
}
func (t Tool) RequiresClientAuthorization() bool {
return t.Source.UseClientAuthorization()
}

View File

@@ -0,0 +1,94 @@
// 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 alloydbgetinstance_test
import (
"testing"
yaml "github.com/goccy/go-yaml"
"github.com/google/go-cmp/cmp"
"github.com/googleapis/genai-toolbox/internal/server"
"github.com/googleapis/genai-toolbox/internal/testutils"
alloydbgetinstance "github.com/googleapis/genai-toolbox/internal/tools/alloydb/alloydbgetinstance"
)
func TestParseFromYaml(t *testing.T) {
ctx, err := testutils.ContextWithNewLogger()
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
tcs := []struct {
desc string
in string
want server.ToolConfigs
}{
{
desc: "basic example",
in: `
tools:
get-my-instance:
kind: alloydb-get-instance
source: my-alloydb-admin-source
description: some description
`,
want: server.ToolConfigs{
"get-my-instance": alloydbgetinstance.Config{
Name: "get-my-instance",
Kind: "alloydb-get-instance",
Source: "my-alloydb-admin-source",
Description: "some description",
AuthRequired: []string{},
},
},
},
{
desc: "with auth required",
in: `
tools:
get-my-instance-auth:
kind: alloydb-get-instance
source: my-alloydb-admin-source
description: some description
authRequired:
- my-google-auth-service
- other-auth-service
`,
want: server.ToolConfigs{
"get-my-instance-auth": alloydbgetinstance.Config{
Name: "get-my-instance-auth",
Kind: "alloydb-get-instance",
Source: "my-alloydb-admin-source",
Description: "some description",
AuthRequired: []string{"my-google-auth-service", "other-auth-service"},
},
},
},
}
for _, tc := range tcs {
t.Run(tc.desc, func(t *testing.T) {
got := struct {
Tools server.ToolConfigs `yaml:"tools"`
}{}
// Parse contents
err := yaml.UnmarshalContext(ctx, testutils.FormatYaml(tc.in), &got)
if err != nil {
t.Fatalf("unable to unmarshal: %s", err)
}
if diff := cmp.Diff(tc.want, got.Tools); diff != "" {
t.Fatalf("incorrect parse: diff %v", diff)
}
})
}
}

View File

@@ -115,6 +115,11 @@ func getAlloyDBToolsConfig() map[string]any {
"source": "alloydb-admin-source",
"description": "Retrieves details of a specific AlloyDB cluster.",
},
"alloydb-get-instance": map[string]any{
"kind": "alloydb-get-instance",
"source": "alloydb-admin-source",
"description": "Retrieves details of a specific AlloyDB instance.",
},
},
}
}
@@ -149,6 +154,7 @@ func TestAlloyDBToolEndpoints(t *testing.T) {
runAlloyDBListUsersTest(t, vars)
runAlloyDBListInstancesTest(t, vars)
runAlloyDBGetClusterTest(t, vars)
runAlloyDBGetInstanceTest(t, vars)
}
func runAlloyDBToolGetTest(t *testing.T) {
@@ -685,7 +691,6 @@ func runAlloyDBGetClusterTest(t *testing.T, vars map[string]string) {
Result string `json:"result"`
}
invokeTcs := []struct {
name string
requestBody io.Reader
@@ -723,7 +728,6 @@ func runAlloyDBGetClusterTest(t *testing.T, vars map[string]string) {
},
}
for _, tc := range invokeTcs {
t.Run(tc.name, func(t *testing.T) {
api := "http://127.0.0.1:5000/api/tool/alloydb-get-cluster/invoke"
@@ -733,34 +737,29 @@ func runAlloyDBGetClusterTest(t *testing.T, vars map[string]string) {
}
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 resp.StatusCode != tc.wantStatusCode {
bodyBytes, _ := io.ReadAll(resp.Body)
t.Fatalf("response status code is not %d, got %d: %s", tc.wantStatusCode, resp.StatusCode, string(bodyBytes))
}
if tc.wantStatusCode == http.StatusOK {
var body ToolResponse
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
t.Fatalf("error parsing response body: %v", err)
}
if tc.want != nil {
var gotMap map[string]any
if err := json.Unmarshal([]byte(body.Result), &gotMap); err != nil {
t.Fatalf("failed to unmarshal JSON result into map: %v", err)
}
got := make(map[string]any)
for key := range tc.want {
if value, ok := gotMap[key]; ok {
@@ -768,7 +767,101 @@ func runAlloyDBGetClusterTest(t *testing.T, vars map[string]string) {
}
}
if diff := cmp.Diff(tc.want, got); diff != "" {
t.Errorf("Unexpected result: got %#v, want: %#v", got, tc.want)
}
}
}
})
}
}
func runAlloyDBGetInstanceTest(t *testing.T, vars map[string]string) {
type ToolResponse struct {
Result string `json:"result"`
}
invokeTcs := []struct {
name string
requestBody io.Reader
want map[string]any
wantStatusCode int
}{
{
name: "get instance success",
requestBody: bytes.NewBufferString(fmt.Sprintf(`{"project": "%s", "location": "%s", "cluster": "%s", "instance": "%s"}`, vars["projectId"], vars["locationId"], vars["clusterId"], vars["instanceId"])),
want: map[string]any{
"instanceType": "PRIMARY",
"name": fmt.Sprintf("projects/%s/locations/%s/clusters/%s/instances/%s", vars["projectId"], vars["locationId"], vars["clusterId"], vars["instanceId"]),
},
wantStatusCode: http.StatusOK,
},
{
name: "get instance missing project",
requestBody: bytes.NewBufferString(fmt.Sprintf(`{"location": "%s", "cluster": "%s", "instance": "%s"}`, vars["locationId"], vars["clusterId"], vars["instanceId"])),
wantStatusCode: http.StatusBadRequest,
},
{
name: "get instance missing location",
requestBody: bytes.NewBufferString(fmt.Sprintf(`{"project": "%s", "cluster": "%s", "instance": "%s"}`, vars["projectId"], vars["clusterId"], vars["instanceId"])),
wantStatusCode: http.StatusBadRequest,
},
{
name: "get instance missing clusterId",
requestBody: bytes.NewBufferString(fmt.Sprintf(`{"project": "%s", "location": "%s", "instance": "%s"}`, vars["projectId"], vars["locationId"], vars["instanceId"])),
wantStatusCode: http.StatusBadRequest,
},
{
name: "get instance missing instanceId",
requestBody: bytes.NewBufferString(fmt.Sprintf(`{"project": "%s", "location": "%s", "cluster": "%s"}`, vars["projectId"], vars["locationId"], vars["clusterId"])),
wantStatusCode: http.StatusBadRequest,
},
{
name: "get instance non-existent instance",
requestBody: bytes.NewBufferString(fmt.Sprintf(`{"project": "%s", "location": "%s", "cluster": "%s", "instance": "non-existent-instance"}`, vars["projectId"], vars["locationId"], vars["clusterId"])),
wantStatusCode: http.StatusBadRequest,
},
}
for _, tc := range invokeTcs {
t.Run(tc.name, func(t *testing.T) {
api := "http://127.0.0.1:5000/api/tool/alloydb-get-instance/invoke"
req, err := http.NewRequest(http.MethodPost, api, tc.requestBody)
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 resp.StatusCode != tc.wantStatusCode {
bodyBytes, _ := io.ReadAll(resp.Body)
t.Fatalf("response status code is not %d, got %d: %s", tc.wantStatusCode, resp.StatusCode, string(bodyBytes))
}
if tc.wantStatusCode == http.StatusOK {
var body ToolResponse
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
t.Fatalf("error parsing response body: %v", err)
}
if tc.want != nil {
var gotMap map[string]any
if err := json.Unmarshal([]byte(body.Result), &gotMap); err != nil {
t.Fatalf("failed to unmarshal JSON result into map: %v", err)
}
got := make(map[string]any)
for key := range tc.want {
if value, ok := gotMap[key]; ok {
got[key] = value
}
}
if diff := cmp.Diff(tc.want, got); diff != "" {
t.Errorf("Unexpected result: got %#v, want: %#v", got, tc.want)
}