Skip to main content
Glama

infracost_cloud_create_guardrail

Create cost guardrails in Infracost Cloud to notify stakeholders or block pull requests when infrastructure cost thresholds are exceeded, enabling proactive cloud cost management.

Instructions

Create cost guardrails in Infracost Cloud that notify stakeholders or block PRs when cost thresholds are exceeded. Requires INFRACOST_SERVICE_TOKEN environment variable.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
orgSlugNoOrganization slug from Infracost Cloud (defaults to INFRACOST_ORG env var)
nameYesName for the guardrail
scopeYesScope configuration
increaseThresholdNoThreshold for cost increases (monthly dollar amount)
increasePercentThresholdNoThreshold for cost increases (percentage)
totalThresholdNoThreshold for total cost (monthly dollar amount)
messageNoCustom message to display when threshold is exceeded
webhookUrlNoWebhook URL to notify when threshold is exceeded
blockPullRequestNoWhether to block PR when threshold is exceeded
commentOnPullRequestNoWhether to comment on PR when threshold is exceeded

Implementation Reference

  • The main handler function for the 'infracost_cloud_create_guardrail' tool. Validates input, transforms scope parameters to API format, constructs the request, calls the API client to create the guardrail, and returns the result.
    async handleCreateGuardrail(args: z.infer<typeof CreateGuardrailSchema>) {
      if (!this.cloudApiClient) {
        throw new Error('INFRACOST_SERVICE_TOKEN is not configured for Infracost Cloud API operations');
      }
    
      const orgSlug = args.orgSlug || this.config.orgSlug;
      if (!orgSlug) {
        throw new Error('Organization slug is required. Provide it via orgSlug parameter or set INFRACOST_ORG environment variable');
      }
    
      const {
        orgSlug: _,
        scope,
        blockPullRequest,
        commentOnPullRequest,
        webhookUrl,
        emailRecipientOrgMemberIds,
        mailingListEmails,
        msTeamsEmails,
        ...rest
      } = args;
    
      let scopeString: string;
      if (scope.type === 'ALL_PROJECTS' || scope.type === 'REPO') {
        scopeString = 'REPO';
      } else {
        scopeString = 'PROJECT';
      }
      const filters: any = {};
    
      if (scope.repositories && scope.repositories.length > 0) {
        filters.repos = { include: scope.repositories };
      }
      if (scope.projects && scope.projects.length > 0) {
        filters.projects = { include: scope.projects };
      }
    
      const apiRequest: any = {
        ...rest,
        scope: scopeString,
        filters: Object.keys(filters).length > 0 ? filters : undefined,
        prComment: commentOnPullRequest,
        blockPr: blockPullRequest,
        webhookUrl, // Schema defaults to empty string if not provided
      };
    
      if (emailRecipientOrgMemberIds) {
        apiRequest.emailRecipientOrgMemberIds = emailRecipientOrgMemberIds;
      }
      if (mailingListEmails) {
        apiRequest.mailingListEmails = mailingListEmails;
      }
      if (msTeamsEmails) {
        apiRequest.msTeamsEmails = msTeamsEmails;
      }
    
      const result = await this.cloudApiClient.createGuardrail(orgSlug, apiRequest);
    
      if (!result.success) {
        throw new Error(result.error || 'Create guardrail request failed');
      }
    
      return {
        content: [
          {
            type: 'text',
            text: result.output || 'Guardrail created successfully',
          },
        ],
      };
    }
  • Zod schema for input validation of the 'infracost_cloud_create_guardrail' tool parameters.
    export const CreateGuardrailSchema = z.object({
      orgSlug: z.string().optional().describe('Organization slug from Infracost Cloud (defaults to INFRACOST_ORG env var)'),
      name: z.string().describe('Name for the guardrail'),
      scope: z
        .object({
          type: z
            .enum(['ALL_PROJECTS', 'REPO', 'PROJECT'])
            .describe('Scope type for the guardrail'),
          repositories: z.array(z.string()).optional().describe('Repository names (for REPO scope)'),
          projects: z.array(z.string()).optional().describe('Project names (for PROJECT scope)'),
        })
        .describe('Scope configuration'),
      increaseThreshold: z
        .number()
        .optional()
        .describe('Threshold for cost increases (monthly dollar amount)'),
      increasePercentThreshold: z
        .number()
        .optional()
        .describe('Threshold for cost increases (percentage)'),
      totalThreshold: z
        .number()
        .optional()
        .describe('Threshold for total cost (monthly dollar amount)'),
      message: z.string().optional().describe('Custom message to display when threshold is exceeded'),
      webhookUrl: z.string().default('').describe('Webhook URL to notify when threshold is exceeded (defaults to empty string if not needed)'),
      blockPullRequest: z.boolean().optional().describe('Whether to block PR when threshold is exceeded'),
      commentOnPullRequest: z
        .boolean()
        .optional()
        .describe('Whether to comment on PR when threshold is exceeded'),
      emailRecipientOrgMemberIds: z
        .array(z.string())
        .optional()
        .describe('Array of organization member IDs to email'),
      mailingListEmails: z
        .array(z.string())
        .optional()
        .describe('Array of email addresses to notify'),
      msTeamsEmails: z
        .array(z.string())
        .optional()
        .describe('Array of MS Teams email addresses to notify'),
    });
  • src/index.ts:764-767 (registration)
    Switch case in CallToolRequest handler that registers and dispatches the tool call to the handler method.
    case 'infracost_cloud_create_guardrail': {
      const validatedArgs = CreateGuardrailSchema.parse(args);
      return await tools.handleCreateGuardrail(validatedArgs);
    }
  • src/index.ts:522-588 (registration)
    Tool registration in ListToolsRequest handler, including name, description, and input schema.
    name: 'infracost_cloud_create_guardrail',
    description:
      'Create cost guardrails in Infracost Cloud that notify stakeholders or block PRs when cost thresholds are exceeded. Requires INFRACOST_SERVICE_TOKEN environment variable.',
    inputSchema: {
      type: 'object',
      properties: {
        orgSlug: {
          type: 'string',
          description: 'Organization slug from Infracost Cloud (defaults to INFRACOST_ORG env var)',
        },
        name: {
          type: 'string',
          description: 'Name for the guardrail',
        },
        scope: {
          type: 'object',
          description: 'Scope configuration',
          properties: {
            type: {
              type: 'string',
              enum: ['ALL_PROJECTS', 'REPO', 'PROJECT'],
              description: 'Scope type for the guardrail',
            },
            repositories: {
              type: 'array',
              items: { type: 'string' },
              description: 'Repository names (for REPO scope)',
            },
            projects: {
              type: 'array',
              items: { type: 'string' },
              description: 'Project names (for PROJECT scope)',
            },
          },
          required: ['type'],
        },
        increaseThreshold: {
          type: 'number',
          description: 'Threshold for cost increases (monthly dollar amount)',
        },
        increasePercentThreshold: {
          type: 'number',
          description: 'Threshold for cost increases (percentage)',
        },
        totalThreshold: {
          type: 'number',
          description: 'Threshold for total cost (monthly dollar amount)',
        },
        message: {
          type: 'string',
          description: 'Custom message to display when threshold is exceeded',
        },
        webhookUrl: {
          type: 'string',
          description: 'Webhook URL to notify when threshold is exceeded',
        },
        blockPullRequest: {
          type: 'boolean',
          description: 'Whether to block PR when threshold is exceeded',
        },
        commentOnPullRequest: {
          type: 'boolean',
          description: 'Whether to comment on PR when threshold is exceeded',
        },
      },
      required: ['name', 'scope'],
    },
  • API client method that performs the actual HTTP POST request to create the guardrail in Infracost Cloud.
    async createGuardrail(
      orgSlug: string,
      request: CreateGuardrailRequest
    ): Promise<CommandResult> {
      try {
        const response = await fetch(`${INFRACOST_CLOUD_API_BASE}/orgs/${orgSlug}/guardrails`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${this.serviceToken}`,
          },
          body: JSON.stringify({ data: { type: 'guardrails', attributes: request } }),
        });
    
        if (!response.ok) {
          const errorText = await response.text();
          return {
            success: false,
            error: `API request failed with status ${response.status}: ${errorText}`,
          };
        }
    
        const data = await response.json();
    
        return {
          success: true,
          output: JSON.stringify(data, null, 2),
          data,
        };
      } catch (error) {
        return {
          success: false,
          error: error instanceof Error ? error.message : 'Unknown error occurred',
        };
      }
    }
Behavior2/5

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

With no annotations provided, the description carries full burden. It mentions the authentication requirement (INFRACOST_SERVICE_TOKEN) but doesn't disclose other behavioral traits like whether this is a mutating operation (implied by 'create'), potential side effects, rate limits, or what happens on success/failure. The description is minimal beyond the basic purpose.

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 appropriately concise with two sentences: one stating the purpose and one stating the authentication requirement. Both sentences earn their place, though it could be slightly more structured by separating purpose from prerequisites.

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?

For a creation tool with 10 parameters, no annotations, and no output schema, the description is insufficient. It doesn't explain what happens after creation, potential errors, or the relationship between parameters (e.g., how thresholds interact). The authentication requirement is noted, but other critical context is missing.

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 schema already documents all 10 parameters thoroughly. The description doesn't add any parameter-specific information beyond what's in the schema descriptions. The baseline of 3 is appropriate when the schema does the heavy lifting.

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

Purpose5/5

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

The description clearly states the verb ('create'), resource ('cost guardrails in Infracost Cloud'), and purpose ('notify stakeholders or block PRs when cost thresholds are exceeded'). It distinguishes from siblings like infracost_cloud_list_guardrails (list) and infracost_cloud_update_guardrail (update) by specifying creation.

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 when setting up cost monitoring/control mechanisms, but doesn't explicitly state when to use this tool versus alternatives like infracost_cloud_update_guardrail or infracost_cloud_get_guardrail. It mentions the INFRACOST_SERVICE_TOKEN requirement, which is a prerequisite rather than usage guidance.

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/phildougherty/infracost_mcp'

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