工具
使用 Zod 校验和类型安全创建 MCP 工具。
什么是工具?
工具是 AI 助手可以调用来执行操作或检索信息的函数。它们接收经过验证的输入参数,并返回结构化结果。
搭建一个新的 MCP 工具
基础工具定义
下面是一个简单的工具,会回显一条消息:
server/mcp/tools/echo.ts
import { z } from 'zod'
import { defineMcpTool } from '@nuxtjs/mcp-toolkit/server'
export default defineMcpTool({
name: 'echo',
description: '回显一条消息',
inputSchema: {
message: z.string().describe('要回显的消息'),
},
handler: async ({ message }) => `回显:${message}`,
})
自动生成的名称和标题
你可以省略 name 和 title——它们将从文件名自动生成:
server/mcp/tools/list-documentation.ts
import { defineMcpTool } from '@nuxtjs/mcp-toolkit/server'
export default defineMcpTool({
// name 和 title 会根据文件名自动生成:
// name: 'list-documentation'
// title: 'List Documentation'
description: '列出所有文档文件',
handler: async () => {
// ...
},
})
文件名 list-documentation.ts 会自动变为:
name:list-documentation(kebab-case)title:List Documentation(标题式大小写)
你仍然可以显式提供 name 或 title 来覆盖自动生成的值。
工具结构
一个工具定义由以下部分组成:
export default defineMcpTool({
name: 'tool-name', // 唯一标识符(可选 - 将从文件名自动生成)
inputSchema: { ... }, // 用于输入校验的 Zod schema
handler: async (args) => {
return 'result' // string、number、boolean、object 或 CallToolResult
},
})
export default defineMcpTool({
name: 'tool-name', // 可选 - 将从文件名自动生成
title: 'Tool Title', // 可选 - 将从文件名自动生成
description: '工具描述', // 工具的作用
inputSchema: { ... }, // 可选 - 用于输入校验的 Zod schema
outputSchema: { ... }, // 用于结构化输出的 Zod schema
annotations: { ... }, // 面向客户端的行为提示
inputExamples: [{ ... }], // 具体的使用示例
handler: async (args) => { ... },
})
进一步探索
在你编写了一些工具之后,可以继续扩展: