Skip to main content
Glama

replace_block_between_manual_anchors

Replace content in Word documents by specifying start and end anchor texts, updating sections with new paragraphs while maintaining desired formatting and structure.

Instructions

Replace all content between start_anchor_text and end_anchor_text (or next logical header if not provided).

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
end_anchor_textNo
filenameYes
new_paragraph_styleNo
new_paragraphsYes
start_anchor_textYes

Implementation Reference

  • MCP tool registration using @mcp.tool() decorator. This defines the entry point for the tool with input parameters matching the tool schema and calls the implementation wrapper.
    async def replace_block_between_manual_anchors(filename: str, start_anchor_text: str, new_paragraphs: List[str], end_anchor_text: Optional[str] = None, new_paragraph_style: Optional[str] = None):
        """Replace all content between start_anchor_text and end_anchor_text (or next logical header if not provided)."""
        return await replace_block_between_manual_anchors_tool(
            filename=filename,
            start_anchor_text=start_anchor_text,
            new_paragraphs=new_paragraphs,
            end_anchor_text=end_anchor_text,
            new_paragraph_style=new_paragraph_style
        )
  • Tool handler wrapper function that receives parameters from MCP and delegates to the core utility function in document_utils.
    async def replace_block_between_manual_anchors_tool(filename: str, start_anchor_text: str, new_paragraphs: list[str], end_anchor_text: str = None, new_paragraph_style: str = None) -> str:
        """Replace all content between start_anchor_text and end_anchor_text (or next logical header if not provided)."""
        return replace_block_between_manual_anchors(
            doc_path=filename,
            start_anchor=start_anchor_text,
            new_paragraphs=new_paragraphs,
            end_anchor=end_anchor_text,
            new_paragraph_style=new_paragraph_style
        )
  • Core utility function implementing the logic to find anchors by text or index, delete paragraphs between them, insert new paragraphs with optional styles, and save the document.
    def replace_block_between_manual_anchors(
        doc_path: str,
        start_anchor,
        new_paragraphs: list[str],
        end_anchor=None,
        new_paragraph_style: str = None
    ) -> str:
        """
        Replace all content (paragraphs) between start_anchor and end_anchor (exclusive).
        Anchors can be specified by string (exact paragraph text) or by integer (paragraph index).
        If end_anchor is None, deletes until the end of the document.
        Inserts new_paragraphs after the start anchor.
        """
        from docx import Document
        import os
        if not os.path.exists(doc_path):
            return f"Document {doc_path} not found."
        doc = Document(doc_path)
    
        # Find start anchor index
        if isinstance(start_anchor, int):
            start_idx = start_anchor
            if start_idx < 0 or start_idx >= len(doc.paragraphs):
                return f"Invalid start_anchor index: {start_idx}. Document has {len(doc.paragraphs)} paragraphs."
        else:
            start_idx = None
            for i, para in enumerate(doc.paragraphs):
                if para.text.strip() == str(start_anchor).strip():
                    start_idx = i
                    break
            if start_idx is None:
                return f"Start anchor '{start_anchor}' not found."
    
        # Find end anchor index
        if end_anchor is None:
            end_idx = len(doc.paragraphs)
        elif isinstance(end_anchor, int):
            end_idx = end_anchor
            if end_idx < 0 or end_idx > len(doc.paragraphs):
                return f"Invalid end_anchor index: {end_idx}. Document has {len(doc.paragraphs)} paragraphs."
        else:
            end_idx = None
            for i in range(start_idx + 1, len(doc.paragraphs)):
                if doc.paragraphs[i].text.strip() == str(end_anchor).strip():
                    end_idx = i
                    break
            if end_idx is None:
                return f"End anchor '{end_anchor}' not found after start anchor."
    
        # Delete all paragraphs between start_idx and end_idx (exclusive)
        removed_count = 0
        for i in range(end_idx - 1, start_idx, -1):
            p = doc.paragraphs[i]._element
            p.getparent().remove(p)
            removed_count += 1
    
        # Insert new paragraphs after the start anchor
        style_to_use = new_paragraph_style or "Normal"
        anchor_para = doc.paragraphs[start_idx]
        current_para = anchor_para
        for para in new_paragraphs:
            if isinstance(para, dict):
                text = para.get("text", "")
                style = para.get("style", style_to_use)
            else:
                text = str(para)
                style = style_to_use
            new_para = doc.add_paragraph(text, style=style)
            current_para._element.addnext(new_para._element)
            current_para = new_para
    
        doc.save(doc_path)
        return f"Replaced content between anchor {start_anchor} and {end_anchor if end_anchor is not None else 'end of document'} with {len(new_paragraphs)} paragraph(s), removed {removed_count} paragraphs."
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 indicates a mutation operation ('replace') but doesn't specify permissions needed, whether changes are reversible, or potential side effects (e.g., if anchors are not found). The fallback to 'next logical header' adds some context, but overall, it lacks details on error handling, rate limits, or output format, making it insufficient 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 a single, efficient sentence that front-loads the core action ('replace all content') and includes essential details (anchors and fallback). There is no wasted verbiage, and it directly addresses the tool's function without redundancy, making it highly concise and well-structured.

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 mutation tool with 5 parameters, 0% schema coverage, no annotations, and no output schema, the description is incomplete. It lacks details on parameter semantics, behavioral traits (e.g., error conditions), and expected outcomes, failing to provide enough context for safe and effective use by an AI agent.

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

Parameters2/5

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

Schema description coverage is 0%, so the description must compensate for all parameters. It mentions 'start_anchor_text' and 'end_anchor_text' and implies their usage, but doesn't explain 'filename', 'new_paragraphs', or 'new_paragraph_style'. The description adds minimal value beyond the schema, failing to clarify parameter meanings or interactions, such as how 'new_paragraphs' relates to the replacement content.

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 'replace' and specifies the resource as 'content between start_anchor_text and end_anchor_text', making the purpose understandable. It distinguishes from siblings like 'replace_paragraph_block_below_header' by focusing on manual anchors rather than headers. However, it doesn't explicitly mention what type of content is being replaced (e.g., in a document), which slightly reduces specificity.

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 by mentioning the fallback to 'next logical header if not provided' for end_anchor_text, suggesting when to omit that parameter. However, it doesn't provide explicit guidance on when to use this tool versus alternatives like 'replace_paragraph_block_below_header' or 'search_and_replace', nor does it mention prerequisites or exclusions, leaving usage context somewhat vague.

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

Related 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/franlealp1/mcp-word'

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