Skip to main content
Glama

fill_merge_fields

Populate merge fields in Word documents using provided data to automate document personalization and template processing.

Instructions

Fill merge fields in a document with provided data.

Args: filepath: Path to the document or template data: Dictionary mapping field names to values

Returns: Dictionary with status and modified document info

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
filepathYes
dataYes

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The handler function 'fill_merge_fields' iterates through document paragraphs and runs, replacing placeholders of the form {{field_name}} with values provided in the data dictionary.
    def fill_merge_fields(filepath: str, data: dict[str, str]) -> dict[str, Any]:
        """
        Fill merge fields in a document with provided data.
    
        Args:
            filepath: Path to the document or template
            data: Dictionary mapping field names to values
    
        Returns:
            Dictionary with status and modified document info
        """
        logger.info("Filling merge fields", extra={"tool": "fill_merge_fields", "filepath": filepath})
    
        try:
            doc = safe_open_document(filepath)
            fields_filled = 0
    
            # Simple merge field filling by replacing in text
            for paragraph in doc.paragraphs:
                for run in paragraph.runs:
                    for field_name, field_value in data.items():
                        if f"{{{{{field_name}}}}}" in run.text:
                            run.text = run.text.replace(f"{{{{{field_name}}}}}", str(field_value))
                            fields_filled += 1
    
            safe_save_document(doc, filepath)
            logger.info(f"Filled {fields_filled} merge fields", extra={"filepath": filepath})
    
            return {
                "status": "success",
                "filepath": filepath,
                "fields_filled": fields_filled,
                "message": f"Filled {fields_filled} merge fields",
            }
        except DocxMcpError as e:
            logger.warning(e.message, extra={"tool": "fill_merge_fields", "error_code": e.error_code})
            return {"status": "error", "error": e.message, "error_code": e.error_code}
        except Exception as e:
            logger.error(f"Unexpected error filling merge fields: {str(e)}")
            return {"status": "error", "error": str(e)}
  • The tool is registered using the @app.tool() decorator immediately preceding the function definition (implied by the structure).
    @app.tool()
    def fill_merge_fields(filepath: str, data: dict[str, str]) -> dict[str, Any]:
        """
        Fill merge fields in a document with provided data.
    
        Args:
            filepath: Path to the document or template
            data: Dictionary mapping field names to values
    
        Returns:
            Dictionary with status and modified document info
        """
        logger.info("Filling merge fields", extra={"tool": "fill_merge_fields", "filepath": filepath})
    
        try:
            doc = safe_open_document(filepath)
            fields_filled = 0
    
            # Simple merge field filling by replacing in text
            for paragraph in doc.paragraphs:
                for run in paragraph.runs:
                    for field_name, field_value in data.items():
                        if f"{{{{{field_name}}}}}" in run.text:
                            run.text = run.text.replace(f"{{{{{field_name}}}}}", str(field_value))
                            fields_filled += 1
    
            safe_save_document(doc, filepath)
            logger.info(f"Filled {fields_filled} merge fields", extra={"filepath": filepath})
    
            return {
                "status": "success",
                "filepath": filepath,
                "fields_filled": fields_filled,
                "message": f"Filled {fields_filled} merge fields",
            }
        except DocxMcpError as e:
            logger.warning(e.message, extra={"tool": "fill_merge_fields", "error_code": e.error_code})
            return {"status": "error", "error": e.message, "error_code": e.error_code}
        except Exception as e:
            logger.error(f"Unexpected error filling merge fields: {str(e)}")
            return {"status": "error", "error": str(e)}
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 modifies a document (implied mutation) but doesn't cover critical aspects like whether it overwrites the original file, creates a new file, requires specific permissions, handles errors, or has rate limits. This leaves significant gaps for a mutation tool.

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 front-loaded with a clear purpose statement, followed by structured sections for Args and Returns. Every sentence earns its place: the first defines the tool, and the subsequent lines efficiently document parameters and output without redundancy. It's appropriately sized for a 2-parameter tool.

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's moderate complexity (2 parameters, mutation operation), no annotations, and an output schema present, the description is partially complete. It covers the basic purpose and parameters but lacks behavioral details (e.g., file handling, error cases). The output schema reduces the need to explain return values, but more context on the mutation's effects is warranted.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The description adds meaningful context for both parameters: 'filepath: Path to the document or template' and 'data: Dictionary mapping field names to values.' With 0% schema description coverage, this compensates well by explaining what each parameter represents. However, it doesn't specify format details (e.g., file path conventions, data types beyond strings), keeping it from a perfect score.

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 tool's purpose: 'Fill merge fields in a document with provided data.' This specifies the verb ('fill'), resource ('merge fields in a document'), and mechanism ('with provided data'). However, it doesn't explicitly differentiate from sibling tools like 'list_merge_fields' or 'write_docx', which prevents a perfect score.

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 a document with merge fields), exclusions, or comparisons to siblings like 'write_docx' for saving or 'list_merge_fields' for discovery. Usage is implied but not explicitly stated.

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/Andrew82106/LLM_Docx_Agent_MCP'

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