Skip to main content
Glama
krzko

Google Cloud MCP Server

by krzko

Get Project IAM Policy

gcp-iam-get-project-policy

Retrieve the IAM policy for a Google Cloud project to view access controls and permissions. Specify project ID and policy version as needed.

Instructions

Retrieve the IAM policy for a Google Cloud project

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
projectNoProject ID (defaults to current project)
requestedPolicyVersionNoThe policy format version (1, 2, or 3)

Implementation Reference

  • Executes the tool logic: gets the current or specified project ID, fetches the IAM policy using Google Cloud Resource Manager client with specified version, formats it using formatIamPolicy helper, and returns markdown text response. Handles missing policy and errors with user-friendly messages.
      async ({ project, requestedPolicyVersion }) => {
        try {
          const projectId = project || (await getProjectId());
          const resourceManager = getResourceManagerClient();
    
          const [policy] = await resourceManager.getIamPolicy({
            resource: `projects/${projectId}`,
            options: {
              requestedPolicyVersion,
            },
          });
    
          if (!policy) {
            return {
              content: [
                {
                  type: "text",
                  text: `# Project IAM Policy Not Found\n\nNo IAM policy found for project: ${projectId}`,
                },
              ],
            };
          }
    
          const formattedPolicy = formatIamPolicy(policy as IamPolicy);
    
          return {
            content: [
              {
                type: "text",
                text: `# Project IAM Policy\n\nProject: ${projectId}\nPolicy Version: ${requestedPolicyVersion}\n\n${formattedPolicy}`,
              },
            ],
          };
        } catch (error: unknown) {
          const errorMessage =
            error instanceof Error ? error.message : "Unknown error";
          logger.error(`Error getting project IAM policy: ${errorMessage}`);
    
          return {
            content: [
              {
                type: "text",
                text: `# Error Getting Project IAM Policy\n\nFailed to retrieve IAM policy for project "${project || "current"}": ${errorMessage}\n\nPlease ensure:\n- The project ID is correct\n- You have the required permissions (resourcemanager.projects.getIamPolicy)\n- The project exists and is accessible`,
              },
            ],
            isError: true,
          };
        }
      },
    );
  • Input schema definition using Zod validators for optional project ID and policy version (1-3, default 3). Title and description provided for the tool.
    {
      title: "Get Project IAM Policy",
      description: "Retrieve the IAM policy for a Google Cloud project",
      inputSchema: {
        project: z
          .string()
          .optional()
          .describe("Project ID (defaults to current project)"),
        requestedPolicyVersion: z
          .number()
          .min(1)
          .max(3)
          .default(3)
          .describe("The policy format version (1, 2, or 3)"),
      },
    },
  • Registers the tool 'gcp-iam-get-project-policy' on the MCP server within the registerIamTools function, providing schema and handler.
      "gcp-iam-get-project-policy",
      {
        title: "Get Project IAM Policy",
        description: "Retrieve the IAM policy for a Google Cloud project",
        inputSchema: {
          project: z
            .string()
            .optional()
            .describe("Project ID (defaults to current project)"),
          requestedPolicyVersion: z
            .number()
            .min(1)
            .max(3)
            .default(3)
            .describe("The policy format version (1, 2, or 3)"),
        },
      },
      async ({ project, requestedPolicyVersion }) => {
        try {
          const projectId = project || (await getProjectId());
          const resourceManager = getResourceManagerClient();
    
          const [policy] = await resourceManager.getIamPolicy({
            resource: `projects/${projectId}`,
            options: {
              requestedPolicyVersion,
            },
          });
    
          if (!policy) {
            return {
              content: [
                {
                  type: "text",
                  text: `# Project IAM Policy Not Found\n\nNo IAM policy found for project: ${projectId}`,
                },
              ],
            };
          }
    
          const formattedPolicy = formatIamPolicy(policy as IamPolicy);
    
          return {
            content: [
              {
                type: "text",
                text: `# Project IAM Policy\n\nProject: ${projectId}\nPolicy Version: ${requestedPolicyVersion}\n\n${formattedPolicy}`,
              },
            ],
          };
        } catch (error: unknown) {
          const errorMessage =
            error instanceof Error ? error.message : "Unknown error";
          logger.error(`Error getting project IAM policy: ${errorMessage}`);
    
          return {
            content: [
              {
                type: "text",
                text: `# Error Getting Project IAM Policy\n\nFailed to retrieve IAM policy for project "${project || "current"}": ${errorMessage}\n\nPlease ensure:\n- The project ID is correct\n- You have the required permissions (resourcemanager.projects.getIamPolicy)\n- The project exists and is accessible`,
              },
            ],
            isError: true,
          };
        }
      },
    );
  • Provides a singleton instance of the Google Cloud Resource Manager ProjectsClient, used by the handler to call getIamPolicy.
    export function getResourceManagerClient(): ProjectsClient {
      if (!resourceManagerClientInstance) {
        resourceManagerClientInstance = new ProjectsClient({
          projectId: process.env.GOOGLE_CLOUD_PROJECT,
        });
      }
      return resourceManagerClientInstance;
    }
  • Formats the raw IAM policy into a structured markdown string, including version, bindings with members and conditions, and audit configurations.
    export function formatIamPolicy(policy: IamPolicy): string {
      let result = `## IAM Policy\n\n`;
    
      result += `**Version:** ${policy.version || 1}\n`;
      if (policy.etag) result += `**ETag:** ${policy.etag}\n`;
    
      if (policy.bindings && policy.bindings.length > 0) {
        result += `\n**Policy Bindings:**\n\n`;
    
        policy.bindings.forEach((binding, index) => {
          result += `### Binding ${index + 1}: ${binding.role}\n\n`;
          result += `**Members:**\n`;
          binding.members.forEach((member) => {
            result += `- ${member}\n`;
          });
    
          if (binding.condition) {
            result += `\n**Condition:**\n`;
            if (binding.condition.title)
              result += `- Title: ${binding.condition.title}\n`;
            if (binding.condition.description)
              result += `- Description: ${binding.condition.description}\n`;
            result += `- Expression: \`${binding.condition.expression}\`\n`;
          }
          result += "\n";
        });
      }
    
      if (policy.auditConfigs && policy.auditConfigs.length > 0) {
        result += `**Audit Configurations:**\n\n`;
    
        policy.auditConfigs.forEach((config, index) => {
          result += `### Audit Config ${index + 1}: ${config.service}\n\n`;
          config.auditLogConfigs.forEach((logConfig, logIndex) => {
            result += `**Log Config ${logIndex + 1}:**\n`;
            result += `- Log Type: ${logConfig.logType}\n`;
            if (logConfig.exemptedMembers && logConfig.exemptedMembers.length > 0) {
              result += `- Exempted Members: ${logConfig.exemptedMembers.join(", ")}\n`;
            }
            result += "\n";
          });
        });
      }
    
      return result;
    }
