Skip to main content
Glama
krzko

Google Cloud MCP Server

by krzko

Get Project ID

gcp-utils-get-project-id

Retrieve your current Google Cloud project ID and view recent project history for managing cloud resources and configurations.

Instructions

Get the current Google Cloud project ID and recent project history

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The core handler function that executes the tool logic: retrieves current project ID from state or auth, fetches recent projects, formats as markdown, handles errors.
    async () => {
      try {
        // Get the current project ID from the state manager first
        let projectId = stateManager.getCurrentProjectId();
    
        // If not available in state manager, try to get it from auth
        if (!projectId) {
          projectId = await getProjectId();
        }
    
        const recentProjectIds = await getRecentProjectIds();
    
        let markdown = `# Current Google Cloud Project\n\nCurrent project ID: \`${projectId}\`\n\n`;
    
        if (recentProjectIds.length > 0) {
          markdown += "## Recently Used Projects\n\n";
          for (const id of recentProjectIds) {
            markdown += `- \`${id}\`${id === projectId ? " (current)" : ""}\n`;
          }
        }
    
        return {
          content: [
            {
              type: "text",
              text: markdown,
            },
          ],
        };
      } catch (error: any) {
        logger.error(
          `Error in get-project-id tool: ${error instanceof Error ? error.message : String(error)}`,
        );
        return {
          content: [
            {
              type: "text",
              text: `# Error Getting Project ID\n\nFailed to get project ID: ${error.message}`,
            },
          ],
        };
      }
    },
  • The server.registerTool call that registers the 'gcp-utils-get-project-id' tool with schema and inline handler.
    server.registerTool(
      "gcp-utils-get-project-id",
      {
        title: "Get Project ID",
        description:
          "Get the current Google Cloud project ID and recent project history",
        inputSchema: {},
      },
      async () => {
        try {
          // Get the current project ID from the state manager first
          let projectId = stateManager.getCurrentProjectId();
    
          // If not available in state manager, try to get it from auth
          if (!projectId) {
            projectId = await getProjectId();
          }
    
          const recentProjectIds = await getRecentProjectIds();
    
          let markdown = `# Current Google Cloud Project\n\nCurrent project ID: \`${projectId}\`\n\n`;
    
          if (recentProjectIds.length > 0) {
            markdown += "## Recently Used Projects\n\n";
            for (const id of recentProjectIds) {
              markdown += `- \`${id}\`${id === projectId ? " (current)" : ""}\n`;
            }
          }
    
          return {
            content: [
              {
                type: "text",
                text: markdown,
              },
            ],
          };
        } catch (error: any) {
          logger.error(
            `Error in get-project-id tool: ${error instanceof Error ? error.message : String(error)}`,
          );
          return {
            content: [
              {
                type: "text",
                text: `# Error Getting Project ID\n\nFailed to get project ID: ${error.message}`,
              },
            ],
          };
        }
      },
    );
  • The input schema (empty), title, and description for the tool.
    {
      title: "Get Project ID",
      description:
        "Get the current Google Cloud project ID and recent project history",
      inputSchema: {},
    },
  • Key helper function called by the handler to fallback-retrieve the project ID from state, env, credentials, config, or GoogleAuth client.
    export async function getProjectId(requireAuth = true): Promise<string> {
      try {
        // First check the state manager (fastest and most reliable method)
        const stateProjectId = stateManager.getCurrentProjectId();
        if (stateProjectId) {
          logger.debug(`Using project ID from state manager: ${stateProjectId}`);
          return stateProjectId;
        }
    
        // Next check environment variable
        if (process.env.GOOGLE_CLOUD_PROJECT) {
          logger.debug(
            `Using project ID from environment: ${process.env.GOOGLE_CLOUD_PROJECT}`,
          );
          // Store in state manager for future use
          await stateManager.setCurrentProjectId(process.env.GOOGLE_CLOUD_PROJECT);
          return process.env.GOOGLE_CLOUD_PROJECT;
        }
    
        // Check if we have credentials file and try to extract project ID from it
        if (process.env.GOOGLE_APPLICATION_CREDENTIALS) {
          try {
            const credentialsPath = process.env.GOOGLE_APPLICATION_CREDENTIALS;
            logger.debug(
              `Attempting to read project ID from credentials file: ${credentialsPath}`,
            );
    
            if (fs.existsSync(credentialsPath)) {
              const credentialsContent = fs.readFileSync(credentialsPath, "utf8");
              const credentials = JSON.parse(credentialsContent);
    
              if (credentials.project_id) {
                logger.debug(
                  `Found project ID in credentials file: ${credentials.project_id}`,
                );
                // Store in state manager for future use
                await stateManager.setCurrentProjectId(credentials.project_id);
                return credentials.project_id;
              }
            }
          } catch (fileError) {
            logger.warn(
              `Error reading credentials file: ${fileError instanceof Error ? fileError.message : String(fileError)}`,
            );
            // Continue to next method
          }
        }
    
        // Next check if we have a configured default project ID
        try {
          await configManager.initialize();
          const configuredProjectId = configManager.getDefaultProjectId();
          if (configuredProjectId) {
            logger.debug(`Using project ID from config: ${configuredProjectId}`);
            // Store in state manager for future use
            await stateManager.setCurrentProjectId(configuredProjectId);
            return configuredProjectId;
          }
        } catch (configError) {
          logger.warn(
            `Config error: ${configError instanceof Error ? configError.message : String(configError)}`,
          );
          // Continue to next method
        }
    
        // Fall back to getting it from auth client
        try {
          logger.debug("Attempting to get project ID from auth client...");
          const auth = await initGoogleAuth(requireAuth);
          if (!auth) {
            logger.warn("Authentication client not available");
            if (requireAuth) {
              throw new Error(
                "Google Cloud authentication not available. Please configure authentication to access project ID.",
              );
            }
            return "unknown-project";
          }
    
          logger.debug("Auth client available, requesting project ID...");
          const projectId = await auth.getProjectId();
    
          if (!projectId) {
            logger.warn("Auth client returned empty project ID");
            if (requireAuth) {
              throw new Error(
                "Could not determine Google Cloud project ID. Please set GOOGLE_CLOUD_PROJECT environment variable or use the set-project-id tool.",
              );
            }
            return "unknown-project";
          }
    
          logger.debug(`Got project ID from auth client: ${projectId}`);
    
          // Store in state manager for future use
          await stateManager.setCurrentProjectId(projectId);
    
          return projectId;
        } catch (authError) {
          logger.warn(
            `Auth error while getting project ID: ${authError instanceof Error ? authError.message : String(authError)}`,
          );
          if (requireAuth) {
            throw authError;
          }
          return "unknown-project";
        }
      } catch (error) {
        logger.error(
          `Project ID error: ${error instanceof Error ? error.message : String(error)}`,
        );
        if (requireAuth) {
          throw error;
        }
        return "unknown-project";
      }
    }
  • State manager method to get the current project ID from persisted state.
     * Get the current project ID
     *
     * @returns The current project ID or null if not set
     */
    getCurrentProjectId(): string | null {
      return this.state.currentProjectId;
    }
