Skip to main content
Glama

run-gcp-code

Execute TypeScript code using Google Cloud Client Libraries to query and manage GCP resources like Compute Engine, Cloud Storage, and BigQuery across projects and regions.

Instructions

Run GCP code

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
reasoningYesThe reasoning behind the code
codeYesYour job is to answer questions about GCP environment by writing Javascript/TypeScript code using Google Cloud Client Libraries. The code must adhere to a few rules: - Must use promises and async/await - Think step-by-step before writing the code, approach it logically - Must be written in TypeScript using official Google Cloud client libraries - Avoid hardcoded values like project IDs - Code written should be as parallel as possible enabling the fastest and most optimal execution - Code should handle errors gracefully, especially when doing multiple API calls - Each error should be handled and logged with a reason, script should continue to run despite errors - Data returned from GCP APIs must be returned as JSON containing only the minimal amount of data needed to answer the question - All extra data must be filtered out - Code MUST "return" a value: string, number, boolean or JSON object - If code does not return anything, it will be considered as FAILED - Whenever tool/function call fails, retry it 3 times before giving up - When listing resources, ensure pagination is handled correctly - Do not include any comments in the code - Try to write code that returns as few data as possible to answer without any additional processing required Be concise, professional and to the point. Do not give generic advice, always reply with detailed & contextual data sourced from the current GCP environment.
projectIdNoGCP project ID to use
regionNoRegion to use (if not provided, us-central1 is used)

Implementation Reference

  • Main handler logic for the 'run-gcp-code' tool. Parses input, sets up a sandboxed context with GCP clients, wraps and executes the user-provided code using vm.runInContext, and returns the result or error.
    if (name === "run-gcp-code") {
      const { reasoning, code, projectId, region } = RunGCPCodeSchema.parse(args);
      
      if (!selectedProject && !projectId) {
        const projects = await listAvailableProjects();
        return createTextResponse(
          `Please select a project first using the 'select-project' tool! Available projects: ${projects.join(", ")}`
        );
      }
    
      if (projectId) {
        selectedProjectCredentials = await auth.getClient();
        selectedProject = projectId;
        selectedRegion = region || "us-central1";
      }
    
      // Initialize context with better error handling and type safety
      const context = {
        selectedProject,
        selectedRegion,
        compute: new InstancesClient({ projectId: selectedProject || undefined }),
        storage: new Storage({ projectId: selectedProject || undefined }),
        functions: new CloudFunctionsServiceClient({ projectId: selectedProject || undefined }),
        run: new ServicesClient({ projectId: selectedProject || undefined }),
        bigquery: new BigQuery({ projectId: selectedProject || undefined }),
        resourceManager: new ProjectsClient({ projectId: selectedProject || undefined }),
        container: new ClusterManagerClient({ projectId: selectedProject || undefined }),
        logging: new Logging({ projectId: selectedProject || undefined }),
        sql: new SqlInstancesServiceClient({ projectId: selectedProject || undefined }),
        // Add helper functions
        retry: async <T>(fn: () => Promise<T>, retries = 3): Promise<T> => {
          try {
            return await fn();
          } catch (error) {
            if (retries > 0) {
              console.error(`Operation failed, retrying... (${retries} attempts left)`);
              await new Promise(resolve => setTimeout(resolve, 1000));
              return context.retry(fn, retries - 1);
            }
            throw error;
          }
        },
        // Add documentation
        help: () => gcpClientDocs
      };
    
      try {
        const wrappedCode = wrapUserCode(code);
        const wrappedIIFECode = `(async function() { return (async () => { ${wrappedCode} })(); })()`;
        const result = await runInContext(wrappedIIFECode, createContext(context));
    
        return createTextResponse(JSON.stringify(result, null, 2));
      } catch (error: any) {
        console.error('Error executing GCP code:', error);
        return createTextResponse(`Error executing GCP code: ${error.message}\n\nAvailable clients and their usage:\n${gcpClientDocs}`);
      }
  • index.ts:72-97 (registration)
    Tool registration in the listTools response, including name, description, and input schema definition.
    {
      name: "run-gcp-code",
      description: "Run GCP code",
      inputSchema: {
        type: "object",
        properties: {
          reasoning: {
            type: "string",
            description: "The reasoning behind the code",
          },
          code: {
            type: "string",
            description: codePrompt,
          },
          projectId: {
            type: "string",
            description: "GCP project ID to use",
          },
          region: {
            type: "string",
            description: "Region to use (if not provided, us-central1 is used)",
          },
        },
        required: ["reasoning", "code"],
      },
    },
  • Zod schema for validating 'run-gcp-code' tool arguments, used in the handler.
    const RunGCPCodeSchema = z.object({
      reasoning: z.string(),
      code: z.string(),
      projectId: z.string().optional(),
      region: z.string().optional(),
    });
  • Helper function to wrap user code, ensuring it returns a value by modifying the AST with ts-morph if necessary.
    function wrapUserCode(userCode: string) {
      const project = new Project({
        useInMemoryFileSystem: true,
      });
      const sourceFile = project.createSourceFile("userCode.ts", userCode);
      const lastStatement = sourceFile.getStatements().pop();
    
      if (
        lastStatement &&
        lastStatement.getKind() === SyntaxKind.ExpressionStatement
      ) {
        const returnStatement = lastStatement.asKind(SyntaxKind.ExpressionStatement);
        if (returnStatement) {
          const expression = returnStatement.getExpression();
          sourceFile.addStatements(`return ${expression.getText()};`);
          returnStatement.remove();
        }
      }
    
      return sourceFile.getFullText();
    }
Behavior1/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure but offers none. It doesn't indicate whether this is a read-only or mutative operation, what permissions or authentication are required, potential side effects, rate limits, or error handling. The description fails to provide any behavioral context beyond the minimal action implied by the name.

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

Conciseness5/5

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

The description is extremely concise at just three words, with no wasted language or unnecessary elaboration. It's front-loaded with the core action, though this brevity comes at the cost of completeness. Every word earns its place by directly stating the tool's function without redundancy.

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

Completeness1/5

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

Given the complexity of executing code in a GCP environment with no annotations and no output schema, the description is completely inadequate. It doesn't explain what the tool actually does, what happens when code runs, what permissions are needed, what format results return, or any behavioral characteristics. The agent would be left guessing about fundamental aspects of this potentially complex operation.

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%, providing detailed documentation for all parameters including 'reasoning', 'code', 'projectId', and 'region'. The description adds no additional parameter semantics beyond what's already in the schema. According to scoring rules, when schema coverage is high (>80%), the baseline score is 3 even without parameter information in the description.

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

Purpose2/5

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

The description 'Run GCP code' is essentially a tautology that restates the tool name with minimal elaboration. It doesn't specify what kind of code execution this involves (e.g., executing scripts, invoking APIs, or running queries) or what resources it acts upon. While it distinguishes from sibling tools by focusing on code execution rather than information retrieval, it lacks the specific verb+resource clarity needed for higher scores.

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

Usage Guidelines1/5

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

The description provides no guidance on when to use this tool versus alternatives. There's no mention of prerequisites, appropriate contexts, or comparison with sibling tools like 'get-logs' or 'list-projects' that might serve related purposes. The agent must infer usage entirely from the tool name and input schema without any descriptive assistance.

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/RadiumGu/gcp-ops-mcp'

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