Skip to content
Merged
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
1 change: 1 addition & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ import (
_ "github.com/googleapis/genai-toolbox/internal/tools/postgres/postgreslistavailableextensions"
_ "github.com/googleapis/genai-toolbox/internal/tools/postgres/postgreslistinstalledextensions"
_ "github.com/googleapis/genai-toolbox/internal/tools/postgres/postgreslisttables"
_ "github.com/googleapis/genai-toolbox/internal/tools/postgres/postgreslistviews"
_ "github.com/googleapis/genai-toolbox/internal/tools/postgres/postgressql"
_ "github.com/googleapis/genai-toolbox/internal/tools/redis"
_ "github.com/googleapis/genai-toolbox/internal/tools/serverlessspark/serverlesssparkgetbatch"
Expand Down
6 changes: 3 additions & 3 deletions cmd/root_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1397,7 +1397,7 @@ func TestPrebuiltTools(t *testing.T) {
wantToolset: server.ToolsetConfigs{
"alloydb_postgres_database_tools": tools.ToolsetConfig{
Name: "alloydb_postgres_database_tools",
ToolNames: []string{"execute_sql", "list_tables", "list_active_queries", "list_available_extensions", "list_installed_extensions", "list_autovacuum_configurations", "list_memory_configurations", "list_top_bloated_tables", "list_replication_slots", "list_invalid_indexes", "get_query_plan"},
ToolNames: []string{"execute_sql", "list_tables", "list_active_queries", "list_available_extensions", "list_installed_extensions", "list_autovacuum_configurations", "list_memory_configurations", "list_top_bloated_tables", "list_replication_slots", "list_invalid_indexes", "get_query_plan", "list_views"},
},
},
},
Expand Down Expand Up @@ -1427,7 +1427,7 @@ func TestPrebuiltTools(t *testing.T) {
wantToolset: server.ToolsetConfigs{
"cloud_sql_postgres_database_tools": tools.ToolsetConfig{
Name: "cloud_sql_postgres_database_tools",
ToolNames: []string{"execute_sql", "list_tables", "list_active_queries", "list_available_extensions", "list_installed_extensions", "list_autovacuum_configurations", "list_memory_configurations", "list_top_bloated_tables", "list_replication_slots", "list_invalid_indexes", "get_query_plan"},
ToolNames: []string{"execute_sql", "list_tables", "list_active_queries", "list_available_extensions", "list_installed_extensions", "list_autovacuum_configurations", "list_memory_configurations", "list_top_bloated_tables", "list_replication_slots", "list_invalid_indexes", "get_query_plan", "list_views"},
},
},
},
Expand Down Expand Up @@ -1527,7 +1527,7 @@ func TestPrebuiltTools(t *testing.T) {
wantToolset: server.ToolsetConfigs{
"postgres_database_tools": tools.ToolsetConfig{
Name: "postgres_database_tools",
ToolNames: []string{"execute_sql", "list_tables", "list_active_queries", "list_available_extensions", "list_installed_extensions", "list_autovacuum_configurations", "list_memory_configurations", "list_top_bloated_tables", "list_replication_slots", "list_invalid_indexes", "get_query_plan"},
ToolNames: []string{"execute_sql", "list_tables", "list_active_queries", "list_available_extensions", "list_installed_extensions", "list_autovacuum_configurations", "list_memory_configurations", "list_top_bloated_tables", "list_replication_slots", "list_invalid_indexes", "get_query_plan", "list_views"},
},
},
},
Expand Down
6 changes: 6 additions & 0 deletions docs/en/reference/prebuilt-tools.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ details on how to connect your AI tools (IDEs) to databases via Toolbox and MCP.
* `list_replication_slots`: Lists replication slots in the database.
* `list_invalid_indexes`: Lists invalid indexes in the database.
* `get_query_plan`: Generate the execution plan of a statement.
* `list_views`: Lists views in the database from pg_views with a default
limit of 50 rows. Returns schemaname, viewname and the ownername.

## AlloyDB Postgres Admin

Expand Down Expand Up @@ -210,6 +212,8 @@ details on how to connect your AI tools (IDEs) to databases via Toolbox and MCP.
* `list_replication_slots`: Lists replication slots in the database.
* `list_invalid_indexes`: Lists invalid indexes in the database.
* `get_query_plan`: Generate the execution plan of a statement.
* `list_views`: Lists views in the database from pg_views with a default
limit of 50 rows. Returns schemaname, viewname and the ownername.

## Cloud SQL for PostgreSQL Observability

Expand Down Expand Up @@ -492,6 +496,8 @@ details on how to connect your AI tools (IDEs) to databases via Toolbox and MCP.
* `list_replication_slots`: Lists replication slots in the database.
* `list_invalid_indexes`: Lists invalid indexes in the database.
* `get_query_plan`: Generate the execution plan of a statement.
* `list_views`: Lists views in the database from pg_views with a default
limit of 50 rows. Returns schemaname, viewname and the ownername.

## Google Cloud Serverless for Apache Spark

Expand Down
3 changes: 3 additions & 0 deletions docs/en/resources/sources/alloydb-pg.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@ cluster][alloydb-free-trial].
- [`postgres-list-installed-extensions`](../tools/postgres/postgres-list-installed-extensions.md)
List installed extensions in a PostgreSQL database.

