

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

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

当 LLM 收到无法直接处理的请求时，它将审查可用工具以帮助其完成请求。LLM 根据其对所提供工具名称和描述的语义理解以及提示中提供的任何说明来选择工具。然后，它将根据定义的输入架构创建输入，并根据输出架构期望输出。因此，创建描述性工具定义和经过验证的输入和输出架构对于帮助法学硕士有效选择工具至关重要。创建此文档通常有两种方法：工具规范方法和文档字符串方法。

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

推荐的方法是在定义工具时直接遵循 MCP [工具规范](https://modelcontextprotocol.io/specification/2025-06-18/server/tools#tool)。以下示例是使用 Str [ands 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`、`description``inputSchema`、和`outputSchema`确保每个工具都有一致的文档，法学硕士和人类都能理解。每个工具都应至少定义这些字段，并可选择提供标题和注释，这些都是有关工具行为的可选提示。如果可能，请使用枚举作为参数值，以便 LLM 可以轻松选择正确的选项。枚举最适合有限集，例如状态或优先级值，但不适用于自由格式文本、动态值、任意数字或资源标识符。在这种情况下，请改为提供清晰的描述和示例。还要尽可能包括默认值，这样 LLM 就不必猜测正确的选项是什么。请记住，工具定义包含在每次调用的 LLM 提示符中，会占用上下文窗口空间以及系统指令和对话历史记录。

## 文档字符串方法
<a name="mcp-tool-strategy-definitions-docstring-approach"></a>

如果你用 Python 编写工具，另一种方法是使用文档字符串来提供工具的描述、用法和输出。以下是这种方法的示例：

```
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``description``inputSchema`、、和`outputSchema`字段。对于 Python 实现，使用 [Pydantic 模型](https://docs.pydantic.dev/latest/concepts/models/)通过字段描述、自动类型验证和通过枚举提供约束值来提供内联文档。这使得架构可以自我记录，并提高了 LLM 对有效参数选项的理解。
+ **将描述写成提示** — 工具描述是指导法学硕士决策的说明。包括工具用途（工具的用途）、何时使用（用户意图模式或场景）、输出上下文（输出用途）、参数和错误条件的基本组成部分。
+ **提供具体示例** — 包括带有实际值的工作流程示例是指导法学硕士正确使用工具的最有效方法。
+ **明确记录依赖关系**-包括先决条件、编号序列、状态更改和后续操作。