2

工具:createTool + 挂载 Agent 再 generate

按官方 Tools 文档用 createTool 定义天气工具(Zod schema + execute),挂到 Agent.tools,再 generate 触发工具调用并读出结果。

图文23 分钟Mastra 官方文档 ↗

课程目录2 / 2

学习位置仅保存在当前浏览器,有效期 180 天。

01 / 图文教材

图文讲义

来源:Mastra · ToolsGet startedcreateTool 参考。本讲义为中文跟做整理,非原文搬运。

你将得到什么

  • 一个用 createTool 定义的工具(含 Zod inputSchema / outputSchemaexecute
  • Agent 的 tools: { weatherTool } 挂载
  • 一次会调用工具的 generate(或能用 CLI 单独测工具)

官方硬性约定(Get started / Tools 页):

  1. 必须createTool();纯对象工具定义会静默不执行。
  2. execute 现行唯一签名execute(inputData, context)。第一参数是经 inputSchema 校验的输入;第二参数由运行时注入(含 requestContexttracingContextabortSignal 等),不用时可省略形参。
  3. 其它旧签名过时,不要照抄。

步骤 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;idget-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 单测通过

延伸阅读(官方)

  • 多工具、子 Agent、Workflow 作工具:Tools
  • MCP 连接:MCP
  • 模型总表:Models

恭喜:你已按官方路径完成 Mastra 脚手架、Agent 与 createTool 首调。