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.listAgents();
Returns a record of agent IDs to their serialized agent configurations.
Working with a Specific AgentDirect link to Working with a Specific Agent
Get an instance of a specific agent by its ID:
export const myAgent = new Agent({
id: "my-agent",
// ...
});
const agent = mastraClient.getAgent("my-agent");
Agent MethodsDirect link to Agent Methods
details()Direct link to details()
Retrieve detailed information about an agent:
const details = await agent.details();
generate()Direct link to generate()
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
});
You can also use the simplified string format:
const response = await agent.generate("Hello, how are you?", {
threadId: "thread-1",
resourceId: "resource-1",
});
stream()Direct link to stream()
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 use the simplified string format:
const response = await agent.stream("Tell me a story", {
threadId: "thread-1",
clientTools: { colorChangeTool },
});
response.processDataStream({
onChunk: async (chunk) => {
if (chunk.type === "text-delta") {
console.log(chunk.payload.text);
}
},
});
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));
}
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 toAISdkStream:
import { createUIMessageStream } from "ai";
import { toAISdkStream } 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 toAISdkStream(
chunkStream as unknown as MastraModelOutput,
{ from: "agent" },
)) {
writer.write(part);
}
},
});
for await (const part of uiMessageStream) {
console.log(part);
}
getTool()Direct link to getTool()
Retrieve information about a specific tool available to the agent:
const tool = await agent.getTool("tool-id");
executeTool()Direct link to executeTool()
Execute a specific tool for the agent:
const result = await agent.executeTool("tool-id", {
data: { input: "value" },
});
network()Direct link to network()
Stream responses from an agent network for multi-agent interactions:
const response = await agent.network({
messages: [
{
role: "user",
content: "Research this topic and write a summary",
},
],
});
response.processDataStream({
onChunk: async (chunk) => {
console.log(chunk);
},
});
approveToolCall()Direct link to approveToolCall()
Approve a pending tool call that requires human confirmation:
const response = await agent.approveToolCall({
runId: "run-123",
toolCallId: "tool-call-456",
});
response.processDataStream({
onChunk: async (chunk) => {
console.log(chunk);
},
});
declineToolCall()Direct link to declineToolCall()
Decline a pending tool call that requires human confirmation:
const response = await agent.declineToolCall({
runId: "run-123",
toolCallId: "tool-call-456",
});
response.processDataStream({
onChunk: async (chunk) => {
console.log(chunk);
},
});
Client ToolsDirect link to Client Tools
Client-side tools allow you to execute custom functions on the client side when the agent requests them.
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 (inputData) => {
document.body.style.backgroundColor = inputData.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)}`,
);
}
},
});
Stored AgentsDirect link to Stored Agents
Stored agents are agent configurations stored in a database that can be created, updated, and deleted at runtime. They reference primitives (tools, workflows, other agents, memory, scorers) by key, which are resolved from the Mastra registry when the agent is instantiated.
listStoredAgents()Direct link to listStoredAgents()
Retrieve a paginated list of all stored agents:
const result = await mastraClient.listStoredAgents();
console.log(result.agents); // Array of stored agents
console.log(result.total); // Total count
With pagination and ordering:
const result = await mastraClient.listStoredAgents({
page: 0,
perPage: 20,
orderBy: {
field: "createdAt",
direction: "DESC",
},
});
createStoredAgent()Direct link to createStoredAgent()
Create a new stored agent:
const agent = await mastraClient.createStoredAgent({
id: "my-agent",
name: "My Assistant",
instructions: "You are a helpful assistant.",
model: {
provider: "openai",
name: "gpt-4",
},
});
With all options:
const agent = await mastraClient.createStoredAgent({
id: "full-agent",
name: "Full Agent",
description: "A fully configured agent",
instructions: "You are a helpful assistant.",
model: {
provider: "openai",
name: "gpt-4",
},
tools: ["calculator", "weather"],
workflows: ["data-processing"],
agents: ["sub-agent-1"],
memory: "my-memory",
scorers: {
"quality-scorer": {
sampling: { type: "ratio", rate: 0.1 },
},
},
defaultOptions: {
maxSteps: 10,
},
metadata: {
version: "1.0",
team: "engineering",
},
});
getStoredAgent()Direct link to getStoredAgent()
Get an instance of a specific stored agent:
const storedAgent = mastraClient.getStoredAgent("my-agent");
Stored Agent MethodsDirect link to Stored Agent Methods
details()Direct link to details()
Retrieve the stored agent configuration:
const details = await storedAgent.details();
console.log(details.name);
console.log(details.instructions);
console.log(details.model);
update()Direct link to update()
Update specific fields of a stored agent. All fields are optional:
const updated = await storedAgent.update({
name: "Updated Agent Name",
instructions: "New instructions for the agent.",
});
// Update just the tools
await storedAgent.update({
tools: ["new-tool-1", "new-tool-2"],
});
// Update metadata
await storedAgent.update({
metadata: {
version: "2.0",
lastModifiedBy: "admin",
},
});
delete()Direct link to delete()
Delete a stored agent:
const result = await storedAgent.delete();
console.log(result.success); // true