

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 工具定義
<a name="mcp-tool-strategy-definitions"></a>

當 LLM 收到無法直接處理的請求時，將會檢閱可用的工具，以協助完成請求。LLM 會根據其對所提供工具的名稱和描述的語意理解，以及提示中提供的任何指示來選取工具。然後，它會根據定義的輸入結構描述建立輸入，並根據輸出結構描述預期輸出。因此，建立描述性工具定義和經過驗證的輸入和輸出結構描述，對於協助 LLM 有效選取工具至關重要。建立本文件通常有兩種方法：工具規格方法和文件方法。

## 工具規格方法
<a name="mcp-tool-strategy-definitions-spec-approach"></a>

建議的方法是在定義[工具時直接遵循 MCP 工具規格](https://modelcontextprotocol.io/specification/2025-06-18/server/tools#tool)。以下範例使用 [Strands Agent](https://strandsagents.com/docs/user-guide/quickstart/overview/) 工具裝飾項目顯示：

```
@tool(
  name = "search_website",
  description = "This tool searches the provided website for semantic matches to the query provided",
  inputSchema = {
    "json": {
      "type": "object",
      "properties": {
        "url": {
          "type": "string",
          "description": "The url of the website to load and search."
        },
        "query": {
          "type": "string",
          "description": "The content you want to try and match in the website."
      }
    },
    "required": ["url", "query"]
  },
  outputSchema = {
    "json": {
      "type": "object",
      "properties": {
      "results": {
          "type": "array",
          "items": {
            "type": "string" 
          }
        }
      }
    }
  }
)
def search_website:
  …
```

使用標準欄位，例如 `name`、`inputSchema`、 `description`和 ，`outputSchema`確保每個工具都有 LLM 和人類都可以理解的一致文件。每個工具都應至少定義這些欄位，並選擇性地提供標題和註釋，這些是工具行為的選用提示。盡可能使用參數值的列舉，讓 LLM 可以輕鬆選取正確的選項。列舉最適合無限集，例如狀態或優先順序值，但不適用於自由格式文字、動態值、任意數字或資源識別符。在這些情況下，請改為提供明確的描述和範例。同時盡可能包含預設值，以便 LLM 不必猜測正確的選項。請記住，工具定義會在每次調用時包含在 LLM 提示中，並會耗用內容時段空間以及系統指示和對話歷史記錄。

## Docstring 方法
<a name="mcp-tool-strategy-definitions-docstring-approach"></a>

如果您以 Python 撰寫工具，另一種方法是使用 docstring 來提供工具的描述、用量和輸出。以下是此方法的範例：

```
def search_website(url: str, query: str) -> list:
    
    """
    This tool loads the specified website and then attempts to find content that matches the provided query through semantic search. It provides back a list of strings that are the sentences that match the query. 
    Args:
      url: the website url to load
      query: the content you want to semantically match in the website
    """
```

文件字串不會強制執行結構描述或標準化格式。根據工具開發人員選擇記錄每個工具的方式，使用此方法可能會產生不一致的結果。如果您遵循此方法，則定義和強制執行整個組織的標準至關重要。

## MCP 工具定義的最佳實務
<a name="mcp-tool-strategy-definitions-best-practices"></a>
+ **遵循 MCP 工具規格** – 為每個工具提供 `name`、`inputSchema`、 `description`和 `outputSchema` 欄位。對於 Python 實作，請使用 [Pydantic 模型](https://docs.pydantic.dev/latest/concepts/models/)透過欄位描述提供內嵌文件、自動類型驗證，以及透過列舉提供限制值。這可讓結構描述自我記錄，並改善 LLM 對有效參數選項的了解。
+ 將**描述撰寫為提示** – 工具描述是指導 LLM 決策的說明。包含工具用途 （工具的功能）、使用時機 （使用者意圖模式或案例）、輸出內容 （輸出的用途）、參數和錯誤條件的基本元件。
+ **提供具體範例** – 包含工作流程範例與實際值是引導 LLMs正確工具用量的最有效方法。
+ **明確記錄相依性** – 包含先決條件、編號序列、狀態變更和後續動作。