Skip to main content
Glama

gcp_sql_query

Read-onlyIdempotent

Execute read-only SQL queries on Google Cloud SQL databases to retrieve data for analysis or reporting purposes.

Instructions

Cloud SQL 쿼리|DB 조회|sql query - Cloud SQL에서 읽기 전용 쿼리를 실행합니다

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
instanceYesCloud SQL 인스턴스 이름
databaseYes데이터베이스 이름
queryYesSELECT 쿼리 (읽기 전용만 허용)
project_idNoGCP 프로젝트 ID (기본: 현재 설정된 프로젝트)
formatNo출력 형식 (기본: text)text

Implementation Reference

  • The async handler function that implements the core logic for 'gcp_sql_query'. It performs security checks (SELECT-only, no dangerous keywords, adds LIMIT), prepares a gcloud sql connect command, and returns formatted results or errors.
    export async function gcpSqlQuery(args: GcpSqlQueryArgs) {
      try {
        const projectId = await getProjectId(args.project_id);
    
        // Security check: only allow SELECT queries
        const normalizedQuery = args.query.trim().toLowerCase();
        if (!normalizedQuery.startsWith('select')) {
          return {
            content: [
              {
                type: 'text',
                text: '❌ 보안 제한: SELECT 쿼리만 허용됩니다.\n\nINSERT, UPDATE, DELETE, DROP 등의 쿼리는 실행할 수 없습니다.',
              },
            ],
            isError: true,
          };
        }
    
        // Check for dangerous keywords
        const dangerousKeywords = ['insert', 'update', 'delete', 'drop', 'truncate', 'alter', 'create', 'grant', 'revoke'];
        for (const keyword of dangerousKeywords) {
          if (normalizedQuery.includes(keyword)) {
            return {
              content: [
                {
                  type: 'text',
                  text: `❌ 보안 제한: "${keyword.toUpperCase()}" 키워드가 포함된 쿼리는 실행할 수 없습니다.`,
                },
              ],
              isError: true,
            };
          }
        }
    
        // Add LIMIT if not present (safety measure)
        let safeQuery = args.query.trim();
        if (!normalizedQuery.includes('limit')) {
          safeQuery += ' LIMIT 100';
        }
    
        // Note: Cloud SQL direct query requires Cloud SQL Proxy or gcloud sql connect
        // This implementation uses gcloud sql connect with --quiet flag
        // For production, consider using Cloud SQL Admin API
    
        const command = `sql connect ${args.instance} --database=${args.database} --project=${projectId} --quiet <<< "${safeQuery.replace(/"/g, '\\"')}"`;
    
        // This is a simplified implementation
        // Real implementation would need proper SQL connection handling
        return {
          content: [
            {
              type: 'text',
              text: `⚠️ Cloud SQL 직접 연결 기능\n\n현재 구현에서는 Cloud SQL Proxy 또는 직접 연결이 필요합니다.\n\n실행하려던 쿼리:\n${safeQuery}\n\n대안:\n1. Cloud SQL Studio 사용 (GCP Console)\n2. Cloud SQL Proxy 설정 후 로컬에서 연결\n3. gcloud sql connect ${args.instance} --database=${args.database} 명령어 직접 실행`,
            },
          ],
        };
      } catch (error: any) {
        return {
          content: [
            {
              type: 'text',
              text: formatError(error),
            },
          ],
          isError: true,
        };
      }
    }
  • The tool schema definition, including name, description, annotations, and detailed inputSchema with properties for instance, database, query, optional project_id and format.
    export const gcpSqlQueryDefinition = {
      name: 'gcp_sql_query',
      description: 'Cloud SQL 쿼리|DB 조회|sql query - Cloud SQL에서 읽기 전용 쿼리를 실행합니다',
      annotations: {
        title: 'Cloud SQL 쿼리 실행',
        readOnlyHint: true,
        destructiveHint: false,
        idempotentHint: true,
        openWorldHint: true,
      },
      inputSchema: {
        type: 'object' as const,
        properties: {
          instance: {
            type: 'string',
            description: 'Cloud SQL 인스턴스 이름',
          },
          database: {
            type: 'string',
            description: '데이터베이스 이름',
          },
          query: {
            type: 'string',
            description: 'SELECT 쿼리 (읽기 전용만 허용)',
          },
          project_id: {
            type: 'string',
            description: 'GCP 프로젝트 ID (기본: 현재 설정된 프로젝트)',
          },
          format: {
            type: 'string',
            enum: ['text', 'json'],
            description: '출력 형식 (기본: text)',
            default: 'text',
          },
        },
        required: ['instance', 'database', 'query'],
      },
    };
  • src/index.ts:77-89 (registration)
    Registration of all tools including gcpSqlQueryDefinition in the tools array used by ListToolsRequestSchema handler.
    const tools = [
      gcpSetupDefinition,
      gcpLogsReadDefinition,
      gcpRunStatusDefinition,
      gcpRunLogsDefinition,
      gcpSqlQueryDefinition,
      gcpSqlProxyDefinition,
      gcpStorageListDefinition,
      gcpSecretListDefinition,
      gcpAuthStatusDefinition,
      gcpServicesListDefinition,
      gcpBillingInfoDefinition,
    ];
  • src/index.ts:221-222 (registration)
    Dispatch/execution registration in the CallToolRequestSchema switch statement, mapping 'gcp_sql_query' to the gcpSqlQuery handler.
    case 'gcp_sql_query':
      return await gcpSqlQuery(args as any) as CallToolResult;
  • TypeScript interface defining the arguments for the gcpSqlQuery handler, matching the inputSchema.
    interface GcpSqlQueryArgs {
      instance: string;
      database: string;
      query: string;
      project_id?: string;
      format?: 'text' | 'json';
    }
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Annotations already provide key behavioral hints (readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true). The description adds value by reinforcing the read-only nature ('읽기 전용') and specifying it's for Cloud SQL queries, which aligns with annotations. It doesn't contradict annotations and provides additional context about the tool's scope, though it could mention more about rate limits or authentication needs.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is concise and front-loaded, stating the core purpose in a single sentence with no wasted words. The use of pipe-separated terms ('Cloud SQL 쿼리|DB 조회|sql query') adds redundancy but doesn't significantly detract from clarity. It's appropriately sized for the tool's complexity.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's moderate complexity (5 parameters, 3 required), rich annotations (covering safety and idempotency), and 100% schema coverage, the description is mostly complete. It clarifies the read-only query execution, which is crucial. However, without an output schema, it could benefit from mentioning the return type (e.g., query results in text or JSON format), though the format parameter hints at this.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the input schema fully documents all 5 parameters (instance, database, query, project_id, format) with descriptions and defaults. The description doesn't add any parameter-specific semantics beyond what's in the schema, such as query syntax examples or format details. Baseline 3 is appropriate as the schema handles the heavy lifting.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: 'Cloud SQL에서 읽기 전용 쿼리를 실행합니다' (execute read-only queries in Cloud SQL). It specifies the verb (execute queries) and resource (Cloud SQL), and the '읽기 전용' (read-only) qualifier helps distinguish it from potential write operations. However, it doesn't explicitly differentiate from sibling tools like gcp_sql_proxy, which might handle different SQL operations.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage by specifying '읽기 전용 쿼리' (read-only queries), suggesting it's for SELECT operations only. However, it doesn't provide explicit guidance on when to use this tool versus alternatives (e.g., gcp_sql_proxy for other SQL tasks or gcp_logs_read for logging data). The context is clear but lacks sibling differentiation or exclusion criteria.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/su-record/hi-gcloud'

If you have feedback or need assistance with the MCP directory API, please join our Discord server