Skip to main content
Glama

replace_paragraph_block_below_header

Replace a paragraph block below a specific header in a Word document without altering the table of contents. Ideal for targeted content updates while maintaining document structure.

Instructions

Reemplaza el bloque de párrafos debajo de un encabezado, evitando modificar TOC.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
detect_block_end_fnNo
filenameYes
header_textYes
new_paragraphsYes

Implementation Reference

  • The main handler function for the MCP tool that wraps the core logic.
    async def replace_paragraph_block_below_header_tool(filename: str, header_text: str, new_paragraphs: list[str], detect_block_end_fn=None) -> str:
        """Reemplaza el bloque de párrafos debajo de un encabezado, evitando modificar TOC."""
        return replace_paragraph_block_below_header(filename, header_text, new_paragraphs, detect_block_end_fn)
  • MCP tool registration using @mcp.tool() decorator, defining input schema via parameters.
    @mcp.tool()
    async def replace_paragraph_block_below_header(filename: str, header_text: str, new_paragraphs: List[str], detect_block_end_fn=None):
        """Reemplaza el bloque de párrafos debajo de un encabezado, evitando modificar TOC."""
        return await replace_paragraph_block_below_header_tool(filename, header_text, new_paragraphs, detect_block_end_fn)
  • Core helper function implementing the replacement logic, including finding header, deleting block, and inserting new paragraphs.
    def replace_paragraph_block_below_header(
        doc_path: str,
        header_text: str,
        new_paragraphs: list[str],
        detect_block_end_fn=None,
        new_paragraph_style: str = None
    ) -> str:
        """
        Reemplaza todo el contenido debajo de una cabecera (por texto), hasta el siguiente encabezado/TOC (por estilo).
        """
        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 the header paragraph first
        header_para = None
        header_idx = None
        for i, para in enumerate(doc.paragraphs):
            para_text = para.text.strip().lower()
            is_toc = is_toc_paragraph(para)
            if para_text == header_text.strip().lower() and not is_toc:
                header_para = para
                header_idx = i
                break
        
        if header_para is None:
            return f"Header '{header_text}' not found in document."
        
        # Delete everything under the header using the same document instance
        header_el, removed_count = delete_block_under_header(doc, header_text)
        
        # Now insert new paragraphs after the header (which should still be in the document)
        style_to_use = new_paragraph_style or "Normal"
        
        # Find the header again after deletion (it should still be there)
        current_para = header_para
        for text in new_paragraphs:
            new_para = doc.add_paragraph(text, style=style_to_use)
            current_para._element.addnext(new_para._element)
            current_para = new_para
        
        doc.save(doc_path)
        return f"Replaced content under '{header_text}' with {len(new_paragraphs)} paragraph(s), style: {style_to_use}, removed {removed_count} elements."
  • Supporting helper to delete the block under the header until next heading or TOC.
    def delete_block_under_header(doc, header_text):
        """
        Remove all elements (paragraphs, tables, etc.) after the header (by text) and before the next heading/TOC (by style).
        Returns: (header_element, elements_removed)
        """
        # Find the header paragraph by text (like delete_paragraph finds by index)
        header_para = None
        header_idx = None
        
        for i, para in enumerate(doc.paragraphs):
            if para.text.strip().lower() == header_text.strip().lower():
                header_para = para
                header_idx = i
                break
        
        if header_para is None:
            return None, 0
        
        # Find the next heading/TOC paragraph to determine the end of the block
        end_idx = None
        for i in range(header_idx + 1, len(doc.paragraphs)):
            para = doc.paragraphs[i]
            if para.style and para.style.name.lower().startswith(('heading', 'título', 'toc')):
                end_idx = i
                break
        
        # If no next heading found, delete until end of document
        if end_idx is None:
            end_idx = len(doc.paragraphs)
        
        # Remove paragraphs by index (like delete_paragraph does)
        removed_count = 0
        for i in range(header_idx + 1, end_idx):
            if i < len(doc.paragraphs):  # Safety check
                para = doc.paragraphs[header_idx + 1]  # Always remove the first paragraph after header
                p = para._p
                p.getparent().remove(p)
                removed_count += 1
        
        return header_para._p, removed_count
Behavior2/5

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

With no annotations provided, the description carries full burden but offers limited behavioral insight. It mentions avoiding TOC modification (a useful constraint) but doesn't disclose critical traits: whether this is a destructive mutation, what happens to the replaced content, error handling, permissions needed, or output format. For a 4-parameter mutation tool, this is inadequate.

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 in Spanish that front-loads the core purpose. Every word earns its place: it specifies the action, target, and a key constraint without redundancy or fluff.

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 a 4-parameter mutation tool with no annotations, 0% schema coverage, and no output schema, the description is incomplete. It lacks parameter explanations, behavioral details, error conditions, and output expectations. The TOC constraint is helpful but insufficient for the tool's complexity.

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 but adds no parameter information. It doesn't explain what 'detect_block_end_fn' does, how 'header_text' is matched, what 'new_paragraphs' should contain, or file format expectations for 'filename'. The description fails to provide meaning beyond the bare schema.

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 ('Reemplaza' - replaces) and the target ('bloque de párrafos debajo de un encabezado' - paragraph block below a header), with a specific constraint ('evitando modificar TOC' - avoiding modifying TOC). It distinguishes from siblings like 'replace_block_between_manual_anchors' by focusing on header-based replacement, but doesn't explicitly contrast with all alternatives.

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 minimal guidance: it implies usage when needing to replace paragraphs under a header without affecting the TOC. However, it offers no explicit when-to-use vs. when-not-to-use advice, no prerequisites, and no comparison to alternatives like 'replace_block_between_manual_anchors' or 'delete_paragraph' + 'add_paragraph' combinations.

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