如何使用MarkItDown MCP將文件轉換為Markdown?

如何使用MarkItDown MCP將文件轉換為Markdown?

處理文件不再僅僅是在人工智慧專案中開啟檔案,而是要將混亂轉化為清晰。PDF、PowerPoint 和 Word 等文件以各種形狀和大小充斥著我們的工作流程。如今,從這些文件中檢索結構化內容已成為一項艱鉅的任務。微軟的 Markitdown MCP(Markdown 轉換協議)簡化了這一工作。它能將各種檔案轉換為結構化的 Markdown 格式。這有助於開發人員和技術撰稿人改進文件工作流程。

本文將解釋 Markitdown MCP 並展示其用法。我們將介紹 Markitdown MCP 伺服器的設定,還將討論該協議背景下的 MarkItDown。下文還將介紹如何使用 Markitdown MCP 伺服器進行測試。

什麼是MarkItDown MCP?

Markitdown MCP 為文件轉換提供了一種標準方法。它是一種伺服器端協議。它在後臺使用微軟的 MarkItdown 庫。伺服器託管一個 RESTful API。使用者將 PDF 或 Word 檔案等文件傳送到該伺服器。伺服器隨後處理這些檔案。它使用高階解析和特定格式化規則。輸出結果是保持原始文件結構的 Markdown 文字。

Markitdown MCP的主要功能

Markitdown MCP 伺服器包含幾個有用的功能:

  • 寬格式支援:它可將 PDF、DOCX 和 PPTX 等常見檔案轉換為 Markdown。
  • 結構儲存:它使用各種方法來理解和維護文件佈局,如標題和列表。
  • 可配置輸出:使用者可以調整設定來控制最終的 Markdown 風格。
  • 伺服器執行:它以伺服器程序的形式執行。這樣就可以整合到自動化系統和雲設定中。

Markdown在工作流程中的作用

Markdown 是一種流行的文件格式。它的語法簡單,易於讀寫。許多平臺(如 GitHub)都很好地支援它。靜態網站生成器也經常使用它。手動將其他格式轉換為 Markdown 需要時間。Markitdown MCP 可自動完成這種轉換。這樣做的好處顯而易見:

  • 高效的內容處理:將原始檔轉換為可用的 Markdown。
  • 一致的協作:標準格式有助於團隊共同處理文件。
  • 流程自動化:將文件轉換納入更大的自動化工作流程。

為整合設定 Markitdown MCP 伺服器

Github Repo 所述,我們可以使用 Docker Image 將 Markitdown MCP 伺服器與 Claude、Windsurf、Cursor 等不同的客戶端設定在一起。但在這裡,我們將使用LangChain 的 MCP 介面卡建立一個本地 MCP 客戶端。我們需要執行伺服器,以便與 LangChain 配合使用。伺服器支援不同的執行模式。

安裝

首先,安裝所需的 Python 軟體包。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
pip install markitdown-mcp langchain langchain_mcp_adapters langgraph langchain_groq
pip install markitdown-mcp langchain langchain_mcp_adapters langgraph langchain_groq
pip install markitdown-mcp langchain langchain_mcp_adapters langgraph langchain_groq

伺服器配置

使用 STDIO 模式執行 Markitdown MCP 伺服器。該模式連線標準輸入和輸出流。它非常適合基於指令碼的整合。在終端直接執行以下內容。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
markitdown-mcp
markitdown-mcp
markitdown-mcp

伺服器開始執行時會發出一些警告。

伺服器配置

我們還可以使用 SSE(伺服器傳送事件)模式。這種模式適合網路應用程式或長期執行的連線。在設定 Markitdown MCP 伺服器以測試特定場景時,它也非常有用。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
markitdown-mcp --sse --host 127.0.0.1 --port 3001
markitdown-mcp --sse --host 127.0.0.1 --port 3001
markitdown-mcp --sse --host 127.0.0.1 --port 3001

選擇適合您的整合計劃的模式。透過 STDIO 使用伺服器進行本地測試通常是一個好的開始。我們建議在本文中使用 STDIO 模式。

使用 Markitdown MCP 進行 Markdown 轉換

在上一篇文章《如何使用 LangChain 建立 MCP 客戶端伺服器》中,我們已經介紹瞭如何使用 LangChain 在本地構建 MCP 伺服器和客戶端設定。

