feat(tools/alloydb-list-users): Add new custom tool kind for AlloyDB list_users (#1377)

## Description

---
This pull request introduces a new custom tool kind `alloydb-list-users`
that allows users to list all database users within an AlloyDB cluster.

### Example Configuration

```yaml
tools:
  list_users:
    kind: alloydb-list-users
    source: alloydb-admin-source
    description: Use this tool to list all database users within an AlloyDB cluster
```

### Example Request
``` 
curl -X POST http://127.0.0.1:5000/api/tool/list_users/invoke \
-H "Content-Type: application/json" \
-d '{
    "projectId": "example-project",
    "locationId": "us-central1",
    "clusterId": "example-cluster",
}'
```
## 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>

---------

Co-authored-by: Averi Kitsch <akitsch@google.com>
This commit is contained in:
Sri Varshitha
2025-09-12 14:44:21 +05:30
committed by GitHub
parent 236be89961
commit 3a8a65ceaa
8 changed files with 441 additions and 20 deletions

View File

@@ -71,6 +71,7 @@ steps:
- "ALLOYDB_PROJECT=$PROJECT_ID"
- "ALLOYDB_CLUSTER=$_ALLOYDB_POSTGRES_CLUSTER"
- "ALLOYDB_REGION=$_REGION"
secretEnv: ["ALLOYDB_POSTGRES_USER"]
volumes:
- name: "go"
path: "/gopath"

View File

@@ -42,8 +42,9 @@ import (
"github.com/googleapis/genai-toolbox/internal/util"
// Import tool packages for side effect of registration
_ "github.com/googleapis/genai-toolbox/internal/tools/alloydb/alloydblistclusters"
_ "github.com/googleapis/genai-toolbox/internal/tools/alloydbainl"
_ "github.com/googleapis/genai-toolbox/internal/tools/alloydb/alloydblistclusters"
_ "github.com/googleapis/genai-toolbox/internal/tools/alloydb/alloydblistusers"
_ "github.com/googleapis/genai-toolbox/internal/tools/bigquery/bigqueryanalyzecontribution"
_ "github.com/googleapis/genai-toolbox/internal/tools/bigquery/bigqueryconversationalanalytics"
_ "github.com/googleapis/genai-toolbox/internal/tools/bigquery/bigqueryexecutesql"

View File

@@ -1339,7 +1339,7 @@ func TestPrebuiltTools(t *testing.T) {
wantToolset: server.ToolsetConfigs{
"alloydb-postgres-admin-tools": tools.ToolsetConfig{
Name: "alloydb-postgres-admin-tools",
ToolNames: []string{"alloydb-create-cluster", "alloydb-operations-get", "alloydb-create-instance", "list_clusters", "alloydb-list-instances", "alloydb-list-users", "alloydb-create-user"},
ToolNames: []string{"alloydb-create-cluster", "alloydb-operations-get", "alloydb-create-instance", "list_clusters", "alloydb-list-instances", "list_users", "alloydb-create-user"},
},
},
},

View File

@@ -0,0 +1,38 @@
---
title: "alloydb-list-users"
type: docs
weight: 1
description: >
The "alloydb-list-users" tool lists all database users within an AlloyDB cluster.
aliases:
- /resources/tools/alloydb-list-users
---
## About
The `alloydb-list-users` tool lists all database users within an AlloyDB cluster. It is compatible with [alloydb-admin](../../sources/alloydb-admin.md) source.
The tool takes the following input parameters:
| Parameter | Type | Description | Required |
| :--------- | :----- | :--------------------------------------------------------------------------------------- | :------- |
| `projectId` | string | The GCP project ID to list users for. | Yes |
| `clusterId` | string | The ID of the cluster to list users from. | Yes |
| `locationId` | string | The location of the cluster (e.g., 'us-central1'). | 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:
list_users:
kind: alloydb-list-users
source: alloydb-admin-source
description: Use this tool to list all database users within an AlloyDB cluster
```
## Reference
| **field** | **type** | **required** | **description** |
|-------------|:------------------------------------------:|:------------:|--------------------------------------------------------------------------------------------------|
| kind | string | true | Must be alloydb-list-users. | |
| 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

@@ -152,23 +152,10 @@ tools:
type: string
description: "The ID of the cluster to list instances from. Use '-' to get results for all clusters."
default: "-"
alloydb-list-users:
kind: http
source: alloydb-api-source
method: GET
path: /v1/projects/{{.projectId}}/locations/{{.locationId}}/clusters/{{.clusterId}}/users
list_users:
kind: alloydb-list-users
source: alloydb-admin-source
description: "Lists all database users within a specific AlloyDB cluster."
pathParams:
- name: projectId
type: string
description: "The GCP project ID."
- name: locationId
type: string
description: "The location of the cluster (e.g., 'us-central1')."
default: us-central1
- name: clusterId
type: string
description: "The ID of the cluster to list users from."
alloydb-create-user:
kind: http
source: alloydb-api-source
@@ -224,5 +211,5 @@ toolsets:
- alloydb-create-instance
- list_clusters
- alloydb-list-instances
- alloydb-list-users
- list_users
- alloydb-create-user

View File

@@ -0,0 +1,175 @@
// 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 alloydblistusers
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"
"google.golang.org/api/alloydb/v1"
"google.golang.org/api/option"
)
const kind string = "alloydb-list-users"
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 list-users 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("projectId", "The GCP project ID."),
tools.NewStringParameter("locationId", "The location of the cluster (e.g., 'us-central1')."),
tools.NewStringParameter("clusterId", "The ID of the cluster to list users from."),
}
paramManifest := allParameters.Manifest()
inputSchema := allParameters.McpManifest()
inputSchema.Required = []string{"projectId", "locationId", "clusterId"}
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 list-users tool.
type Tool struct {
Name string `yaml:"name"`
Kind string `yaml:"kind"`
Description string `yaml:"description"`
Source *alloydbadmin.Source
AllParams tools.Parameters `yaml:"allParams"`
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()
projectId, ok := paramsMap["projectId"].(string)
if !ok {
return nil, fmt.Errorf("invalid or missing 'projectId' parameter; expected a string")
}
locationId, ok := paramsMap["locationId"].(string)
if !ok {
return nil, fmt.Errorf("invalid 'locationId' parameter; expected a string")
}
clusterId, ok := paramsMap["clusterId"].(string)
if !ok {
return nil, fmt.Errorf("invalid 'clusterId' parameter; expected a string")
}
// Get an authenticated HTTP client from the source
client, err := t.Source.GetClient(ctx, string(accessToken))
if err != nil {
return nil, fmt.Errorf("error getting authorized client: %w", err)
}
// Create a new AlloyDB service client using the authorized client
alloydbService, err := alloydb.NewService(ctx, option.WithHTTPClient(client))
if err != nil {
return nil, fmt.Errorf("error creating AlloyDB service: %w", err)
}
urlString := fmt.Sprintf("projects/%s/locations/%s/clusters/%s", projectId, locationId, clusterId)
resp, err := alloydbService.Projects.Locations.Clusters.Users.List(urlString).Do()
if err != nil {
return nil, fmt.Errorf("error listing AlloyDB users: %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 alloydblistusers_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"
alloydblistusers "github.com/googleapis/genai-toolbox/internal/tools/alloydb/alloydblistusers"
)
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:
list-my-users:
kind: alloydb-list-users
source: my-alloydb-admin-source
description: some description
`,
want: server.ToolConfigs{
"list-my-users": alloydblistusers.Config{
Name: "list-my-users",
Kind: "alloydb-list-users",
Source: "my-alloydb-admin-source",
Description: "some description",
AuthRequired: []string{},
},
},
},
{
desc: "with auth required",
in: `
tools:
list-my-users-auth:
kind: alloydb-list-users
source: my-alloydb-admin-source
description: some description
authRequired:
- my-google-auth-service
- other-auth-service
`,
want: server.ToolConfigs{
"list-my-users-auth": alloydblistusers.Config{
Name: "list-my-users-auth",
Kind: "alloydb-list-users",
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

@@ -39,6 +39,7 @@ var (
AlloyDBProject = os.Getenv("ALLOYDB_PROJECT")
AlloyDBLocation = os.Getenv("ALLOYDB_REGION")
AlloyDBCluster = os.Getenv("ALLOYDB_CLUSTER")
AlloyDBUser = os.Getenv("ALLOYDB_POSTGRES_USER")
)
func getAlloyDBVars(t *testing.T) map[string]string {
@@ -51,10 +52,14 @@ func getAlloyDBVars(t *testing.T) map[string]string {
if AlloyDBCluster == "" {
t.Fatal("'ALLOYDB_CLUSTER' not set")
}
if AlloyDBUser == "" {
t.Fatal("'ALLOYDB_USER' not set")
}
return map[string]string{
"projectId": AlloyDBProject,
"locationId": AlloyDBLocation,
"clusterId": AlloyDBCluster,
"user": AlloyDBUser,
}
}
@@ -90,6 +95,11 @@ func getAlloyDBToolsConfig() map[string]any {
"source": "alloydb-admin-source",
"description": "Lists all AlloyDB clusters in a given project and location.",
},
"alloydb-list-users": map[string]any{
"kind": "alloydb-list-users",
"source": "alloydb-admin-source",
"description": "Lists all AlloyDB users within a specific cluster.",
},
},
}
}
@@ -121,6 +131,7 @@ func TestAlloyDBToolEndpoints(t *testing.T) {
// Run tool-specific invoke tests
runAlloyDBListClustersTest(t, vars)
runAlloyDBListUsersTest(t, vars)
}
func runAlloyDBToolGetTest(t *testing.T) {
@@ -414,4 +425,118 @@ func runAlloyDBListClustersTest(t *testing.T, vars map[string]string) {
}
})
}
}
}
func runAlloyDBListUsersTest(t *testing.T, vars map[string]string) {
type UsersResponse struct {
Users []struct {
Name string `json:"name"`
} `json:"users"`
}
type ToolResponse struct {
Result string `json:"result"`
}
invokeTcs := []struct {
name string
requestBody io.Reader
wantContains string
wantCount int
wantStatusCode int
}{
{
name: "list users success",
requestBody: bytes.NewBufferString(fmt.Sprintf(`{"projectId": "%s", "locationId": "%s", "clusterId": "%s"}`, vars["projectId"], vars["locationId"], vars["clusterId"])),
wantContains: fmt.Sprintf("projects/%s/locations/%s/clusters/%s/users/%s", vars["projectId"], vars["locationId"], vars["clusterId"], AlloyDBUser),
wantCount: 3, // NOTE: If users are added or removed in the test project, update the number of users here must be updated for this test to pass
wantStatusCode: http.StatusOK,
},
{
name: "list users missing project",
requestBody: bytes.NewBufferString(fmt.Sprintf(`{"locationId": "%s", "clusterId": "%s"}`, vars["locationId"], vars["clusterId"])),
wantStatusCode: http.StatusBadRequest,
},
{
name: "list users missing location",
requestBody: bytes.NewBufferString(fmt.Sprintf(`{"projectId": "%s", "clusterId": "%s"}`, vars["projectId"], vars["clusterId"])),
wantStatusCode: http.StatusBadRequest,
},
{
name: "list users missing cluster",
requestBody: bytes.NewBufferString(fmt.Sprintf(`{"projectId": "%s", "locationId": "%s"}`, vars["projectId"], vars["clusterId"])),
wantStatusCode: http.StatusBadRequest,
},
{
name: "list users non-existent project",
requestBody: bytes.NewBufferString(fmt.Sprintf(`{"projectId": "non-existent-project", "locationId": "%s", "clusterId": "%s"}`, vars["locationId"], vars["clusterId"])),
wantStatusCode: http.StatusInternalServerError,
},
{
name: "list users non-existent location",
requestBody: bytes.NewBufferString(fmt.Sprintf(`{"projectId": "%s", "locationId": "non-existent-location", "clusterId": "%s"}`, vars["projectId"], vars["clusterId"])),
wantStatusCode: http.StatusInternalServerError,
},
{
name: "list users non-existent cluster",
requestBody: bytes.NewBufferString(fmt.Sprintf(`{"projectId": "%s", "locationId": "%s", "clusterId": "non-existent-cluster"}`, vars["projectId"], vars["locationId"])),
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-list-users/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 outer response body: %v", err)
}
var usersData UsersResponse
if err := json.Unmarshal([]byte(body.Result), &usersData); err != nil {
t.Fatalf("error parsing nested result JSON: %v", err)
}
var got []string
for _, user := range usersData.Users {
got = append(got, user.Name)
}
sort.Strings(got)
if len(got) != tc.wantCount {
t.Errorf("user count mismatch:\n got: %v\nwant: %v", len(got), tc.wantCount)
}
found := false
for _, g := range got {
if g == tc.wantContains {
found = true
break
}
}
if !found {
t.Errorf("wantContains not found in response:\n got: %v\nwant: %v", got, tc.wantContains)
}
}
})
}
}