- [`postgres-list-views`](../tools/postgres/postgres-list-views.md)
List views in an AlloyDB for PostgreSQL database.

### Pre-built Configurations

- [AlloyDB using MCP](https://googleapis.github.io/genai-toolbox/how-to/connect-ide/alloydb_pg_mcp/)
Expand Down
3 changes: 3 additions & 0 deletions docs/en/resources/sources/cloud-sql-pg.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ to a database by following these instructions][csql-pg-quickstart].
- [`postgres-list-installed-extensions`](../tools/postgres/postgres-list-installed-extensions.md)
List installed extensions in a PostgreSQL database.

- [`postgres-list-views`](../tools/postgres/postgres-list-views.md)
List views in a PostgreSQL database.

### Pre-built Configurations

- [Cloud SQL for Postgres using
Expand Down
3 changes: 3 additions & 0 deletions docs/en/resources/sources/postgres.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ reputation for reliability, feature robustness, and performance.
- [`postgres-list-installed-extensions`](../tools/postgres/postgres-list-installed-extensions.md)
List installed extensions in a PostgreSQL database.

- [`postgres-list-views`](../tools/postgres/postgres-list-views.md)
List views in a PostgreSQL database.

### Pre-built Configurations

- [PostgreSQL using MCP](https://googleapis.github.io/genai-toolbox/how-to/connect-ide/postgres_mcp/)
Expand Down
40 changes: 40 additions & 0 deletions docs/en/resources/tools/postgres/postgres-list-views.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
---
title: "postgres-list-views"
type: docs
weight: 1
description: >
The "postgres-list-views" tool lists views in a Postgres database, with a default limit of 50 rows.
aliases:
- /resources/tools/postgres-list-views
---

## About

The `postgres-list-views` tool retrieves a list of top N (default 50) views from a Postgres database, excluding those in system schemas (`pg_catalog`, `information_schema`). It's compatible with any of the following sources:

- [alloydb-postgres](../../sources/alloydb-pg.md)
- [cloud-sql-postgres](../../sources/cloud-sql-pg.md)
- [postgres](../../sources/postgres.md)

`postgres-list-views` lists detailed view information (schemaname, viewname, ownername) as JSON for views in a database. The tool takes the following input parameters:

- `viewname` (optional): A string pattern to filter view names. The search uses SQL
LIKE operator to filter the views. Default: `""`
- `limit` (optional): The maximum number of rows to return. Default: `50`.

## Example

```yaml
tools:
list_views:
kind: postgres-list-views
source: cloudsql-pg-source
```
## Reference
| **field** | **type** | **required** | **description** |
|-------------|:--------:|:-------------:|------------------------------------------------------|
| kind | string | true | Must be "postgres-list-views". |
| source | string | true | Name of the source the SQL should execute on. |
| description | string | false | Description of the tool that is passed to the agent. |
4 changes: 4 additions & 0 deletions internal/prebuiltconfigs/tools/alloydb-postgres.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,9 @@ tools:
description: "The SQL statement for which you want to generate plan (omit the EXPLAIN keyword)."
required: true

list_views:
kind: postgres-list-views
source: alloydb-pg-source
toolsets:
alloydb_postgres_database_tools:
- execute_sql
Expand All @@ -169,3 +172,4 @@ toolsets:
- list_replication_slots
- list_invalid_indexes
- get_query_plan
- list_views
5 changes: 5 additions & 0 deletions internal/prebuiltconfigs/tools/cloud-sql-postgres.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,10 @@ tools:
description: "The SQL statement for which you want to generate plan (omit the EXPLAIN keyword)."
required: true

list_views:
kind: postgres-list-views
source: cloudsql-pg-source

toolsets:
cloud_sql_postgres_database_tools:
- execute_sql
Expand All @@ -168,3 +172,4 @@ toolsets:
- list_replication_slots
- list_invalid_indexes
- get_query_plan
- list_views
5 changes: 5 additions & 0 deletions internal/prebuiltconfigs/tools/postgres.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,10 @@ tools:
description: "The SQL statement for which you want to generate plan (omit the EXPLAIN keyword)."
required: true

list_views:
kind: postgres-list-views
source: postgresql-source

toolsets:
postgres_database_tools:
- execute_sql
Expand All @@ -167,3 +171,4 @@ toolsets:
- list_replication_slots
- list_invalid_indexes
- get_query_plan
- list_views
186 changes: 186 additions & 0 deletions internal/tools/postgres/postgreslistviews/postgreslistviews.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
// 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 postgreslistviews

import (
"context"
"fmt"

yaml "github.com/goccy/go-yaml"
"github.com/googleapis/genai-toolbox/internal/sources"
"github.com/googleapis/genai-toolbox/internal/sources/alloydbpg"
"github.com/googleapis/genai-toolbox/internal/sources/cloudsqlpg"
"github.com/googleapis/genai-toolbox/internal/sources/postgres"
"github.com/googleapis/genai-toolbox/internal/tools"
"github.com/jackc/pgx/v5/pgxpool"
)

const kind string = "postgres-list-views"

const listViewsStatement = `
SELECT schemaname, viewname, viewowner
FROM pg_views
WHERE
schemaname NOT IN ('pg_catalog', 'information_schema')
AND ($1::text IS NULL OR viewname LIKE '%' || $1::text || '%')
ORDER BY viewname
LIMIT COALESCE($2::int, 50);
`

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
}

type compatibleSource interface {
PostgresPool() *pgxpool.Pool
}

// validate compatible sources are still compatible
var _ compatibleSource = &alloydbpg.Source{}
var _ compatibleSource = &cloudsqlpg.Source{}
var _ compatibleSource = &postgres.Source{}

var compatibleSources = [...]string{alloydbpg.SourceKind, cloudsqlpg.SourceKind, postgres.SourceKind}

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"`
AuthRequired []string `yaml:"authRequired"`
}

