본문으로 건너뛰기

Agent API

Agents API는 응답 생성 및 스트리밍 상호 작용을 포함하여 Mastra AI Agent와 상호 작용하는 방법을 제공합니다. 또한 Agent Tool을 관리하는 방법도 제공합니다.

모든 Agent 가져오기
모든 Agent 가져오기에 대한 직접 링크

사용 가능한 모든 Agent 목록을 검색합니다.

const agents = await mastraClient.listAgents()

Agent ID 레코드를 직렬화된 Agent 구성으로 반환합니다.

특정 Agent와 협력
특정 Agent와 협력에 대한 직접 링크

해당 ID로 특정 Agent의 인스턴스를 가져옵니다.

src/mastra/agents/my-agent.ts
export const myAgent = new Agent({
id: 'my-agent',
})
const agent = mastraClient.getAgent('my-agent')

Agent 방법
Agent 방법에 대한 직접 링크

details()
details에 대한 직접 링크

Agent에 대한 자세한 정보를 검색합니다.

const details = await agent.details()

generate()
generate에 대한 직접 링크

Agent로부터 응답을 생성합니다.

const response = await agent.generate(
[
{
role: 'user',
content: 'Hello, how are you?',
},
],
{
memory: {
thread: 'thread-abc', // Optional: Thread ID for conversation context
resource: 'user-123', // Optional: Resource ID
},
structuredOutput: {}, // Optional: Structured Output configuration
},
)

Memory 옵션과 함께 단순화된 문자열 형식을 사용할 수도 있습니다.

const response = await agent.generate('Hello, how are you?', {
memory: {
thread: 'thread-1',
resource: 'resource-1',
},
})

stream()
stream에 대한 직접 링크

실시간 상호 작용을 위해 Agent의 응답을 스트리밍합니다.

const response = await agent.stream('Tell me a story')

// Process data stream with the processDataStream util
response.processDataStream({
onChunk: async chunk => {
console.log(chunk)
},
})

Memory 옵션과 함께 단순화된 문자열 형식을 사용할 수도 있습니다.

const response = await agent.stream('Tell me a story', {
memory: {
thread: 'thread-1',
resource: 'resource-1',
},
clientTools: { colorChangeTool },
})

response.processDataStream({
onChunk: async chunk => {
if (chunk.type === 'text-delta') {
console.log(chunk.payload.text)
}
},
})

응답 본문에서 직접 읽을 수도 있습니다.

const reader = response.body.getReader()
while (true) {
const { done, value } = await reader.read()
if (done) break
console.log(new TextDecoder().decode(value))
}

AI SDK 호환 형식
AI SDK 호환 형식에 대한 직접 링크

클라이언트에서 agent.stream(...) 응답의 AI SDK 형식 파트를 스트리밍하려면 response.processDataStreamReadableStream<ChunkType>으로 래핑하고 toAISdkStream을 사용하세요.

client-ai-sdk-transform.ts
import { createUIMessageStream } from 'ai'
import { toAISdkStream } from '@mastra/ai-sdk'
import type { ChunkType, MastraModelOutput } from '@mastra/core/stream'

const response = await agent.stream('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)
}

sendMessage()
sendmessage에 대한 직접 링크

사용자가 작성한 입력을 활성 Agent 실행 또는 유휴 Memory 스레드로 보냅니다. 깨어나거나 메시지를 받는 스트림을 클라이언트가 렌더링할 수 있도록 subscribeToThread()와 함께 사용하세요.

const agent = mastraClient.getAgent('support-agent')

const result = await agent.sendMessage({
message: {
contents: 'Also consider the customer note I just added.',
attributes: { sentFrom: 'web' },
},
resourceId: 'user-123',
threadId: 'thread-abc',
})

console.log(result.runId)

message는 문자열, 텍스트/파일 파트 배열 또는 contents, attributes, metadata, providerOptions가 포함된 객체를 허용합니다.

queueMessage()
queuemessage에 대한 직접 링크

다음 스레드 회전을 위해 사용자가 작성한 입력을 대기열에 넣습니다. 스레드가 활성화된 경우 Mastra는 현재 실행이 완료된 후 새 실행을 시작합니다. 스레드가 유휴 상태이면 Mastra는 즉시 실행을 시작합니다.

