Skip to main content
Glama
matchs

Terraform Cloud MCP Server

by matchs

List Workspaces

list_workspaces

Retrieve all workspaces within a Terraform Cloud organization to manage infrastructure projects and configurations.

Instructions

List all workspaces in a Terraform Cloud organization

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
organizationNoOrganization nameurbanmedia

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
workspacesYes

Implementation Reference

  • Handler function that lists all workspaces in the specified Terraform Cloud organization by calling the tfCloudRequest helper to fetch data from the API, maps it to the output format, and handles errors.
    async ({ organization }) => {
      try {
        const data = await tfCloudRequest(`/organizations/${organization}/workspaces`);
        
        const workspaces = data.data.map((ws: any) => ({
          id: ws.id,
          name: ws.attributes.name,
          locked: ws.attributes.locked,
          executionMode: ws.attributes['execution-mode'],
          currentRunStatus: ws.relationships['current-run']?.data ? 'active' : 'idle'
        }));
    
        const output = { workspaces };
    
        return {
          content: [{ type: 'text', text: JSON.stringify(output, null, 2) }],
          structuredContent: output
        };
      } catch (error) {
        const errorMsg = error instanceof Error ? error.message : String(error);
        return {
          content: [{ type: 'text', text: `Error: ${errorMsg}` }],
          isError: true
        };
      }
    }
  • Input and output schema definitions for the list_workspaces tool using Zod validation.
      title: 'List Workspaces',
      description: 'List all workspaces in a Terraform Cloud organization',
      inputSchema: {
        organization: z.string().default('urbanmedia').describe('Organization name')
      },
      outputSchema: {
        workspaces: z.array(z.object({
          id: z.string(),
          name: z.string(),
          locked: z.boolean(),
          executionMode: z.string(),
          currentRunStatus: z.string().optional()
        }))
      }
    },
  • src/index.ts:120-163 (registration)
    Registration of the list_workspaces tool on the MCP server, including name, schema, and handler function.
      'list_workspaces',
      {
        title: 'List Workspaces',
        description: 'List all workspaces in a Terraform Cloud organization',
        inputSchema: {
          organization: z.string().default('urbanmedia').describe('Organization name')
        },
        outputSchema: {
          workspaces: z.array(z.object({
            id: z.string(),
            name: z.string(),
            locked: z.boolean(),
            executionMode: z.string(),
            currentRunStatus: z.string().optional()
          }))
        }
      },
      async ({ organization }) => {
        try {
          const data = await tfCloudRequest(`/organizations/${organization}/workspaces`);
          
          const workspaces = data.data.map((ws: any) => ({
            id: ws.id,
            name: ws.attributes.name,
            locked: ws.attributes.locked,
            executionMode: ws.attributes['execution-mode'],
            currentRunStatus: ws.relationships['current-run']?.data ? 'active' : 'idle'
          }));
    
          const output = { workspaces };
    
          return {
            content: [{ type: 'text', text: JSON.stringify(output, null, 2) }],
            structuredContent: output
          };
        } catch (error) {
          const errorMsg = error instanceof Error ? error.message : String(error);
          return {
            content: [{ type: 'text', text: `Error: ${errorMsg}` }],
            isError: true
          };
        }
      }
    );
  • Helper function to make authenticated requests to the Terraform Cloud API, used by the list_workspaces handler.
    async function tfCloudRequest(endpoint: string): Promise<any> {
      const token = getTerraformToken();
      const response = await fetch(`${TF_API_BASE}${endpoint}`, {
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/vnd.api+json'
        }
      });
    
      if (!response.ok) {
        throw new Error(`Terraform Cloud API error: ${response.statusText}`);
      }
    
      return response.json();
    }
  • Helper function to retrieve the Terraform Cloud API token from the credentials file, used by tfCloudRequest.
    function getTerraformToken(): string {
      const credentialsPath = join(homedir(), '.terraform.d', 'credentials.tfrc.json');
      try {
        const credentials = JSON.parse(readFileSync(credentialsPath, 'utf-8'));
        return credentials.credentials['app.terraform.io'].token;
      } catch (error) {
        throw new Error('Failed to read Terraform Cloud token from ~/.terraform.d/credentials.tfrc.json');
      }
    }
Behavior2/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. It states it's a listing operation but doesn't mention whether it's paginated, what permissions are required, rate limits, or what the output format looks like. For a read operation with zero annotation coverage, this leaves significant behavioral gaps.

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 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 an output schema (which handles return values) and 100% schema coverage for its single parameter, the description is minimally adequate. However, as a read operation with no annotations, it should ideally provide more behavioral context about permissions, pagination, or limitations to be fully complete.

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 schema description coverage is 100%, so the schema already documents the single parameter 'organization' with its type, default value, and description. The tool description doesn't add any additional meaning or context about this parameter beyond what's in the schema, meeting the baseline 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 ('List all workspaces') and resource ('in a Terraform Cloud organization'), providing a specific verb+resource combination. However, it doesn't differentiate from sibling tools like 'get_workspace_details' which suggests this is a listing operation versus a detailed retrieval, but this distinction isn't explicitly stated in the description itself.

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 like 'get_workspace_details' or other sibling tools. It lacks context about use cases, prerequisites, or exclusions, leaving the agent to infer usage from the tool name and description alone.

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/matchs/tf-cloud-mcp-server'

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