Skip to main content
Glama
MKhalusova

Unstructured Document Processor MCP

by MKhalusova

process_document

Extract and use content from unstructured documents across various file formats by processing them with Unstructured.

Instructions

Sends document to process with Unstructured, return the content of the document
 Args:
filepath: path to the document

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
filepathYes

Implementation Reference

  • The core handler function for the 'process_document' tool, decorated with @mcp.tool() for automatic registration in FastMCP. It validates the file, checks supported extensions, partitions the document using UnstructuredClient API, saves elements as JSON, converts to formatted text using json_to_text helper, and returns the result.
    @mcp.tool()
    async def process_document(ctx: Context, filepath: str) -> str:
        """
        Sends document to process with Unstructured, return the content of the document
         Args:
        filepath: path to the document
        """
    
        if not os.path.isfile(filepath):
            return "File does not exist"
    
        # Check is file extension is supported
        _, ext = os.path.splitext(filepath)
        supported_extensions = {".abw", ".bmp", ".csv", ".cwk", ".dbf", ".dif", ".doc", ".docm", ".docx", ".dot",
                                ".dotm", ".eml", ".epub", ".et", ".eth", ".fods", ".gif", ".heic", ".htm", ".html",
                                ".hwp", ".jpeg", ".jpg", ".md", ".mcw", ".mw", ".odt", ".org", ".p7s", ".pages",
                                ".pbd", ".pdf", ".png", ".pot", ".potm", ".ppt", ".pptm", ".pptx", ".prn", ".rst",
                                ".rtf", ".sdp", ".sgl", ".svg", ".sxg", ".tiff", ".txt", ".tsv", ".uof", ".uos1",
                                ".uos2", ".web", ".webp", ".wk2", ".xls", ".xlsb", ".xlsm", ".xlsx", ".xlw", ".xml",
                                ".zabw"}
    
        if ext.lower() not in supported_extensions:
            return "File extension not supported by Unstructured"
    
        client = ctx.request_context.lifespan_context.client
        file_basename = os.path.basename(filepath)
    
        req = operations.PartitionRequest(
            partition_parameters=shared.PartitionParameters(
                files=shared.Files(
                    content=open(filepath, "rb"),
                    file_name=filepath,
                ),
                strategy=shared.Strategy.AUTO,
            ),
        )
    
        os.makedirs(PROCESSED_FILES_FOLDER, exist_ok=True)
    
        try:
            res = client.general.partition(request=req)
            element_dicts = [element for element in res.elements]
            json_elements = json.dumps(element_dicts, indent=2)
            output_json_file_path = os.path.join(PROCESSED_FILES_FOLDER, f"{file_basename}.json")
            with open(output_json_file_path, "w") as file:
                file.write(json_elements)
    
            return json_to_text(output_json_file_path)
        except Exception as e:
            return f"The following exception happened during file processing: {e}"
  • Helper function to convert Unstructured JSON output to formatted HTML/text string, used by process_document.
    def json_to_text(file_path) -> str:
        with open(file_path, 'r') as file:
            elements = json.load(file)
    
        doc_texts = []
    
        for element in elements:
            text = element.get("text", "").strip()
            element_type = element.get("type", "")
            metadata = element.get("metadata", {})
    
            if element_type == "Title":
                doc_texts.append(f"<h1> {text}</h1><br>")
            elif element_type == "Header":
                doc_texts.append(f"<h2> {text}</h2><br/>")
            elif element_type == "NarrativeText" or element_type == "UncategorizedText":
                doc_texts.append(f"<p>{text}</p>")
            elif element_type == "ListItem":
                doc_texts.append(f"<li>{text}</li>")
            elif element_type == "PageNumber":
                doc_texts.append(f"Page number: {text}")
            elif element_type == "Table":
                table_html = metadata.get("text_as_html", "")
                doc_texts.append(table_html)  # Keep the table as HTML
            else:
                doc_texts.append(text)
    
        return " ".join(doc_texts)
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 mentions processing and returning content but lacks details on permissions, rate limits, error handling, or what 'process with Unstructured' entails (e.g., parsing, extraction). For a tool with no annotations, this leaves significant behavioral gaps.

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 concise and well-structured: a clear purpose statement followed by a parameter explanation. It avoids unnecessary words and is front-loaded with the main functionality. The only minor inefficiency is the lack of formatting in the Args section, but overall it's efficient.

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 no annotations, no output schema, and low schema coverage, the description is incomplete. It explains the basic operation and parameter but misses critical details like return format, error conditions, or what 'Unstructured' processing involves. For a tool that processes documents, more context is needed to use it effectively.

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 description includes an Args section explaining 'filepath: path to the document', which adds meaning beyond the schema's bare title 'Filepath'. However, with 0% schema description coverage and only one parameter, this provides basic but incomplete context (e.g., no format examples or constraints). It meets the baseline for minimal parameter explanation.

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: 'Sends document to process with Unstructured, return the content of the document'. It specifies the verb ('process'), resource ('document'), and technology ('Unstructured'), though it doesn't differentiate from siblings since none exist. The purpose is specific and actionable.

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, prerequisites, or typical use cases. It simply states what the tool does without context about when it's appropriate. Since there are no sibling tools, this is less critical but still a gap in usage context.

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/MKhalusova/unstructured-mcp'

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