await agent.queueMessage({
message: 'Also check whether the tests need updates.',
resourceId: 'user-123',
threadId: 'thread-abc',
})

sendSignal()
sendsignal에 대한 직접 링크

활성 Agent 실행 또는 Memory 스레드에 저수준 신호를 보냅니다. 받은편지함 스토리지가 필요하지 않은 반응형 알림이나 알림 형태의 컨텍스트 같은 시스템 생성 컨텍스트에 사용하세요. 알림 내역을 영구적으로 보관하려면 서버 측 Agent.sendNotificationSignal() API를 사용하세요. 사용자가 작성한 입력에는 sendMessage() 또는 queueMessage()를 권장합니다.

const agent = mastraClient.getAgent('support-agent')

const result = await agent.sendSignal({
signal: {
type: 'reactive',
tagName: 'system-reminder',
contents: 'Also consider the latest customer note.',
},
resourceId: 'user-123',
threadId: 'thread-abc',
})

console.log(result.runId)

Mastra가 신호를 전달, 영구 저장, 폐기하거나 신호로부터 깨울지 제어하려면 ifActive.behaviorifIdle.behavior를 사용하세요.

await agent.sendSignal({
signal: { type: 'reactive', tagName: 'system-reminder', contents: 'Store this for later.' },
resourceId: 'user-123',
threadId: 'thread-abc',
ifIdle: {
behavior: 'persist',
},
})

유휴 상태에서 깨어나는 스트림에 Model 설정, Tool 또는 런타임 컨텍스트 같은 옵션이 필요한 경우 ifIdle.streamOptions를 전달하세요.

await agent.sendSignal({
signal: { type: 'reactive', tagName: 'system-reminder', contents: 'Start from this signal.' },
resourceId: 'user-123',
threadId: 'thread-abc',
ifIdle: {
behavior: 'wake',
streamOptions: {
maxSteps: 3,
},
},
})

보고{ accepted: true, runId: string }.

signal:

{ type: 'user' | 'reactive' | 'notification' | string; tagName?: string; contents: string | Array<TextPart | FilePart>; attributes?: Record<string, JSONValue>; metadata?: Record<string, unknown>; providerOptions?: ProviderMetadata }
저수준 신호 페이로드입니다. 의미론적 신호 범주에는 type을 사용하고 Model에 표시되는 XML 태그에는 tagName을 사용하세요. providerOptions는 결과 Prompt 턴에 연결되며 저장된 신호 메시지에 영구 저장됩니다.

runId?:

string
직접 대상으로 지정할 실행 ID입니다.

resourceId?:

string
Memory 스레드의 리소스 ID입니다. 스레드 대상 신호에는 threadId와 함께 사용하세요.

threadId?:

string
대상으로 지정할 스레드 ID입니다. 스레드 대상 신호에는 resourceId와 함께 사용하세요.

ifActive.behavior?:

'deliver' | 'persist' | 'discard'
대상 스레드가 활성 상태일 때의 동작을 제어합니다. 기본값은 deliver입니다.

ifActive.attributes?:

Record<string, string | number | boolean>
대상 스레드가 활성 상태일 때 Mastra가 신호를 수락하면 신호에 병합되는 속성입니다.

ifIdle.behavior?:

'wake' | 'persist' | 'discard'
대상 스레드가 유휴 상태일 때의 동작을 제어합니다. 기본값은 wake입니다.

ifIdle.streamOptions?:

Omit<AgentExecutionOptions, 'messages'>
ifIdle.behaviorwake일 때 시작되는 스트림의 옵션입니다.

ifIdle.attributes?:

Record<string, string | number | boolean>
대상 스레드가 유휴 상태일 때 Mastra가 신호를 수락하면 신호에 병합되는 속성입니다.

subscribeToThread()
subscribetothread에 대한 직접 링크

Memory 스레드의 원시 스트림 청크를 구독합니다. sendMessage(), queueMessage(), sendSignal() 또는 서버 측 알림 전송으로 시작되거나 계속될 수 있는 스레드의 출력을 렌더링할 때 사용하세요.

const agent = mastraClient.getAgent('support-agent')

