Agents API
The Agents API provides methods to interact with Mastra AI agents, including generating responses, streaming interactions, and managing agent tools.
Getting All AgentsDirect link to Getting All Agents
Retrieve a list of all available agents:
const agents = await mastraClient.getAgents();
Working with a Specific AgentDirect link to Working with a Specific Agent
Get an instance of a specific agent:
const agent = mastraClient.getAgent("agent-id");
Agent MethodsDirect link to Agent Methods
Get Agent DetailsDirect link to Get Agent Details
Retrieve detailed information about an agent:
const details = await agent.details();
Generate ResponseDirect link to Generate Response
Generate a response from the agent:
const response = await agent.generate({
messages: [
{
role: "user",
content: "Hello, how are you?",
},
],
threadId: "thread-1", // Optional: Thread ID for conversation context
resourceId: "resource-1", // Optional: Resource ID
output: {}, // Optional: Output configuration
});
Stream ResponseDirect link to Stream Response
Stream responses from the agent for real-time interactions:
const response = await agent.stream({
messages: [
{
role: "user",
content: "Tell me a story",
},
],
});
// Process data stream with the processDataStream util
response.processDataStream({
onChunk: async (chunk) => {
console.log(chunk);
},
});
// You can also read from response body directly
const reader = response.body.getReader();
while (true) {
const { done, value } = await reader.read();
if (done) break;
console.log(new TextDecoder().decode(value));
}
Client toolsDirect link to Client tools
Client-side tools allow you to execute custom functions on the client side when the agent requests them.
Basic UsageDirect link to Basic Usage
import { createTool } from "@mastra/client-js";
import { z } from "zod";
const colorChangeTool = createTool({
id: "changeColor",
description: "Changes the background color",
inputSchema: z.object({
color: z.string(),
}),
execute: async ({ context }) => {
document.body.style.backgroundColor = context.color;
return { success: true };
},
});
// Use with generate
const response = await agent.generate({
messages: "Change the background to blue",
clientTools: { colorChangeTool },
});
// Use with stream
const response = await agent.stream({
messages: "Change the background to green",
clientTools: { colorChangeTool },
});
response.processDataStream({
onChunk: async (chunk) => {
if (chunk.type === "text-delta") {
console.log(chunk.payload.text);
} else if (chunk.type === "tool-call") {
console.log(
`calling tool ${chunk.payload.toolName} with args ${JSON.stringify(chunk.payload.args, null, 2)}`,
);
}
},
});
Get Agent ToolDirect link to Get Agent Tool
Retrieve information about a specific tool available to the agent:
const tool = await agent.getTool("tool-id");
Get Agent EvaluationsDirect link to Get Agent Evaluations
Get evaluation results for the agent:
// Get CI evaluations
const evals = await agent.evals();
// Get live evaluations
const liveEvals = await agent.liveEvals();
StreamDirect link to Stream
Stream responses using the enhanced API with improved method signatures. This method provides enhanced capabilities and format flexibility, with support for Mastra's native format.
const response = await agent.stream("Tell me a story", {
threadId: "thread-1",
clientTools: { colorChangeTool },
});
// Process the stream
response.processDataStream({
onChunk: async (chunk) => {
if (chunk.type === "text-delta") {
console.log(chunk.payload.text);
}
},
});
AI SDK compatible formatDirect link to AI SDK compatible format
To stream AI SDK-formatted parts on the client from an agent.stream(...) response, wrap response.processDataStream into a ReadableStream<ChunkType> and use toAISdkFormat:
import { createUIMessageStream } from "ai";
import { toAISdkFormat } from "@mastra/ai-sdk";
import type { ChunkType, MastraModelOutput } from "@mastra/core/stream";
const response = await agent.stream({ messages: "Tell me a story" });
const chunkStream: ReadableStream<ChunkType> = new ReadableStream<ChunkType>({
start(controller) {
response
.processDataStream({
onChunk: async (chunk) => controller.enqueue(chunk as ChunkType),
})
.finally(() => controller.close());
},
});
const uiMessageStream = createUIMessageStream({
execute: async ({ writer }) => {
for await (const part of toAISdkFormat(
chunkStream as unknown as MastraModelOutput,
{ from: "agent" },
)) {
writer.write(part);
}
},
});
for await (const part of uiMessageStream) {
console.log(part);
}
GenerateDirect link to Generate
Generate a response using the enhanced API with improved method signatures and AI SDK v5 compatibility:
const response = await agent.generate("Hello, how are you?", {
threadId: "thread-1",
resourceId: "resource-1",
});