Behavior2/5

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

With no annotations provided, the description carries full burden but offers minimal behavioral insight. It states it 'retrieves' the policy, implying a read-only operation, but doesn't disclose critical details like authentication requirements, rate limits, error conditions, or what the output contains (e.g., bindings, version). This leaves gaps for an agent to use it effectively.

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 directly states the tool's purpose without unnecessary words. It's front-loaded with the core action and resource, making it easy to parse quickly, and every part of the sentence contributes essential information.

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

Completeness2/5

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

Given the complexity of IAM policies and the lack of annotations and output schema, the description is incomplete. It doesn't explain the output format (e.g., JSON structure with bindings), potential side effects (e.g., requiring IAM permissions), or usage context, leaving significant gaps for an agent to understand the tool's full behavior and results.

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?

The input schema has 100% description coverage, with clear documentation for both parameters ('project' and 'requestedPolicyVersion'), including defaults and constraints. The description adds no additional parameter semantics beyond what the schema provides, so it meets the baseline score of 3 for high schema coverage.

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 action ('Retrieve') and resource ('IAM policy for a Google Cloud project'), making the purpose unambiguous. However, it doesn't differentiate from sibling tools like 'gcp-iam-test-project-permissions' or 'gcp-iam-analyse-permission-gaps', which also relate to IAM policies but serve different functions.

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?

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention prerequisites (e.g., needing IAM permissions), compare it to siblings like 'gcp-iam-test-project-permissions' for testing permissions, or specify scenarios where retrieving the policy is appropriate (e.g., auditing vs. modification).

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