const subscription = await agent.subscribeToThread({
resourceId: 'user-123',
threadId: 'thread-abc',
})

await subscription.processDataStream({
onChunk: chunk => {
console.log(chunk)
},
reconnect: true,
})

subscribeToThread()는 기본 ResponseprocessDataStream() 도우미를 반환합니다. 이 도우미는 연결이 닫히거나 요청이 중단될 때까지 구독 스트림을 읽습니다. 프록시 유휴 시간 초과 후처럼 전송이 닫히거나 재연결 요청이 실패할 때 다시 구독하려면 reconnect: true를 전달하세요.

resourceId?:

string
Memory 스레드의 리소스 ID입니다.

threadId:

string
구독할 스레드 ID입니다.

processDataStream().reconnect?:

boolean | { maxRetries?: number; delayMs?: number }
구독 스트림이 닫히거나 재연결 요청이 실패한 후 다시 연결합니다. true이면 1초 간격으로 무기한 재시도합니다.

streamUntilIdle()
streamuntilidle에 대한 직접 링크

응답을 스트리밍하고 실행 중에 디스패치된 백그라운드 작업이 완료될 때까지 스트림을 열어 둡니다. 각 작업이 완료될 때마다 서버가 Agent 루프에 다시 진입하므로 LLM은 동일한 호출 안에서 결과에 반응할 수 있습니다. Mastra 인스턴스에서 백그라운드 작업이 활성화되어 있고 Memory 스레드가 있어야 합니다. 그렇지 않으면 일반 stream()을 사용합니다.

const response = await agent.streamUntilIdle('Research solana for me', {
memory: {
thread: 'thread-1',
resource: 'resource-1',
},
maxIdleMs: 5 * 60_000, //optional
})

response.processDataStream({
onChunk: async chunk => {
if (chunk.type === 'background-task-completed') {
console.log('task complete:', chunk.payload.taskId)
}
},
})

resumeStreamUntilIdle()
resumestreamuntilidle에 대한 직접 링크

사용자 지정 데이터로 일시 중단된 Agent 스트림을 재개하고 실행 중에 디스패치된 백그라운드 작업이 완료될 때까지 스트림을 열어 둡니다. Agent 내부의 Workflow 일시 중단 같은 일시 중단 지점 이후에 실행을 계속할 때 사용하세요. Mastra 인스턴스에서 백그라운드 작업이 활성화되어 있고 Memory 스레드가 있어야 합니다. 그렇지 않으면 일반 resumeStream()을 사용합니다.

const response = await agent.resumeStreamUntilIdle(
{ approved: true, selectedOption: 'plan-b' },
{
memory: {
thread: 'thread-1',
resource: 'resource-1',
},
runId: 'run-123',
toolCallId: 'tool-call-456', // optional
maxIdleMs: 5 * 60_000, //optional
},
)

await response.processDataStream({
onChunk: chunk => {
console.log(chunk)
},
})

스트림은 stream()과 동일한 청크 유형과 작업 수명 주기 이벤트용 background-task-* 청크를 방출합니다. 전체 서버 측 API는 Agent.streamUntilIdle()을, 페이로드 구조는 백그라운드 작업 청크를 참조하세요.

getTool()
gettool에 대한 직접 링크

Agent가 사용할 수 있는 특정 Tool에 대한 정보를 검색합니다.

const tool = await agent.getTool('tool-id')

executeTool()
executetool에 대한 직접 링크

Agent에 대한 특정 Tool을 실행합니다.

const result = await agent.executeTool('tool-id', {
data: { input: 'value' },
})

network()
network에 대한 직접 링크

다중 Agent 상호 작용을 위해 Agent 네트워크에서 응답을 스트리밍합니다.

const response = await agent.network('Research this topic and write a summary')

response.processDataStream({
onChunk: async chunk => {
console.log(chunk)
},
})

listSuspendedRuns()
listsuspendedruns에 대한 직접 링크

스토리지에서 Agent의 일시 중단된 실행을 나열합니다. 여기에는 Tool 호출 승인을 기다리는 실행이나 일시 중단된 Tool에서 실행 중인 항목이 포함됩니다. 조회가 스토리지 기반이므로 서버를 다시 시작한 후에도 여러 서버 인스턴스에서 작동합니다. 반환된 runIdapproveToolCall(), declineToolCall() 또는 resumeStream()에 전달하세요.

