第 2 课
工具:createTool + 挂载 Agent 再 generate
按官方 Tools 文档用 createTool 定义天气工具(Zod schema + execute),挂到 Agent.tools,再 generate 触发工具调用并读出结果。
课程目录第 2 / 2 课
学习位置仅保存在当前浏览器,有效期 180 天。
图文讲义
来源:Mastra · Tools、Get started、createTool 参考。本讲义为中文跟做整理,非原文搬运。
你将得到什么
- 一个用
createTool定义的工具(含 ZodinputSchema/outputSchema与execute) - Agent 的
tools: { weatherTool }挂载 - 一次会调用工具的
generate(或能用 CLI 单独测工具)
官方硬性约定(Get started / Tools 页):
- 必须用
createTool();纯对象工具定义会静默不执行。 execute现行唯一签名:execute(inputData, context)。第一参数是经inputSchema校验的输入;第二参数由运行时注入(含requestContext、tracingContext、abortSignal等),不用时可省略形参。- 其它旧签名过时,不要照抄。
步骤 1:创建工具文件
// src/mastra/tools/weather-tool.ts
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'
export const weatherTool = createTool({
id: 'get-weather',
description: 'Get current weather for a location',
inputSchema: z.object({
location: z.string().describe('City name'),
}),
outputSchema: z.object({
location: z.string(),
temperatureCelsius: z.number(),
conditions: z.string(),
}),
// 第一参数:校验后的输入;可按字段解构
execute: async ({ location }) => {
return {
location,
temperatureCelsius: 21,
conditions: 'sunny',
}
},
})
说明:上面是官方 Get started 的最小可运行示例(固定返回)。若要打真实 HTTP,Tools 文档示例用 wttr.in,并建议在 execute 第二参数解构 abortSignal:
execute: async ({ location }, { abortSignal }) => {
const response = await fetch(`https://wttr.in/${encodeURIComponent(location)}?format=j1`, {
signal: abortSignal,
})
const data = await response.json()
return {
location,
temperatureCelsius: Number(data.current_condition[0].temp_C),
conditions: data.current_condition[0].weatherDesc[0].value,
}
}
本课验收用最小示例即可;有网络时可换成 wttr 版本。
对照结果:文件可被 import;id 为 get-weather。
步骤 2:把工具挂到 Agent
更新 src/mastra/agents/weather-agent.ts(与官方一致):
import { Agent } from '@mastra/core/agent'
import { weatherTool } from '../tools/weather-tool.ts'
export const weatherAgent = new Agent({
id: 'weather-agent',
name: 'Weather Agent',
instructions: `
You are a helpful weather assistant that provides accurate weather information.
Your primary function is to help users get weather details for specific locations. When responding:
- Include relevant details like humidity, wind conditions, and precipitation
- Keep responses concise but informative
Use the weatherTool to fetch current weather data.
`,
model: 'openai/gpt-5.6-sol',
tools: { weatherTool },
})
要点:
- 在
instructions里点名工具用途,帮助模型决定何时调用。 tools对象的 key 会出现在流式事件的toolName里(官方说明:key 决定toolName,不是id字段本身)。
确认 src/mastra/index.ts 仍注册该 Agent(第 1 课已完成)。
步骤 3:再次 generate
确保 Key 仍在环境中:
export OPENAI_API_KEY="YOUR_API_KEY"
// run.mjs
import { mastra } from './src/mastra/index.ts'
const agent = mastra.getAgentById('weather-agent')
const response = await agent.generate('Weather in SF')
console.log(response.text)
node run.mjs
对照结果:
| 项 | 期望 |
|---|---|
| 文本 | 回答应体现工具结果(最小示例下温度约 21°C、sunny;措辞由模型组织) |
| 工具 | 若开了 tracing/日志,应能看到对 weatherTool / get-weather 的调用 |
| 错误 | 不应再是「工具未执行」的静默失败;若完全不调工具,检查 instructions 与 tools 是否挂上 |
步骤 4(可选):单独测工具
官方 Tools 页提示:可在本地 Mastra server 上直接测工具,而不写临时脚本:
npx mastra dev
# 另开终端(需 server 可达):
npx mastra api tool execute weather-tool '{"location":"San Francisco"}'
# 先看 schema:
npx mastra api tool execute --schema
weather-tool 名称以你项目里注册的工具标识为准;CLI 细节见官方 Tools 页。
常见坑
| 现象 | 处理 |
|---|---|
| 工具从不执行 | 确认用了 createTool,不是手写普通对象 |
execute 参数对不上 | 改用 execute(inputData, context);可解构 inputData |
| 401 / 缺 Key | 核对 model 前缀与环境变量名 |
| 想换模型 | 只改 model: 'anthropic/claude-sonnet-4-6' 等官方字符串,并设 ANTHROPIC_API_KEY |
本课检查清单
-
createTool({ id, description, inputSchema, execute })已写好 - Agent
tools: { weatherTool }已挂载,instructions 提到该工具 -
generate('Weather in SF')能跑通并打印文本 - (可选)
mastra api tool execute单测通过
