Skip to main content
Glama

read_docx

Extract text, tables, and image placeholders from DOCX files to access document content programmatically. Use this tool to read Word documents with structured paragraph separation.

Instructions

Read complete contents of a docx file including tables and images.Use this tool when you want to read file endswith '.docx'.Paragraphs are separated with two line breaks.This tool convert images into placeholder [Image].'--- Paragraph [number] ---' is indicator of each paragraph.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYesAbsolute path to target file

Implementation Reference

  • The main handler function for the read_docx tool. It validates the path, loads the DOCX document, processes paragraphs (including images and track changes), extracts table text, and formats the output with paragraph separators.
    async def read_docx(path: str) -> str:
        """Read docx file as text including tables.
        
        Args:
            path: relative path to target docx file
        Returns:
            str: Text representation of the document including tables
        """
        if not await validate_path(path):
            raise ValueError(f"Not a docx file: {path}")
        
        document = Document(path)
        content = []
    
        paragraph_index = 0
        table_index = 0
        
        # 全要素を順番に処理
        for element in document._body._body:
            # パラグラフの処理
            if element.tag == W_P:
                paragraph = document.paragraphs[paragraph_index]
                paragraph_index += 1
                # 画像のチェック
                if paragraph._element.findall(f'.//{W_DRAWING}', WORDML_NS):
                    content.append("[Image]")
                # テキストのチェック
                else:
                    text = process_track_changes(paragraph._element)
                    if text.strip():
                        content.append(text)
                    else:
                        # 空行を抜くと編集時に困るので、空行でも追加
                        content.append("")
            # テーブルの処理
            elif element.tag == W_TBL:
                table = document.tables[table_index]
                table_index += 1
                table_text = extract_table_text(table)
                content.append(f"[Table]\n{table_text}")
    
        separator = [f"--- Paragraph {i} ---" for i in range(len(content))]
        
        result = []
        for i, p in enumerate(content):
            result.append(separator[i])
            result.append(p)
            
        return "\n".join(result)
  • The Tool object definition providing the schema, name, and description for the read_docx tool, including input schema validation for the 'path' parameter.
    READ_DOCX = types.Tool(
        name="read_docx",
        description=(
            "Read complete contents of a docx file including tables and images."
            "Use this tool when you want to read file endswith '.docx'."
            "Paragraphs are separated with two line breaks."
            "This tool convert images into placeholder [Image]."
            "'--- Paragraph [number] ---' is indicator of each paragraph."
        ),
        inputSchema={
            "type": "object",
                    "properties": {
                    "path": {
                            "type": "string",
                            "description": "Absolute path to target file",
                        }
                    },
            "required": ["path"]
        }
    )
  • Registers the read_docx tool (as READ_DOCX) in the MCP server's list_tools handler.
    @server.list_tools()
    async def list_tools() -> list[types.Tool]:
        return [READ_DOCX, EDIT_DOCX_PARAGRAPH, WRITE_DOCX, EDIT_DOCX_INSERT]
  • Dispatches calls to the read_docx tool handler within the server's call_tool function.
    if name == "read_docx":
        content = await read_docx(arguments["path"])
        return [types.TextContent(type="text", text=content)]
  • Helper function to extract text from paragraphs while handling track changes (insertions). Used in read_docx.
    def process_track_changes(element: OxmlElement) -> str:
        """Process track changes in a paragraph element."""
        text = ""
        for child in element:
            if child.tag == W_R:  # Normal run
                for run_child in child:
                    if run_child.tag == W_T:
                        text += run_child.text if run_child.text else ""
            elif child.tag.endswith('ins'):  # Insertion
                inserted_text = ""
                for run in child.findall('.//w:t', WORDML_NS):
                    inserted_text += run.text if run.text else ""
                if inserted_text:
                    text += inserted_text
        return text
Behavior4/5

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

With no annotations provided, the description carries the full burden and effectively discloses key behavioral traits: it reads complete contents, handles tables and images, converts images to placeholders, uses specific paragraph separators, and includes paragraph indicators. It doesn't mention error handling or performance aspects, but covers core functionality well.

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 appropriately sized with four sentences that each add value: stating the tool's purpose, usage context, output format details, and paragraph indicators. It's front-loaded with the core functionality but could be slightly more streamlined by combining related formatting details.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/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 (reading structured documents), no annotations, no output schema, and 100% schema coverage, the description provides good contextual completeness by explaining what content is read, how images are handled, and paragraph formatting. It could benefit from mentioning error cases or return structure, but covers essential usage well.

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?

The schema description coverage is 100% (the 'path' parameter is documented as 'Absolute path to target file'), so the baseline is 3. The description adds no additional parameter-specific information beyond what the schema provides, maintaining this adequate baseline.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

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

The description clearly states the specific action ('Read complete contents'), resource ('docx file'), and scope ('including tables and images'), distinguishing it from sibling tools like edit_docx_insert or write_docx that modify rather than read files.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

It provides explicit guidance on when to use this tool ('when you want to read file endswith .docx'), distinguishing it from alternatives by focusing on reading rather than editing or writing operations, though it doesn't explicitly name sibling tools.

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/famano/mcp-server-office'

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