const { runs, total } = await agent.listSuspendedRuns({
threadId: 'thread-456',
resourceId: 'user-123',
})

if (runs[0]) {
console.log(runs[0].toolCalls) // [{ toolCallId, toolName, args, requiresApproval }]
await agent.approveToolCall({
runId: runs[0].runId,
toolCallId: runs[0].toolCalls[0].toolCallId,
})
}

선택적 필터(threadId, resourceId, fromDate, toDate)와 페이지네이션(perPage, page)을 지원합니다. { runs, total }을 반환하며, total은 페이지네이션 전 일치하는 실행 수입니다. 반환되는 실행 구조에 관한 자세한 내용은 Agent.listSuspendedRuns()를 참조하세요.

approveToolCall()
approvetoolcall에 대한 직접 링크

보류 중인 Tool 호출을 승인하고 연속 스트림을 반환합니다. 승인 응답에서 재개된 청크를 렌더링할 때 이를 사용하십시오.

const response = await agent.approveToolCall({
runId: 'run-123',
toolCallId: 'tool-call-456',
})

response.processDataStream({
onChunk: async chunk => {
console.log(chunk)
},
})

sendToolApproval()
sendtoolapproval에 대한 직접 링크

구독 중인 스레드의 보류 중인 Tool 호출을 승인하거나 거부합니다. 재개된 청크를 별도의 연속 스트림이 아닌 기존 스레드 구독을 통해 받아야 할 때 subscribeToThread()와 함께 사용하세요.

const result = await agent.sendToolApproval({
resourceId: 'user-123',
threadId: 'thread-456',
toolCallId: 'tool-call-456',
approved: true,
})

console.log(result.accepted)

보고{ accepted: true, runId: string, toolCallId?: string }.

declineToolCall()
declinetoolcall에 대한 직접 링크

보류 중인 Tool 호출을 거부하고 연속 스트림을 반환합니다. 거부 응답에서 재개된 청크를 렌더링할 때 이것을 사용하십시오.

const response = await agent.declineToolCall({
runId: 'run-123',
toolCallId: 'tool-call-456',
})

response.processDataStream({
onChunk: async chunk => {
console.log(chunk)
},
})

resumeStream()
resumestream에 대한 직접 링크

사용자 정의 데이터를 사용하여 일시중단된 Agent 스트림을 재개합니다. Agent 내에서 Workflow 일시 중지와 같은 일시 중지 지점 이후에 실행을 계속하려면 이 옵션을 사용합니다.

const response = await agent.resumeStream(
{ approved: true, selectedOption: 'plan-b' },
{
runId: 'run-123',
toolCallId: 'tool-call-456', // optional
},
)

await response.processDataStream({
onChunk: chunk => {
console.log(chunk)
},
})

approveToolCallGenerate()
approvetoolcallgenerate에 대한 직접 링크

generate()(비스트리밍)를 사용할 때 보류 중인 Tool 호출을 승인합니다. 전체 응답을 반환합니다.

const output = await agent.generate('Find user John', {
requireToolApproval: true,
})

if (output.finishReason === 'suspended') {
const result = await agent.approveToolCallGenerate({
runId: output.runId,
toolCallId: output.suspendPayload.toolCallId,
})

console.log(result.text)
}

declineToolCallGenerate()
declinetoolcallgenerate에 대한 직접 링크

generate()(비스트리밍)를 사용할 때 보류 중인 Tool 호출을 거부합니다. 전체 응답을 반환합니다.

const output = await agent.generate('Find user John', {
requireToolApproval: true,
})

if (output.finishReason === 'suspended') {
const result = await agent.declineToolCallGenerate({
runId: output.runId,
toolCallId: output.suspendPayload.toolCallId,
})

console.log(result.text)
}

Agent 일정
Agent 일정에 대한 직접 링크

클라이언트 SDK 일정 메서드를 사용하여 /api/schedules 경로를 통해 영구 Agent 일정을 관리합니다. 개념과 서버 측 예제는 일정mastra.schedules 레퍼런스를 참조하세요.

