載入中

MCP 伺服器中的提示讓您能夠定義預先建立、高品質的指令,客戶端可以直接使用這些指令,而不必從頭開始撰寫自己的提示。可以將它們視為精心製作的範本,比使用者自行想出的內容能帶來更好的結果。

為什麼要使用提示?

假設您想讓 Claude 將文件重新格式化為 markdown。使用者可以直接輸入「將 report.pdf 轉換為 markdown」,這樣也能正常運作。但如果使用一個經過充分測試、包含格式、結構和輸出要求等具體指示的提示,他們很可能會得到更好的結果。

使用者的單行提示旁邊是一個經過測試的提示,該提示設定了文件轉換角色、格式規則和分析標籤。

關鍵的洞察在於,雖然使用者可以自行完成這些任務,但當他們使用由 MCP 伺服器作者精心開發和測試過的提示時,會獲得更一致、更高品質的結果。

提示如何運作

提示定義了一組使用者和助理訊息,客戶端可以直接使用這些訊息。當客戶端請求一個提示時,您的伺服器會回傳一份訊息清單,這些訊息可以直接傳送給 Claude。

一個 MCP 伺服器包含一個名為「format」的提示,其 format_document 函式回傳一份訊息清單,如下所示。

基本結構如下所示:

  • 使用 @mcp.prompt() 裝飾器定義提示
  • 為每個提示新增名稱和描述
  • 回傳一份構成完整提示的訊息清單
  • 這些提示應該是高品質、經過充分測試,並且與您的 MCP 伺服器的用途相關

建立格式化指令

以下說明如何實作一個文件格式化提示。首先,您需要匯入基礎訊息類型:

python
from mcp.server.fastmcp.prompts import base

接著定義您的提示函式:

python
@mcp.prompt(
    name="format",
    description="Rewrites the contents of the document in Markdown format."
)
def format_document(
    doc_id: str = Field(description="Id of the document to format")
) -> list[base.Message]:
    prompt = f"""
Your goal is to reformat a document to be written with markdown syntax.

The id of the document you need to reformat is:

{doc_id}


Add in headers, bullet points, tables, etc as necessary. Feel free to add in extra formatting.
Use the 'edit_document' tool to edit the document. After the document has been reformatted...
"""
    
    return [
        base.UserMessage(prompt)
    ]

測試您的提示

您可以使用 MCP Inspector 來測試提示。導覽至 Prompts 區段,選擇您的提示,並提供任何必要的參數。Inspector 會顯示將傳送給 Claude 的生成訊息。

MCP Inspector 顯示「format」提示,doc_id 為 outlook.pdf,以及 Get Prompt 結果,一則角色為「user」的訊息。

這讓您能夠在實際應用程式中使用之前,驗證您的提示是否正確地插入變數,並產生預期的訊息結構。

最佳實踐

在為您的 MCP 伺服器建立提示時:

  • 專注於對您伺服器用途至關重要的任務
  • 撰寫詳細、具體的指示,而非模糊的要求
  • 使用不同的輸入徹底測試您的提示
  • 包含清楚的描述,讓使用者了解每個提示的作用
  • 考慮提示將如何與您伺服器的工具和資源搭配運作

請記住,提示的目的是提供使用者自己難以輕易獲得的價值——它們應該代表您在 MCP 伺服器所涵蓋領域中的專業知識。