Skip to main content
Glama
AgentWong

IAC Memory MCP Server

by AgentWong

add_terraform_resource

Define and store new Terraform resource configurations with schema, version, and documentation for infrastructure-as-code management.

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

  • The MCP tool handler that validates arguments, checks schema JSON validity, invokes the database add function, and returns success/error TextContent.
    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)]
  • 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"},
        },
    },
  • Dictionary registering the add_terraform_resource handler function with the tool name, used by the MCP server to dispatch tool calls.
    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,
        "update_resource_schema": handle_update_resource_schema,
    }
  • Core database helper function that inserts the new Terraform resource record, creates provider-resource relationship, and handles transactions with proper error handling.
    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?

No annotations are provided, so the description carries the full burden of behavioral disclosure. It states the tool adds a resource definition, implying a write operation, but doesn't cover critical aspects like permissions required, whether it's idempotent, error handling (e.g., duplicate resources), or what happens on success (e.g., confirmation message). This leaves significant gaps for safe and effective use.

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 front-loads the core action ('Add a new Terraform resource definition') and includes essential details ('with its schema and version information') without unnecessary words. Every part earns its place, making it easy to scan and understand quickly.

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 a 6-parameter write tool with no annotations and no output schema, the description is insufficient. It lacks behavioral context (e.g., side effects, error cases), usage guidance relative to siblings, and details on return values or success indicators. This makes it incomplete for safe and informed use by an AI agent.

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%, with each parameter clearly documented in the schema (e.g., 'provider_id' as 'Provider ID'). The description adds no additional meaning beyond the schema, such as explaining relationships between parameters (e.g., how 'provider_id' relates to 'resource_type') or providing examples. Baseline 3 is appropriate since 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 action ('Add a new Terraform resource definition') and specifies what is being added ('with its schema and version information'), which distinguishes it from generic creation tools like 'create_entity'. However, it doesn't explicitly differentiate from sibling tools like 'add_terraform_provider' or 'update_resource_schema' in terms of scope or use case.

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 an existing provider), contrast with similar tools (e.g., 'add_terraform_provider' for providers, 'update_resource_schema' for updates), or specify scenarios where it's appropriate (e.g., initial setup vs. modifications).

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'

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