本節將介紹如何將 LangChain 與 Markitdown MCP 伺服器結合使用。它能自動將 PDF 檔案轉換為 Markdown 檔案。該示例透過 ChatGroq 使用了 Groq 的 LLaMA 模型。請確保將 Groq API 金鑰設定為環境變數,或直接將其傳遞給 ChatGroq。

第 1 步:首先匯入必要的庫。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from langchain_mcp_adapters.tools import load_mcp_tools
from langgraph.prebuilt import create_react_agent
import asyncio
from langchain_groq import ChatGroq
from mcp import ClientSession, StdioServerParameters from mcp.client.stdio import stdio_client from langchain_mcp_adapters.tools import load_mcp_tools from langgraph.prebuilt import create_react_agent import asyncio from langchain_groq import ChatGroq
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from langchain_mcp_adapters.tools import load_mcp_tools
from langgraph.prebuilt import create_react_agent
import asyncio
from langchain_groq import ChatGroq

第 2 步:免費初始化Groq LLM。

您可以在此處找到 API 金鑰:Groq API Key

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# Initialize Groq model
model = ChatGroq(model="meta-llama/llama-4-scout-17b-16e-instruct", api_key="YOUR_API_KEY")
# Initialize Groq model model = ChatGroq(model="meta-llama/llama-4-scout-17b-16e-instruct", api_key="YOUR_API_KEY")
# Initialize Groq model
model = ChatGroq(model="meta-llama/llama-4-scout-17b-16e-instruct", api_key="YOUR_API_KEY")

第 3 步:配置MCP伺服器

