載入中
載入中

MCP 伺服器中的提示(prompts)讓您可以定義預先建置的高品質指令,供客戶端使用,而不必從頭撰寫自己的提示。您可以將它們想像成精心製作的範本,比使用者自己想出的內容能帶來更好的結果。

為什麼要使用提示?

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

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

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

提示的運作方式

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

一個名為「format」的提示所在的 MCP 伺服器,其 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 伺服器所涵蓋領域中的專業知識。