createSchedule()
createschedule에 대한 직접 링크

전달하여 Agent 일정을 만듭니다.agentId.

const schedule = await mastraClient.createSchedule({
agentId: 'pinger',
cron: '0 * * * *',
prompt: 'Give me a status update.',
})

listSchedules()
listschedules에 대한 직접 링크

Agent 일정을 나열합니다. agentId, threadId, resourceId, name, status 같은 필드로 필터링할 수 있습니다.

const schedules = await mastraClient.listSchedules({
agentId: 'pinger',
status: 'active',
})

getSchedule()
getschedule에 대한 직접 링크

ID별로 단일 Agent 일정을 가져옵니다.

const schedule = await mastraClient.getSchedule('agent_pinger')

updateSchedule()
updateschedule에 대한 직접 링크

Agent 일정을 업데이트합니다. Agent 일정에서는 cron, timezone, prompt, name, 신호 전달 옵션, 메타데이터 및 status 같은 필드를 업데이트할 수 있습니다.

const updated = await mastraClient.updateSchedule('agent_pinger', {
cron: '*/30 * * * *',
prompt: 'Give me a status update every 30 minutes.',
})

deleteSchedule()
deleteschedule에 대한 직접 링크

Agent 일정을 삭제합니다.

await mastraClient.deleteSchedule('agent_pinger')

runSchedule()
runschedule에 대한 직접 링크

크론 주기를 변경하지 않고 즉시 Agent 일정을 한 번 실행합니다.

const run = await mastraClient.runSchedule('agent_pinger')

pauseSchedule()
pauseschedule에 대한 직접 링크

스케줄러가 실행을 중지하도록 Agent 일정을 일시 중지합니다. 업데이트된 일정을 반환합니다.

await mastraClient.pauseSchedule('agent_pinger')

resumeSchedule()
resumeschedule에 대한 직접 링크

일시중지된 Agent 일정을 재개합니다. 다음 실행 시간은 지금부터 다시 계산되므로 오랫동안 일시 중지된 일정은 백로그를 실행하지 않습니다. 업데이트된 일정을 반환합니다.

await mastraClient.resumeSchedule('agent_pinger')

listScheduleTriggers()
listscheduletriggers에 대한 직접 링크

각 화재에 대한 결합 실행 요약을 포함하여 Agent 일정에 대한 트리거 기록을 나열합니다.

const { triggers } = await mastraClient.listScheduleTriggers('agent_pinger', {
limit: 50,
})

클라이언트 Tool
클라이언트 Tool에 대한 직접 링크

클라이언트 측 Tool을 사용하면 Agent가 요청할 때 클라이언트 측에서 사용자 정의 기능을 실행할 수 있습니다.

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('Change the background to blue', {
clientTools: { colorChangeTool },
})

// Use with stream
const response = await agent.stream('Tell me a story', {
memory: {
thread: 'thread-1',
resource: 'resource-1',
},
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,
)}`,
)
}
},
})

Model에 대한 Shape 클라이언트 Tool 출력
Model에 대한 Shape 클라이언트 Tool 출력에 대한 직접 링크

클라이언트 Tool은 이미지 같은 멀티모달 콘텐츠를 포함하여 Model이 받는 내용을 제어하는 toModelOutput을 지원합니다. 클라이언트 Tool은 로컬에서 실행되므로 execute가 완료된 후 매핑도 클라이언트에서 실행됩니다. 변환된 출력은 원시 결과와 함께 서버로 다시 전송되므로 원시 결과를 스토리지 및 애플리케이션 로직에서 계속 사용할 수 있습니다.

const screenshotTool = createTool({
id: 'takeScreenshot',
description: 'Takes a screenshot of the current page',
inputSchema: z.object({}),
execute: async () => {
const base64 = await captureScreenshot()
return { ok: true, data: base64 }
},
toModelOutput: output => ({
type: 'content',
value: [{ type: 'media', data: output.data, mediaType: 'image/jpeg' }],
}),
})

클라이언트 Tool 추적
클라이언트 Tool 추적에 대한 직접 링크

서버에 @mastra/observability가 설치 및 구성되어 있으면 클라이언트 측 Tool은 현재 AGENT_RUN 스팬의 자식으로 CLIENT_TOOL_CALL 스팬을 기록합니다. Model이 클라이언트 Tool 호출을 방출하면 서버가 해당 스팬을 생성하고 발신 Tool 호출 청크에 W3C Trace 캐리어를 삽입합니다. Tool 인수를 사용할 수 있게 되면 스팬을 종료합니다. 서버 측 Observability가 구성되지 않은 경우 클라이언트 Tool 추적은 아무 작업도 하지 않습니다. 클라이언트 SDK는 각 클라이언트 Tool의 execute 함수가 소요한 실제 시간도 측정하여 서버로 다시 전송합니다. 서버에서는 이 값이 toolType: "client"가 포함된 mastra_tool_duration_ms 메트릭으로 방출됩니다. Tool의 execute 함수 내부에서 더욱 풍부한 원격 측정을 사용하려면 실행 컨텍스트의 observe 도우미를 사용하여 자식 스팬과 구조화된 로그를 추가하세요.

import { createTool } from '@mastra/client-js'
import { z } from 'zod'

const fetchUserTool = createTool({
id: 'fetchUser',
description: 'Fetches the current user profile',
inputSchema: z.object({ userId: z.string() }),
execute: async ({ userId }, { observe }) => {
observe.log('info', 'fetching user', { userId })
const user = await observe.span('http GET /users', async () => {
const res = await fetch(`/api/users/${userId}`)
return res.json()
})
return user
},
})

observe는 항상 사용할 수 있습니다. Trace 컨텍스트가 활성화되지 않은 경우(예: Trace되는 Agent 외부에서 실행 중) span은 함수를 직접 실행하고 log는 아무 작업도 하지 않습니다. null 검사는 필요하지 않습니다. SDK는 수집기가 OTLP/JSON으로 버퍼링한 모든 항목을 직렬화하여 다음 요청 본문으로 다시 전송합니다. 서버의 @mastra/observability 패키지는 스팬이 올바른 Trace에 속하는지 검증하여 Trace 간 삽입을 방지하고, 각 스팬과 로그를 서버 측 원격 측정에서 사용하는 것과 동일한 Observability 버스로 전달합니다. Observability가 구성되면 기존 익스포터가 이를 자동으로 수집합니다.

저장된 Agent
저장된 Agent에 대한 직접 링크

저장된 Agent는 런타임에 생성, 업데이트 및 삭제할 수 있는 데이터베이스 저장형 Agent 구성입니다. Agent가 인스턴스화될 때 Mastra 레지스트리에서 확인되는 기본 요소(Tool, Workflow, 다른 Agent, 채점자)를 키로 참조합니다. Memory는 lastMessages, semanticRecall 같은 옵션이 포함된 SerializedMemoryConfig 객체로 인라인 구성됩니다.

listStoredAgents()
liststoredagents에 대한 직접 링크

저장된 모든 Agent의 페이지가 매겨진 목록을 검색합니다.

const result = await mastraClient.listStoredAgents()
console.log(result.agents) // Array of stored agents
console.log(result.total) // Total count

페이지 매김 및 순서 지정:

const result = await mastraClient.listStoredAgents({
page: 0,
perPage: 20,
orderBy: {
field: 'createdAt',
direction: 'DESC',
},
})

createStoredAgent()
createstoredagent에 대한 직접 링크

새 저장된 Agent를 만듭니다.

const agent = await mastraClient.createStoredAgent({
id: 'my-agent',
name: 'My Assistant',
instructions: 'You are a helpful assistant.',
model: {
provider: 'openai',
name: 'gpt-5.4',
},
})

기본적으로 createStoredAgent()는 초기 버전을 즉시 게시합니다. activateVersion()을 호출하기 전에 검토할 수 있는 게시되지 않은 초안을 생성하려면 autoPublishfalse로 설정하세요.

const draft = await mastraClient.createStoredAgent({
id: 'draft-agent',
name: 'Draft Assistant',
instructions: 'You are a helpful assistant.',
model: {
provider: 'openai',
name: 'gpt-5',
},
autoPublish: false,
})

code 소스로 구성된 편집기는 저장 시 Agent 구성이 파일 시스템에 기록되므로 항상 초기 버전을 게시합니다. 모든 옵션 포함:

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-5.4',
},
tools: { calculator: {}, weather: {} },
workflows: { 'data-processing': {} },
agents: { 'subagent-1': {} },
memory: {
options: {
lastMessages: 20,
semanticRecall: false,
},
},
scorers: {
'quality-scorer': {
sampling: { type: 'ratio', rate: 0.1 },
},
},
defaultOptions: {
maxSteps: 10,
},
metadata: {
version: '1.0',
team: 'engineering',
},
})

getStoredAgent()
getstoredagent에 대한 직접 링크

저장된 특정 Agent의 인스턴스를 가져옵니다.

const storedAgent = mastraClient.getStoredAgent('my-agent')

저장된 Agent 방법
저장된 Agent 방법에 대한 직접 링크

details()
details-1에 대한 직접 링크

저장된 Agent 구성을 검색합니다.

const details = await storedAgent.details()
console.log(details.name)
console.log(details.instructions)
console.log(details.model)

update()
update에 대한 직접 링크

저장된 Agent의 특정 필드를 업데이트합니다. 모든 필드는 선택 사항입니다.

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()
delete에 대한 직접 링크

저장된 Agent 삭제:

const result = await storedAgent.delete()
console.log(result.success) // true

버전 관리
버전 관리에 대한 직접 링크

Agent(코드로 정의됨)와 StoredAgent 인스턴스 모두 구성 버전을 관리하는 메서드를 제공합니다. 수명 주기 및 선택 동작은 편집기 버전 관리를 참조하세요.

특정 버전의 Agent 가져오기
특정 버전의 Agent 가져오기에 대한 직접 링크

Agent를 가져올 때 버전 식별자를 전달합니다.

// Load the published version (default)
const agent = mastraClient.getAgent('support-agent')

// Load the latest draft
const draftAgent = mastraClient.getAgent('support-agent', { status: 'draft' })

// Load a specific version
const versionedAgent = mastraClient.getAgent('support-agent', { versionId: 'abc-123' })

저장된 Agent의 경우 상태 옵션을details():

const storedAgent = mastraClient.getStoredAgent('my-agent')
const draft = await storedAgent.details(undefined, { status: 'draft' })

listVersions()
listversions에 대한 직접 링크

Agent의 모든 버전을 나열합니다.

const versions = await agent.listVersions()
console.log(versions.items) // Array of version snapshots
console.log(versions.total)

페이지 매김 및 정렬 사용:

const versions = await agent.listVersions({
page: 0,
perPage: 10,
orderBy: {
field: 'createdAt',
direction: 'DESC',
},
})

createVersion()
createversion에 대한 직접 링크

새 버전 스냅샷을 만듭니다.

const version = await agent.createVersion({
changeMessage: 'Updated tone to be more friendly',
})

getVersion()
getversion에 대한 직접 링크

ID로 특정 버전을 얻으세요:

const version = await agent.getVersion('version-123')
console.log(version.versionNumber)
console.log(version.changedFields)
console.log(version.createdAt)

activateVersion()
activateversion에 대한 직접 링크

버전을 활성 게시 버전으로 설정합니다.

await agent.activateVersion('version-123')

restoreVersion()
restoreversion에 대한 직접 링크

동일한 구성으로 새 버전을 생성하여 이전 버전을 복원합니다.

await agent.restoreVersion('version-456')

deleteVersion()
deleteversion에 대한 직접 링크

버전 삭제:

await agent.deleteVersion('version-789')

compareVersions()
compareversions에 대한 직접 링크

두 버전을 비교하고 차이점을 반환합니다.

const diff = await agent.compareVersions('version-123', 'version-456')
console.log(diff.changes) // Fields that changed between versions

리액트 SDK
리액트 SDK에 대한 직접 링크

React SDK에서 useChat 훅을 사용할 때 requestContext를 통해 agentVersionId를 전달하세요.

Version targeting with React SDK
import { useChat } from '@mastra/react'

function Chat() {
const { messages, input, handleInputChange, handleSubmit } = useChat({
agentId: 'support-agent',
requestContext: {
agentVersionId: 'abc-123',
},
})

// ... render chat UI
}