Skip to main content
Glama
zeph-gh

DOCX MCP Server

by zeph-gh

convert_to_markdown

Convert DOCX files to Markdown format to simplify document formatting and enable compatibility with markdown-supported platforms.

Instructions

Convert DOCX file to Markdown format

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
file_pathYesPath to the .docx file

Implementation Reference

  • The core handler function that performs the DOCX to Markdown conversion using mammoth for HTML intermediate step and regex-based HTML to Markdown transformation.
    async ({ file_path }) => {
      try {
        const absolutePath = path.resolve(file_path)
    
        if (!fs.existsSync(absolutePath)) {
          throw new Error(`File not found: ${absolutePath}`)
        }
    
        // Convert to HTML first
        const htmlResult = await mammoth.convertToHtml({ path: absolutePath })
        let html = htmlResult.value
    
        // Simple HTML to Markdown conversion
        let markdown = html
          // Headers
          .replace(/<h1[^>]*>(.*?)<\/h1>/gi, '# $1\n\n')
          .replace(/<h2[^>]*>(.*?)<\/h2>/gi, '## $1\n\n')
          .replace(/<h3[^>]*>(.*?)<\/h3>/gi, '### $1\n\n')
          .replace(/<h4[^>]*>(.*?)<\/h4>/gi, '#### $1\n\n')
          .replace(/<h5[^>]*>(.*?)<\/h5>/gi, '##### $1\n\n')
          .replace(/<h6[^>]*>(.*?)<\/h6>/gi, '###### $1\n\n')
          // Bold and italic
          .replace(/<strong[^>]*>(.*?)<\/strong>/gi, '**$1**')
          .replace(/<b[^>]*>(.*?)<\/b>/gi, '**$1**')
          .replace(/<em[^>]*>(.*?)<\/em>/gi, '*$1*')
          .replace(/<i[^>]*>(.*?)<\/i>/gi, '*$1*')
          // Lists
          .replace(/<ul[^>]*>/gi, '')
          .replace(/<\/ul>/gi, '\n')
          .replace(/<ol[^>]*>/gi, '')
          .replace(/<\/ol>/gi, '\n')
          .replace(/<li[^>]*>(.*?)<\/li>/gi, '- $1\n')
          // Paragraphs
          .replace(/<p[^>]*>(.*?)<\/p>/gi, '$1\n\n')
          // Line breaks
          .replace(/<br[^>]*>/gi, '\n')
          // Remove remaining HTML tags
          .replace(/<[^>]*>/g, '')
          // Clean up extra whitespace
          .replace(/\n{3,}/g, '\n\n')
          .trim()
    
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(
                {
                  markdown: markdown,
                  word_count: markdown
                    .split(/\s+/)
                    .filter((word: string) => word.length > 0).length,
                  messages: htmlResult.messages,
                },
                null,
                2
              ),
            },
          ],
        }
      } catch (error) {
        return {
          content: [
            {
              type: 'text',
              text: `Error converting to Markdown: ${(error as Error).message}`,
            },
          ],
          isError: true,
        }
      }
    }
  • src/index.ts:323-401 (registration)
    Registers the 'convert_to_markdown' tool with the MCP server, including description, input schema, and inline handler function.
    server.tool(
      'convert_to_markdown',
      'Convert DOCX file to Markdown format',
      {
        file_path: z.string().describe('Path to the .docx file'),
      },
      async ({ file_path }) => {
        try {
          const absolutePath = path.resolve(file_path)
    
          if (!fs.existsSync(absolutePath)) {
            throw new Error(`File not found: ${absolutePath}`)
          }
    
          // Convert to HTML first
          const htmlResult = await mammoth.convertToHtml({ path: absolutePath })
          let html = htmlResult.value
    
          // Simple HTML to Markdown conversion
          let markdown = html
            // Headers
            .replace(/<h1[^>]*>(.*?)<\/h1>/gi, '# $1\n\n')
            .replace(/<h2[^>]*>(.*?)<\/h2>/gi, '## $1\n\n')
            .replace(/<h3[^>]*>(.*?)<\/h3>/gi, '### $1\n\n')
            .replace(/<h4[^>]*>(.*?)<\/h4>/gi, '#### $1\n\n')
            .replace(/<h5[^>]*>(.*?)<\/h5>/gi, '##### $1\n\n')
            .replace(/<h6[^>]*>(.*?)<\/h6>/gi, '###### $1\n\n')
            // Bold and italic
            .replace(/<strong[^>]*>(.*?)<\/strong>/gi, '**$1**')
            .replace(/<b[^>]*>(.*?)<\/b>/gi, '**$1**')
            .replace(/<em[^>]*>(.*?)<\/em>/gi, '*$1*')
            .replace(/<i[^>]*>(.*?)<\/i>/gi, '*$1*')
            // Lists
            .replace(/<ul[^>]*>/gi, '')
            .replace(/<\/ul>/gi, '\n')
            .replace(/<ol[^>]*>/gi, '')
            .replace(/<\/ol>/gi, '\n')
            .replace(/<li[^>]*>(.*?)<\/li>/gi, '- $1\n')
            // Paragraphs
            .replace(/<p[^>]*>(.*?)<\/p>/gi, '$1\n\n')
            // Line breaks
            .replace(/<br[^>]*>/gi, '\n')
            // Remove remaining HTML tags
            .replace(/<[^>]*>/g, '')
            // Clean up extra whitespace
            .replace(/\n{3,}/g, '\n\n')
            .trim()
    
          return {
            content: [
              {
                type: 'text',
                text: JSON.stringify(
                  {
                    markdown: markdown,
                    word_count: markdown
                      .split(/\s+/)
                      .filter((word: string) => word.length > 0).length,
                    messages: htmlResult.messages,
                  },
                  null,
                  2
                ),
              },
            ],
          }
        } catch (error) {
          return {
            content: [
              {
                type: 'text',
                text: `Error converting to Markdown: ${(error as Error).message}`,
              },
            ],
            isError: true,
          }
        }
      }
    )
  • Zod schema defining the input parameter 'file_path' for the tool.
    {
      file_path: z.string().describe('Path to the .docx file'),
    },
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. It states what the tool does but doesn't describe important behavioral traits: whether it preserves formatting, handles images/tables, requires specific permissions, has rate limits, or what happens on failure. 'Convert' implies a transformation but lacks details about the conversion process quality or limitations.

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 extremely concise with a single sentence that directly states the tool's function. There's zero wasted language, no unnecessary elaboration, and it's front-loaded with the core purpose. Every word earns its place in this minimal description.

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?

For a file conversion tool with no annotations and no output schema, the description is insufficiently complete. It doesn't explain what the output looks like (format details, where the markdown is saved/returned), conversion quality, error conditions, or important behavioral constraints. The agent would need to guess about the conversion's scope and limitations.

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?

Schema description coverage is 100%, so the schema already fully documents the single 'file_path' parameter. The description doesn't add any parameter semantics beyond what the schema provides - it doesn't explain acceptable path formats, file location constraints, or supported DOCX versions. Baseline 3 is appropriate when schema does the heavy lifting.

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 with a specific verb ('Convert') and resource ('DOCX file'), specifying the target format ('Markdown format'). It distinguishes from some siblings like 'extract_text' or 'extract_images' by focusing on format conversion, though it doesn't explicitly differentiate from 'convert_to_html' which is a similar conversion tool.

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 when to choose this over 'convert_to_html' for different output formats, or when to use 'extract_text' if only plain text is needed. There's no context about prerequisites, file size limitations, or compatibility issues.

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/zeph-gh/Docx-Mcp-Server'

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