Skip to main content
Glama
AgentWong
by AgentWong

add_terraform_resource

Store Terraform resource definitions with schema and version details for persistent memory in IaC workflows.

Instructions

Add a new Terraform resource definition with its schema and version information

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
provider_idNoProvider ID
nameYesResource name
resource_typeYesResource type
schemaYesResource schema
versionYesResource version
doc_urlYesDocumentation URL

Implementation Reference

  • MCP tool handler function that validates arguments, parses JSON schema, calls the database add_terraform_resource function, and returns success or error content.
    async def handle_add_terraform_resource(db: Any, arguments: Dict[str, Any], operation_id: str) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]:
        """Handle add_terraform_resource tool."""
        # Validate required arguments
        required_args = ["provider", "name", "resource_type", "schema", "version", "doc_url"]
        missing_args = [arg for arg in required_args if arg not in arguments]
        if missing_args:
            error_msg = f"Missing required arguments for add_terraform_resource: {', '.join(missing_args)}"
            logger.error(error_msg, extra={"operation_id": operation_id})
            return [types.TextContent(
                type="text",
                text=error_msg
            )]
    
        try:
            # Validate schema is valid JSON
            try:
                import json
                json.loads(arguments["schema"])
            except json.JSONDecodeError:
                error_msg = "Invalid schema format. Schema must be valid JSON."
                logger.error(error_msg, extra={"operation_id": operation_id})
                return [types.TextContent(type="text", text=error_msg)]
    
            # Add resource
            logger.info(
                "Adding Terraform resource",
                extra={
                    "provider": arguments["provider"],
                    "resource_name": arguments["name"],
                    "operation_id": operation_id,
                },
            )
    
            resource_id = add_terraform_resource(
                db,
                arguments["provider"],
                arguments["name"],
                arguments["resource_type"],
                arguments["schema"],
                arguments["version"],
                arguments["doc_url"],
            )
    
            return [types.TextContent(
                type="text",
                text=f"Added resource {arguments['name']} with ID: {resource_id}"
            )]
    
        except Exception as e:
            error_msg = f"Failed to add resource: {str(e)}"
            logger.error(error_msg, extra={"operation_id": operation_id})
            return [types.TextContent(type="text", text=error_msg)]
  • Registration of the add_terraform_resource handler in the terraform_tool_handlers dictionary used for MCP tool dispatching.
    terraform_tool_handlers = {
        "get_terraform_provider_info": handle_get_terraform_provider_info,
        "list_provider_resources": handle_list_provider_resources,
        "get_terraform_resource_info": handle_get_terraform_resource_info,
        "add_terraform_provider": handle_add_terraform_provider,
        "add_terraform_resource": handle_add_terraform_resource,
        "update_provider_version": handle_update_provider_version,
    }
  • JSON schema defining the input parameters and validation rules for the add_terraform_resource tool.
    "add_terraform_resource": {
        "type": "object",
        "description": "Add a new Terraform resource definition with its schema and version information",
        "required": [
            "provider",
            "name",
            "resource_type",
            "schema",
            "version",
            "doc_url",
        ],
        "properties": {
            "provider_id": {"type": "string", "description": "Provider ID"},
            "name": {"type": "string", "description": "Resource name"},
            "resource_type": {"type": "string", "description": "Resource type"},
            "schema": {"type": "string", "description": "Resource schema"},
            "version": {"type": "string", "description": "Resource version"},
            "doc_url": {"type": "string", "description": "Documentation URL"},
        },
    },
  • Core database helper function that performs the actual insertion of the Terraform resource into the database tables terraform_resources and provider_resources, handling transactions and provider lookup.
    def add_terraform_resource(
        db: DatabaseManager,
        provider_id: str,
        name: str,
        resource_type: str,
        schema: str,
        version: str,
        doc_url: str,
    ) -> str:
        """Add a new Terraform resource."""
        logger.info(
            "Adding Terraform resource",
            extra={
                "provider_id": provider_id,
                "resource_name": name,
                "resource_type": resource_type,
                "version": version,
                "operation": "add_terraform_resource",
            },
        )
        try:
            with db.get_connection() as conn:
                # Look up provider by ID or name
                provider = conn.execute(
                    """SELECT id FROM terraform_providers 
                    WHERE id = ? OR name = ?""",
                    (provider_id, provider_id),
                ).fetchone()
    
                if not provider:
                    raise ValueError(f"Provider '{provider_id}' not found")
    
                provider_id = provider["id"]  # Ensure we have the numeric ID
    
                conn.execute("BEGIN IMMEDIATE")
                try:
                    # Insert resource
                    cursor = conn.execute(
                        """INSERT INTO terraform_resources
                        (provider_id, name, resource_type, schema, version, doc_url, description, updated_at)
                        VALUES (?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)""",
                        (
                            provider_id,
                            name,
                            resource_type,
                            schema,
                            version,
                            doc_url,
                            f"Terraform {resource_type} resource",
                        ),
                    )
                    resource_id = cursor.lastrowid
    
                    # Create provider-resource relationship
                    provider_info = conn.execute(
                        "SELECT name FROM terraform_providers WHERE id = ?", (provider_id,)
                    ).fetchone()
    
                    conn.execute(
                        """INSERT INTO provider_resources
                        (provider_id, resource_id, provider_name, resource_type, 
                         schema_version, doc_url, relationship_type, metadata)
                        VALUES (?, ?, ?, ?, ?, ?, 'MANAGED', '{}')""",
                        (
                            provider_id,
                            resource_id,
                            provider_info["name"],
                            resource_type,
                            version,
                            doc_url,
                        ),
                    )
                    conn.commit()
                    return str(cursor.lastrowid)
                except Exception:
                    conn.rollback()
                    raise
        except sqlite3.Error as e:
            error_msg = f"Failed to add Terraform resource: {str(e)}"
            logger.error(error_msg)
            raise DatabaseError(error_msg)
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. It states this is an 'Add' operation (implying creation/mutation) but doesn't disclose any behavioral traits: no information about permissions required, whether this is idempotent, what happens on conflicts, rate limits, or what the response looks like. For a mutation tool with zero annotation coverage, this leaves significant gaps.

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 a single, efficient sentence that states the core purpose without unnecessary words. It's appropriately sized for a tool with clear parameters documented elsewhere, though it could be more front-loaded with critical behavioral information given the lack of annotations.

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 mutation tool with 6 required parameters, no annotations, and no output schema, the description is insufficiently complete. It doesn't address key contextual questions: what happens when adding duplicates, what permissions are needed, what the return value contains, or how this interacts with sibling tools. The description provides only basic purpose without necessary operational context.

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 6 parameters. The description adds no additional parameter semantics beyond what's in the schema - it doesn't explain relationships between parameters, format expectations, or provide examples. Baseline 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.

Purpose4/5

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

The description clearly states the verb ('Add') and resource ('new Terraform resource definition'), specifying what gets added (schema and version information). It distinguishes from siblings like 'add_terraform_provider' by focusing on resources rather than providers, but doesn't explicitly contrast with other resource-related tools like 'update_resource_schema' or 'get_terraform_resource_info'.

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. There's no mention of prerequisites (e.g., whether a provider must exist first), when to choose this over 'update_resource_schema', or what happens if the resource already exists. The description only states what the tool does, not when to use it.

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/AgentWong/iac-memory-mcp-server-project'

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