Behavior2/5

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

No annotations are provided, so the description carries full burden. It mentions retrieving both 'current project ID' and 'recent project history', which adds some behavioral context, but doesn't disclose authentication requirements, rate limits, format of the history, or what 'recent' means. For a tool with zero annotation coverage, this is insufficient.

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 a single, efficient sentence that clearly states the tool's purpose without any wasted words. It's appropriately sized and front-loaded with the core functionality.

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

Completeness3/5

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

Given the tool has no parameters, no annotations, and no output schema, the description provides basic purpose but lacks important context about authentication, rate limits, format of returned data, or how 'recent project history' is defined. It's minimally adequate but has clear gaps.

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

Parameters4/5

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

The tool has 0 parameters with 100% schema description coverage, so no parameter documentation is needed. The description appropriately doesn't discuss parameters, earning a baseline score of 4 for this dimension.

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: 'Get the current Google Cloud project ID and recent project history'. It specifies the verb ('Get') and resource ('Google Cloud project ID'), but doesn't explicitly differentiate from its sibling 'gcp-utils-set-project-id' beyond the obvious get/set distinction.

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

Usage Guidelines2/5

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

No guidance is provided about when to use this tool versus alternatives. The description doesn't mention prerequisites, context, or relationships with sibling tools like 'gcp-billing-get-project-info' or 'gcp-utils-set-project-id'.

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/krzko/google-cloud-mcp'

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