// validate interface
var _ tools.ToolConfig = Config{}

func (cfg Config) ToolConfigKind() string {
return kind
}

func (cfg Config) Initialize(srcs map[string]sources.Source) (tools.Tool, error) {
// verify source exists
rawS, ok := srcs[cfg.Source]
if !ok {
return nil, fmt.Errorf("no source named %q configured", cfg.Source)
}

// verify the source is compatible
s, ok := rawS.(compatibleSource)
if !ok {
return nil, fmt.Errorf("invalid source for %q tool: source kind must be one of %q", kind, compatibleSources)
}

allParameters := tools.Parameters{
tools.NewStringParameterWithDefault("viewname", "", "Optional: A specific view name to search for."),
tools.NewIntParameterWithDefault("limit", 50, "Optional: The maximum number of rows to return."),
}
paramManifest := allParameters.Manifest()
description := cfg.Description
if description == "" {
description = "Lists views in the database from pg_views with a default limit of 50 rows. Returns schemaname, viewname and the ownername."
}
mcpManifest := tools.GetMcpManifest(cfg.Name, description, cfg.AuthRequired, allParameters)

// finish tool setup
return Tool{
name: cfg.Name,
kind: kind,
authRequired: cfg.AuthRequired,
allParams: allParameters,
pool: s.PostgresPool(),
manifest: tools.Manifest{
Description: cfg.Description,
Parameters: paramManifest,
AuthRequired: cfg.AuthRequired,
},
mcpManifest: mcpManifest,
}, nil
}

// validate interface
var _ tools.Tool = Tool{}

type Tool struct {
name string `yaml:"name"`
kind string `yaml:"kind"`
authRequired []string `yaml:"authRequired"`
allParams tools.Parameters `yaml:"allParams"`
pool *pgxpool.Pool
manifest tools.Manifest
mcpManifest tools.McpManifest
}

func (t Tool) Invoke(ctx context.Context, params tools.ParamValues, accessToken tools.AccessToken) (any, error) {
paramsMap := params.AsMap()

newParams, err := tools.GetParams(t.allParams, paramsMap)
if err != nil {
return nil, fmt.Errorf("unable to extract standard params %w", err)
}
sliceParams := newParams.AsSlice()

results, err := t.pool.Query(ctx, listViewsStatement, sliceParams...)
if err != nil {
return nil, fmt.Errorf("unable to execute query: %w", err)
}
defer results.Close()

fields := results.FieldDescriptions()
var out []map[string]any

for results.Next() {
values, err := results.Values()
if err != nil {
return nil, fmt.Errorf("unable to parse row: %w", err)
}
rowMap := make(map[string]any)
for i, field := range fields {
rowMap[string(field.Name)] = values[i]
}
out = append(out, rowMap)
}

return out, nil
}

func (t Tool) ParseParams(data map[string]any, claims map[string]map[string]any) (tools.ParamValues, error) {
return tools.ParseParams(t.allParams, data, claims)
}

func (t Tool) Manifest() tools.Manifest {
return t.manifest
}

func (t Tool) McpManifest() tools.McpManifest {
return t.mcpManifest
}

func (t Tool) Authorized(verifiedAuthServices []string) bool {
return tools.IsAuthorized(t.authRequired, verifiedAuthServices)
}

func (t Tool) RequiresClientAuthorization() bool {
return false
}
Loading
Loading