我們在這裡使用 StdioServerParameters,並直接使用已安裝的 Markitdown MCP 軟體包

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
server_params = StdioServerParameters(
command="markitdown-mcp",
args=[] # No additional arguments needed for STDIO mode
)
server_params = StdioServerParameters( command="markitdown-mcp", args=[] # No additional arguments needed for STDIO mode )
server_params = StdioServerParameters(
   command="markitdown-mcp",
   args=[]  # No additional arguments needed for STDIO mode
)

第 4 步:現在,定義非同步函式

load_mcp_tools 提供了 LangChain 與 Markitdown MCP 互動的函式。然後建立 ReAct 代理,並使用模型和 MCP 工具。程式碼會為 PDF 建立 file_uri,併傳送提示,要求代理使用 MCP 轉換檔案。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
async def run_conversion(pdf_path: str):
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
print("MCP Session Initialized.")
# Load available tools
tools = await load_mcp_tools(session)
print(f"Loaded Tools: {[tool.name for tool in tools]}")
# Create ReAct agent
agent = create_react_agent(model, tools)
print("ReAct Agent Created.")
# Prepare file URI (convert local path to file:// URI)
file_uri = f"file://{pdf_path}"
# Invoke agent with conversion request
response = await agent.ainvoke({
"messages": [("user", f"Convert {file_uri} to markdown using Markitdown MCP just return the output from MCP server")]
})
# Return the last message content
return response["messages"][-1].content
async def run_conversion(pdf_path: str): async with stdio_client(server_params) as (read, write): async with ClientSession(read, write) as session: await session.initialize() print("MCP Session Initialized.") # Load available tools tools = await load_mcp_tools(session) print(f"Loaded Tools: {[tool.name for tool in tools]}") # Create ReAct agent agent = create_react_agent(model, tools) print("ReAct Agent Created.") # Prepare file URI (convert local path to file:// URI) file_uri = f"file://{pdf_path}" # Invoke agent with conversion request response = await agent.ainvoke({ "messages": [("user", f"Convert {file_uri} to markdown using Markitdown MCP just return the output from MCP server")] }) # Return the last message content return response["messages"][-1].content
async def run_conversion(pdf_path: str):
   async with stdio_client(server_params) as (read, write):
       async with ClientSession(read, write) as session:
           await session.initialize()
           print("MCP Session Initialized.")
           # Load available tools
           tools = await load_mcp_tools(session)
           print(f"Loaded Tools: {[tool.name for tool in tools]}")
           # Create ReAct agent
           agent = create_react_agent(model, tools)
           print("ReAct Agent Created.")
           # Prepare file URI (convert local path to file:// URI)
           file_uri = f"file://{pdf_path}"
           # Invoke agent with conversion request
           response = await agent.ainvoke({
               "messages": [("user", f"Convert {file_uri} to markdown using Markitdown MCP just return the output from MCP server")]
           })
           # Return the last message content
           return response["messages"][-1].content

第 5 步:該程式碼呼叫run_conversion函式

我們正在呼叫並從響應中提取 Markdown。它將內容儲存到 pdf.md,最後在終端中列印輸出。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
if __name__ == "__main__":
pdf_path = "/home/harsh/Downloads/LLM Evaluation.pptx.pdf" # Use absolute path
result = asyncio.run(run_conversion(pdf_path))
with open("pdf.md", 'w') as f:
f.write(result)
print("\nMarkdown Conversion Result:")
print(result)
if __name__ == "__main__": pdf_path = "/home/harsh/Downloads/LLM Evaluation.pptx.pdf" # Use absolute path result = asyncio.run(run_conversion(pdf_path)) with open("pdf.md", 'w') as f: f.write(result) print("\nMarkdown Conversion Result:") print(result)
if __name__ == "__main__":
   pdf_path = "/home/harsh/Downloads/LLM Evaluation.pptx.pdf"  # Use absolute path
   result = asyncio.run(run_conversion(pdf_path))
   with open("pdf.md", 'w') as f:
      f.write(result)
   print("\nMarkdown Conversion Result:")
   print(result)

輸出

呼叫run_conversion函式

完整程式碼

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from langchain_mcp_adapters.tools import load_mcp_tools
from langgraph.prebuilt import create_react_agent
import asyncio
from langchain_groq import ChatGroq
# Initialize Groq model
model = ChatGroq(model="meta-llama/llama-4-scout-17b-16e-instruct", api_key="")
# Configure MCP server
server_params = StdioServerParameters(
command="markitdown-mcp",
args=[] # No additional arguments needed for STDIO mode
)
async def run_conversion(pdf_path: str):
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
print("MCP Session Initialized.")
# Load available tools
tools = await load_mcp_tools(session)
print(f"Loaded Tools: {[tool.name for tool in tools]}")
# Create ReAct agent
agent = create_react_agent(model, tools)
print("ReAct Agent Created.")
# Prepare file URI (convert local path to file:// URI)
file_uri = f"file://{pdf_path}"
# Invoke agent with conversion request
response = await agent.ainvoke({
"messages": [("user", f"Convert {file_uri} to markdown using Markitdown MCP just retrun the output from MCP server")]
})
# Return the last message content
return response["messages"][-1].content
if __name__ == "__main__":
pdf_path = "/home/harsh/Downloads/LLM Evaluation.pdf" # Use absolute path
result = asyncio.run(run_conversion(pdf_path))
with open("pdf.md", 'w') as f:
f.write(result)
print("\nMarkdown Conversion Result:")
print(result)
from mcp import ClientSession, StdioServerParameters from mcp.client.stdio import stdio_client from langchain_mcp_adapters.tools import load_mcp_tools from langgraph.prebuilt import create_react_agent import asyncio from langchain_groq import ChatGroq # Initialize Groq model model = ChatGroq(model="meta-llama/llama-4-scout-17b-16e-instruct", api_key="") # Configure MCP server server_params = StdioServerParameters( command="markitdown-mcp", args=[] # No additional arguments needed for STDIO mode ) async def run_conversion(pdf_path: str): async with stdio_client(server_params) as (read, write): async with ClientSession(read, write) as session: await session.initialize() print("MCP Session Initialized.") # Load available tools tools = await load_mcp_tools(session) print(f"Loaded Tools: {[tool.name for tool in tools]}") # Create ReAct agent agent = create_react_agent(model, tools) print("ReAct Agent Created.") # Prepare file URI (convert local path to file:// URI) file_uri = f"file://{pdf_path}" # Invoke agent with conversion request response = await agent.ainvoke({ "messages": [("user", f"Convert {file_uri} to markdown using Markitdown MCP just retrun the output from MCP server")] }) # Return the last message content return response["messages"][-1].content if __name__ == "__main__": pdf_path = "/home/harsh/Downloads/LLM Evaluation.pdf" # Use absolute path result = asyncio.run(run_conversion(pdf_path)) with open("pdf.md", 'w') as f: f.write(result) print("\nMarkdown Conversion Result:") print(result)
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from langchain_mcp_adapters.tools import load_mcp_tools
from langgraph.prebuilt import create_react_agent
import asyncio
from langchain_groq import ChatGroq
# Initialize Groq model
model = ChatGroq(model="meta-llama/llama-4-scout-17b-16e-instruct", api_key="")
# Configure MCP server
server_params = StdioServerParameters(
   command="markitdown-mcp", 
   args=[]  # No additional arguments needed for STDIO mode
)
async def run_conversion(pdf_path: str):
   async with stdio_client(server_params) as (read, write):
       async with ClientSession(read, write) as session:
           await session.initialize()
           print("MCP Session Initialized.")
           # Load available tools
           tools = await load_mcp_tools(session)
           print(f"Loaded Tools: {[tool.name for tool in tools]}")
           # Create ReAct agent
           agent = create_react_agent(model, tools)
           print("ReAct Agent Created.")
           # Prepare file URI (convert local path to file:// URI)
           file_uri = f"file://{pdf_path}"
           # Invoke agent with conversion request
           response = await agent.ainvoke({
               "messages": [("user", f"Convert {file_uri} to markdown using Markitdown MCP just retrun the output from MCP server")]
           })
           # Return the last message content
           return response["messages"][-1].content
if __name__ == "__main__":
   pdf_path = "/home/harsh/Downloads/LLM Evaluation.pdf"  # Use absolute path
   result = asyncio.run(run_conversion(pdf_path))
   with open("pdf.md", 'w') as f:
       f.write(result)
   print("\nMarkdown Conversion Result:")
   print(result)

檢查輸出

指令碼會生成一個 pdf.md 檔案。該檔案包含輸入 PDF 的 Markdown 版本。轉換質量取決於原始文件的結構。Markitdown MCP 通常會保留以下元素:

  • 標題(不同級別)
  • 段落文字
  • 列表(專案和編號)
  • 表格(轉換為 Markdown 語法)
  • 程式碼塊

輸出

標題、內容以及 Markdown 格式的普通文字

在輸出中,我們可以看到它成功地檢索到了標題、內容以及 Markdown 格式的普通文字。

因此,執行本地伺服器進行測試有助於評估不同的文件型別。

LLM管道中的實際用例

整合 Markitdown MCP 可以改進多個人工智慧工作流程:

  • 知識庫構建:將文件轉換為 Markdown。將這些內容納入知識庫或 RAG 系統。
  • LLM 內容準備:將原始檔轉換為 Markdown。為 LLM 總結或分析任務準備一致的輸入內容。
  • 文件資料提取:將帶表格的文件轉換為 Markdown。這可簡化結構化資料的解析。
  • 文件自動化:生成技術手冊。將 Word 文件等原始檔轉換為 Markdown,用於靜態網站生成器。

小結

Markitdown MCP 提供了一種功能強大、基於伺服器的文件轉換方法。它能處理多種格式。它能生成結構化的 Markdown 輸出。將其與 LLM 整合可實現文件處理任務的自動化。這種方法支援可擴充套件的文件實踐。使用伺服器進行測試可直接進行評估。透過在這些工作流程中的實際應用,我們可以更好地理解 MarkItDown 的MCP

請訪問 Markitdown MCP GitHub 程式碼倉庫瞭解更多資訊。

常見問題

Q1. Markitdown MCP 的主要功能是什麼?

答:Markitdown MCP 可將 PDF 和 Word 等文件轉換為結構化的 Markdown。它使用基於伺服器的協議來完成這項任務。

Q2. Markitdown MCP 伺服器可以處理哪些檔案格式?

答:伺服器可處理 PDF、DOCX、PPTX 和 HTML 檔案。根據核心庫的不同,還可能支援其他格式。

Q3. LangChain 如何使用 Markitdown MCP?

答:LangChain 使用特殊工具與伺服器通訊。代理可以透過該伺服器請求文件轉換。

Q4. Markitdown MCP 是開源的嗎?

回答:是的,它是微軟的開源軟體。使用者需承擔任何伺服器託管費用。

Q5. 我可以執行 Markitdown MCP 伺服器進行測試嗎?

回答:可以,測試伺服器可以在本地執行。使用 STDIO 或 SSE 模式進行開發和評估。

評論留言