Skip to content

Chapter 6 · Agent and Tool Integration in Practice ​

Chapter goals: Combine multiple tools to build a practical travel planning assistant, master tool selection tuning, and control multi-step reasoning.

6.1 Project Goal ​

Build an assistant that can answer "how to plan a trip from Beijing to Shanghai" — it needs to combine two tools:

  • getWeatherTool: check destination weather (decides what to wear, where to go);
  • calculatorTool: precisely calculate the budget (LLM arithmetic is unreliable, must be offloaded).

6.2 Defining the Second Tool: Calculator ​

typescript
// src/mastra/tools/calculator-tool.ts
import { createTool } from '@mastra/core/tools';
import { z } from 'zod';

export const calculatorTool = createTool({
  id: 'calculator',
  description: 'Execute precise arithmetic operations; input a valid arithmetic expression',
  inputSchema: z.object({
    expression: z.string().describe('Arithmetic expression, e.g. "(1200 + 350) * 2"'),
  }),
  outputSchema: z.object({
    result: z.number(),
  }),
  execute: async ({ context }) => {
    const { expression } = context;
    // Safe whitelist validation: only allow digits and operators to prevent injection
    if (!/^[\d+\-*/().\s]+$/.test(expression)) {
      throw new Error('Invalid expression');
    }
    // Evaluate using Function constructor (expression has passed whitelist)
    const result = new Function(`return (${expression})`)() as number;
    return { result };
  },
});

Note the whitelist regex — any code that splices model output directly into an evaluator must have this layer of defense.

6.3 Combined Registration and Invocation ​

typescript
// src/mastra/agents/trip-agent.ts —— dual-tool Agent
import { Agent } from '@mastra/core/agent';
import { weatherTool } from '../tools/weather-tool';
import { calculatorTool } from '../tools/calculator-tool';

export const tripAgent = new Agent({
  id: 'trip-planner',
  name: 'Trip Planner',
  instructions: `
    You are a travel planning assistant.
    - Use getWeather to check destination conditions.
    - ALWAYS use the calculator for any arithmetic (never compute in your head).
    - Present plans as: Weather Overview / Itinerary Suggestions / Budget Breakdown.`,
  model: 'openai/gpt-5-mini',
  tools: {
    weatherTool,
    calculatorTool,
  },
});
typescript
// Invocation: a single request may trigger multiple tools across multiple rounds
const res = await tripAgent.generate(
  'Plan a one-day trip to Shanghai for this Saturday; budget 2000 RMB for two, including tickets, meals, and transport.',
);
console.log(res.text);

6.4 Observing the Multi-Step Reasoning Process ​

Behind a single question lies a complete agentic loop:

text
User: Plan a one-day trip to Shanghai…

├─ [step 1] tool-call: weatherTool({ city: "Shanghai" })
 │   └─ { temperature: 22, condition: "Cloudy" }
 ├─ [step 2] tool-call: calculatorTool({ expression: "150*2 + 400 + 300*2" })
 │   └─ { result: 1300 }
 └─ [final]   Weather: Cloudy 22°C… Budget: Tickets 300×2 + Transport 400 + Meals 300×2 = 1300 RMB…

In Studio's chat panel you can expand each tool call step-by-step — this is the "model decides → executes → feeds back → decides again" loop.

6.5 Tool Selection Tuning Tips ​

When the model doesn't call or misuses tools,排查 in this order:

SymptomCauseFix
Never calls toolsdescription too vagueClarify trigger conditions: "use when user asks X"
Calls B when A was neededTwo tools' descriptions overlap semanticallyClearly delineate boundaries with mutually exclusive descriptions
Params always wrongMissing .describe() or constraints too looseAdd parameter descriptions, tighten Zod validation
Infinite tool call loopNo termination signalRequire "answer once result is obtained" in instructions
typescript
// Read structured tool call records from the response (for audit and debugging)
for (const msg of res.response.messages ?? []) {
  if (msg.role === 'tool') {
    console.log('Tool call:', JSON.stringify(msg.content));
  }
}

Cost note

Each tool call round is a new LLM request. More complex tasks consume more tokens — always set a step上限 in production.

6.6 Chapter Summary ​

  • Multi-tool Agent = a collection of specialized tools + clearly divided instructions;
  • Tasks involving calculation must offload to tools; never trust LLM mental math;
  • Whitelist validation is the security baseline for any dynamic-evaluation tool;
  • Tool behavior issues should be排查 first from description and schema.

🧪 随堂测验

点击你认为正确的选项。答错时会展示正确答案与原因解析。

1. When asking an LLM to calculate a total order amount, the correct approach is?

2. The model never calls your defined tool. What should you check first?

3. For an evaluation-style tool that executes user-input expressions, what safety measure is essential?

4. Regarding the cost of multi-step tool calls, which understanding is correct?

🛠️ Hands-On Exercises ​

  1. Add a third tool currencyConvert (exchange rate conversion) to tripAgent; require instructions to display budget in both RMB and USD.
  2. Change weatherTool's description to the vague "process data"; compare tool-call accuracy before and after the change.
  3. Send 10 identical questions in Studio; stat the calculatorTool call success rate.

Next: Chapter 7 · Workflow Basics and .then()