Agent クラス
Agent クラスは、Mastra で AI Agent を作成するための基盤です。レスポンス生成と対話のストリーミングに使うメソッドを提供し、音声機能も扱います。
使用例使用例への直接リンク
基本的な文字列 instructions基本的な文字列 instructionsへの直接リンク
instructions を文字列または文字列配列で渡す方法が、Agent を設定する最も簡単な方法です。追加設定なしで Prompt を渡す単純なユースケースに適しています。
import { Agent } from '@mastra/core/agent'
// String instructions
export const agent = new Agent({
id: 'test-agent',
name: 'Test Agent',
instructions: 'You are a helpful assistant that provides concise answers.',
model: 'openai/gpt-5.6-sol',
})
// System message object
export const agent2 = new Agent({
id: 'test-agent-2',
name: 'Test Agent 2',
instructions: {
role: 'system',
content: 'You are an expert programmer',
},
model: 'openai/gpt-5.6-sol',
})
// Array of system messages
export const agent3 = new Agent({
id: 'test-agent-3',
name: 'Test Agent 3',
instructions: [
{ role: 'system', content: 'You are a helpful assistant' },
{ role: 'system', content: 'You have expertise in TypeScript' },
],
model: 'openai/gpt-5.6-sol',
})
Provider 固有の設定Provider 固有の設定への直接リンク
各 Model Provider では、Prompt Cache や推論設定などのオプションも利用できます。instructions 単位で providerOptions を設定し、System instructions/Prompt ごとに異なる Cache 方式を指定できます。
import { Agent } from '@mastra/core/agent'
export const agent = new Agent({
id: 'core-message-agent',
name: 'Core Message Agent',
instructions: {
role: 'system',
content: 'You are a helpful assistant specialized in technical documentation.',
providerOptions: {
openai: {
reasoningEffort: 'low',
},
},
},
model: 'openai/gpt-5.6-sol',
})
instructions 形式の混在instructions 形式の混在への直接リンク
import { Agent } from '@mastra/core/agent'
// This could be customizable based on the user
const preferredTone = {
role: 'system',
content: 'Always maintain a professional and empathetic tone.',
}
export const agent = new Agent({
id: 'multi-message-agent',
name: 'Multi Message Agent',
instructions: [
{ role: 'system', content: 'You are a customer service representative.' },
preferredTone,
{
role: 'system',
content: 'Escalate complex issues to human agents when needed.',
providerOptions: {
anthropic: { cacheControl: { type: 'ephemeral' } },
},
},
],
model: 'anthropic/claude-sonnet-4-6',
})
モデル文字列モデル文字列への直接リンク
最も簡単に設定するには、model を provider/model 形式の文字列で渡します。Provider 名とモデル名はスラッシュで区切ります。Mastra が環境から対応する Provider Credential を読み取るため、この形式では Provider Package や import は不要です。
よく使われる Provider 文字列と Credential:
- OpenAI:
openai/gpt-5.6-solはOPENAI_API_KEYを使用します。 - Anthropic:
anthropic/claude-sonnet-4-6はANTHROPIC_API_KEYを使用します。 - Google:
google/gemini-2.5-proはGOOGLE_API_KEYまたはGOOGLE_GENERATIVE_AI_API_KEYを使用します。
対応するモデル ID はモデル、Provider の全一覧は環境変数を参照してください。
Thread SignalThread Signalへの直接リンク
Agent Signal を使うと、Memory Thread へリアルタイムの入力とコンテキストを送信できます。Message API はユーザー入力用です。sendSignal() はシステム生成コンテキスト向けの低レベル API です。
対象 Thread が実行中の場合、sendMessage() はアクティブな Agent Loop へメッセージを配信します。Thread がアイドル状態の場合、Mastra はデフォルトでそのメッセージを最初の入力として Stream を開始します。
const subscription = await agent.subscribeToThread({
resourceId: 'user-123',
threadId: 'thread-abc',
})
void (async () => {
for await (const chunk of subscription.stream) {
console.log(chunk)
}
})()
agent.sendMessage('Use the latest customer note too.', {
resourceId: 'user-123',
threadId: 'thread-abc',
ifIdle: {
streamOptions: {
maxSteps: 3,
},
},
})
共有 Thread 内のユーザーを識別するには attributes を使います。属性は XML として表示されるため、モデルは誰が何を発言したかを区別できます。
agent.sendMessage(
{
contents: 'Can we simplify the API surface?',
attributes: { name: 'Devin', from: 'slack' },
},
{ resourceId: 'user-123', threadId: 'thread-abc' },
)
モデルは次の形式で受け取ります。
<user name="Devin" from="slack">Can we simplify the API surface?</user>
Thread が実行中かどうかに応じてメッセージへ異なるコンテキストを付けるには、ifActive.attributes と ifIdle.attributes を使います。
agent.sendMessage(
{
contents: 'Also cover the edge cases.',
attributes: { source: 'chat' },
},
{
resourceId: 'user-123',
threadId: 'thread-abc',
ifActive: { attributes: { delivery: 'while-active' } },
ifIdle: { attributes: { delivery: 'new-message' } },
},
)
Thread がアクティブな場合、モデルは次を受け取ります。
<user source="chat" delivery="while-active">Also cover the edge cases.</user>
Thread がアイドル状態の場合、モデルは次を受け取ります。
<user source="chat" delivery="new-message">Also cover the edge cases.</user>
UI はメッセージ内容を受け取り、Signal Message の attributes と metadata も読み取ってカスタム表示できます(例:ユーザー名、Avatar、プラットフォーム Badge の表示)。
sendMessage(message, options)sendmessagemessage-optionsへの直接リンク
アクティブな Run または Memory Thread へユーザーメッセージを送信します。アクティブな Agent がメッセージをすぐに受け取る必要がある場合に使います。
message:
attributes がある場合、Mastra は属性を含む <user> XML 要素としてメッセージを表示します。options?:
runId?:
resourceId?:
threadId とともに必須です。threadId?:
resourceId とともに必須です。ifActive?:
behavior?:
deliver です。attributes?:
ifIdle?:
behavior?:
wake です。streamOptions?:
ifIdle.behavior が wake の場合に開始する Stream のオプション。Mastra はトップレベルの resourceId と threadId を Memory コンテキストに使います。attributes?:
アイドル状態の Thread でカスタム実行オプションを使って新しい Stream を開始するには、ifIdle.behavior を wake に設定し、ifIdle.streamOptions を渡します。
agent.sendMessage('Continue with the next step.', {
resourceId: 'user-123',
threadId: 'thread-abc',
ifIdle: {
behavior: 'wake',
streamOptions: {
maxSteps: 3,
},
},
})
{ accepted: Promise<SendAgentSignalAccepted>, signal: CreatedAgentSignal, persisted?: Promise<void> } を返します。accepted は、Mastra がメッセージの処理方法を決定した時点で解決されます。このプロセスが Agent を実行する場合(Run を開始したか、開始する Lease を取得した場合)は { action: 'wake', runId, output }、メッセージが既存 Run へ転送された場合(このプロセスがプロセス間の Wake 競合に負けた場合を含む)は { action: 'deliver', runId }、何も実行されなかった場合は { action: 'persist' }/{ action: 'discard' } です。runId はメッセージを処理した Run の正式な ID で、wake と deliver にのみ存在します。persist/discard では、保存済みメッセージとの対応付けに result.signal.id を使います。accepted は Route 決定時に解決され(wake Run の生成エラーは output.consumeStream() から表面化)、メッセージをまったく Routing または開始できなかった場合(例:Agent の設定不備)だけ Reject されます。persisted は persist 動作の場合にのみ存在し、Mastra が Memory へのメッセージ書き込みを終えると解決されます。wake Action の output は、プロセス内で消費できる Agent Stream です。
queueMessage(message, options)queuemessagemessage-optionsへの直接リンク
Thread の次の Turn に向けてユーザーメッセージを Queue へ追加します。Thread がアクティブな場合、Mastra はアクティブ Run の完了を待ち、Queue 内のメッセージで新しい Run を開始します。Thread がアイドル状態の場合は、すぐに Run を開始します。
agent.queueMessage('Also check whether the tests need updates.', {
resourceId: 'user-123',
threadId: 'thread-abc',
})
queueMessage() は sendMessage() と同じ形式の message と options を受け取り、{ accepted: Promise<SendAgentSignalAccepted>, signal: CreatedAgentSignal, persisted?: Promise<void> } を返します。accepted の意味も sendMessage() と同じです。
sendSignal(signal, options)sendsignalsignal-optionsへの直接リンク
アクティブな Run または Memory Thread へ Signal を送信します。
signal:
type は Signal の意味上のカテゴリです。tagName はモデルに見せる XML Tag を制御します。たとえば、{ type: 'notification', tagName: 'github-review' } は <github-review>...</github-review> として表示されます。従来の user-message と system-reminder Payload も引き続き受け付け、正規化されます。未知の type 値は拒否されるため、カスタム XML Tag には tagName を使います。options?:
runId?:
resourceId?:
threadId とともに必須です。threadId?:
resourceId とともに必須です。ifActive?:
behavior?:
deliver です。attributes?:
ifIdle?:
behavior?:
wake です。streamOptions?:
ifIdle.behavior が wake の場合に開始する Stream のオプション。Mastra はトップレベルの resourceId と threadId を Memory コンテキストに使います。attributes?:
{ accepted: Promise<SendAgentSignalAccepted>, signal: CreatedAgentSignal, persisted?: Promise<void> } を返します。accepted は、Mastra が Signal の処理方法を決定した時点で解決されます。このプロセスが Agent を実行する場合(Run を開始したか、開始する Lease を取得した場合)は { action: 'wake', runId, output }、Signal が既存 Run へ転送された場合(このプロセスがプロセス間の Wake 競合に負けた場合を含む)は { action: 'deliver', runId }、何も実行されなかった場合は { action: 'persist' }/{ action: 'discard' } です。action は ifActive/ifIdle で採用された behavior と一致します。runId は Signal を処理した Run の正式な ID で、wake と deliver にのみ存在します。persist/discard では、保存済み Signal との対応付けに result.signal.id を使います。accepted は Route 決定時に解決され(wake Run の生成エラーは output.consumeStream() から表面化)、Signal をまったく Routing または開始できなかった場合(例:Agent の設定不備)だけ Reject されます。persisted は persist 動作の場合にのみ存在し、Mastra が Memory への Signal 書き込みを終えると解決されます。wake Action の output は、プロセス内で消費できる Agent Stream です。
サーバーレス Handler では accepted を await し、wake の出力をプラットフォームの waitUntil 相当へ渡します。これにより、HTTP レスポンスを返した後も、採用されたプロセスが Stream を最後まで消費できます。
const result = agent.sendSignal(signal, { resourceId, threadId })
ctx.waitUntil(
result.accepted.then(async accepted => {
if (accepted.action === 'wake') {
await accepted.output.consumeStream()
}
}),
)
sendStateSignal(state, options)sendstatesignalstate-optionsへの直接リンク
名前付きで Thread Scope の State Context を、アクティブな Run または Memory Thread へ送信します。ブラウザ状態、Editor 状態、Watcher 出力など、時間とともに変化する永続 Context を外部 Producer が所有する場合に使います。
const result = await agent.sendStateSignal(
{
id: 'browser',
mode: 'snapshot',
cacheKey: 'browser:https://example.com:3-tabs',
contents: 'Browser is open. Active tab URL: https://example.com. 3 open tabs.',
value: {
activeUrl: 'https://example.com',
tabCount: 3,
open: true,
},
},
{
resourceId: 'user-123',
threadId: 'thread-abc',
},
)
state:
id:
browser や editor などの State Lane 名。cacheKey:
contents:
mode?:
snapshot です。value?:
mode: 'snapshot' で使う構造化 Snapshot 値。delta?:
mode: 'delta' で使う構造化変更値。attributes?:
metadata?:
tagName?:
state です。options:
sendSignal() と同じオプションを受け取ります。Mastra が新しい State を受け付けると { accepted: Promise<SendAgentSignalAccepted>, signal: CreatedAgentSignal, persisted?: Promise<void>, skipped?: false } を返します。同じ cacheKey と Mode が State Lane の現在値である場合は { skipped: true, reason: 'unchanged' } を返します。accepted は、Mastra が Signal の処理方法を決定した時点で解決されます。このプロセスが Agent を実行する場合(Run を開始したか、開始する Lease を取得した場合)は { action: 'wake', runId, output }、Signal が既存 Run へ転送された場合(このプロセスがプロセス間の Wake 競合に負けた場合を含む)は { action: 'deliver', runId }、何も実行されなかった場合は { action: 'persist' }/{ action: 'discard' } です。runId は Signal を処理した Run の正式な ID で、wake と deliver にのみ存在します。persist/discard では、保存済み Signal との対応付けに result.signal.id を使います。wake Action の output は、プロセス内で消費できる Agent Stream です。
sendNotificationSignal(notification, options)sendnotificationsignalnotification-optionsへの直接リンク
Notification Inbox Record を作成または統合し、通知配信 Policy を解決します。即時配信が決定された場合は Notification Signal を送信します。
const result = await agent.sendNotificationSignal(
{
source: 'github',
kind: 'ci-status',
priority: 'high',
summary: 'CI failed on main: 3 tests failed.',
dedupeKey: 'github:acme/app:main:ci',
},
{
resourceId: 'user-123',
threadId: 'thread-abc',
},
)
notification:
source:
github、slack、email など、通知を生成した外部システム。kind:
ci-status、mention、direct-message など、Source 内の通知種別。summary:
priority?:
medium です。payload?:
dedupeKey?:
coalesceKey?:
attributes?:
metadata?:
options:
resourceId:
threadId:
ifIdle?:
streamOptions?:
{ record: NotificationRecord, decision: NotificationDeliveryDecision, runId?: string, signal?: CreatedAgentSignal, persisted?: Promise<void>, accepted?: Promise<SendAgentSignalAccepted> } を返します。record は保存済み Inbox Record、decision は配信 Policy の結果です。Ingress が Signal を即時送出した場合は、アクティブな高優先度通知で即時送出される要約も含め、signal と runId が存在します。アイドル状態の Thread を Wake させずに送出 Signal を永続化した場合は persisted が存在します。Signal を送出した場合は accepted が存在し、Mastra が処理方法を決定した時点で解決されます。このプロセスが Agent を実行する場合(Run を開始したか、開始する Lease を取得した場合)は { action: 'wake', runId, output }、Signal が既存 Run へ転送された場合は { action: 'deliver', runId }、何も実行されなかった場合は { action: 'persist' }/{ action: 'discard' } です。解決結果の runId は wake と deliver にのみ存在します。wake Action の output は、プロセス内で消費できる Agent Stream です。
デフォルト配信は優先度を考慮します。urgent 通知は即時配信されます。high 通知は Thread がアイドル状態なら即時配信されます。Thread がアクティブな場合、Mastra は要約をすぐに送出し、Thread がアイドル状態になった後の完全配信用に deliverAt を維持します。medium 通知はアイドル時に即時配信され、アクティブ時には要約へまとめられます。low 通知はアクティブ時もアイドル時も要約へまとめられます。アイドル時の低優先度要約は、Model Loop を Wake させずに購読者へ届きます。処理全体は Signalを参照してください。
一部の通知を別の Dispatch Window や要約 Rollup まで待機させるには、Agent に notifications.deliveryPolicy を設定します。
export const supportAgent = new Agent({
id: 'support-agent',
name: 'Support Agent',
instructions: 'Help the user triage updates.',
model: 'openai/gpt-5.6-sol',
notifications: {
deliveryPolicy: {
priorities: {
urgent: 'deliver',
},
decide: ({ record }) => {
if (record.priority === 'low') {
return {
action: 'summarize',
summaryAt: new Date(Date.now() + 30 * 60 * 1000),
}
}
},
},
},
})
subscribeToThread(options)subscribetothreadoptionsへの直接リンク
Memory Thread の生 Stream チャンクを購読します。sendMessage()、queueMessage()、sendSignal() を呼び出す前に使います。Signal がアクティブ Run を中止した場合も含め、Stream 出力の表示と Signal Echo の監視が可能です。
options:
resourceId?:
threadId:
次のメンバーを持つ AgentThreadSubscription オブジェクトを返します。
stream:
activeRunId:
null です。abort:
true を返します。unsubscribe:
コンストラクターのパラメータコンストラクターのパラメータへの直接リンク
id:
name:
description?:
metadata?:
instructions:
model:
provider/model 形式の Model Router 文字列、モデル設定または Provider インスタンス、あるいは Runtime でモデルを解決する関数を渡します。一般的な Provider と環境変数はモデル文字列を参照してください。agents?:
tools?:
hooks?:
generate() または stream() へ渡す実行単位の Hook は、ここで設定した対応する Hook を上書きします。以下の「Tool Hook」を参照してください。beforeToolCall?:
{ toolName, input, context, metadata } を受け取ります。Tool 呼び出しをスキップし、output を結果として使うには { proceed: false, output } を返します。afterToolCall?:
{ toolName, input, context, metadata, output, error } を受け取ります。Tool がエラーをスローすると output は undefined になり、代わりに error が設定されます。transform?:
createTool() の Tool 単位の transform を使います。workflows?:
defaultOptions?:
stream() と generate() の呼び出しで使うデフォルトオプション。defaultGenerateOptionsLegacy?:
generateLegacy() の呼び出しで使うデフォルトオプション。defaultStreamOptionsLegacy?:
streamLegacy() の呼び出しで使うデフォルトオプション。mastra?:
scorers?:
memory?:
notifications?:
deliveryPolicy?:
decide() 関数を設定できます。voice?:
inputProcessors?:
createWorkflow() で作成した Workflow を指定できます。outputProcessors?:
maxProcessorRetries?:
requestContextSchema?:
editor?:
generate() の Memory オプションgenerate-memory-optionsへの直接リンク
agent.generate() の呼び出し時に memory を渡し、Run が読み書きする会話 Thread を選びます。一般的な形式は memory: { resource: string, thread: string } で、resource は所有者、thread は会話を識別します。概念モデルは Thread と Resourceを参照してください。
const response = await agent.generate('What did we decide about retries?', {
memory: {
resource: 'user-123',
thread: 'support-thread-456',
},
})
呼び出し中に Thread メタデータを作成または更新する場合は、Thread オブジェクトを使います。
const response = await agent.generate('Continue the support conversation.', {
memory: {
resource: 'user-123',
thread: {
id: 'support-thread-456',
title: 'Billing support',
metadata: { category: 'billing' },
},
},
})
Tool HookTool Hookへの直接リンク
hooks を使うと、割り当て済み Tool、Memory Tool、Toolset、クライアント Tool、Workspace Tool を含め、Agent によるすべての Tool 呼び出しの前後でロジックを実行できます。
import { Agent } from '@mastra/core/agent'
export const agent = new Agent({
id: 'support-agent',
name: 'support-agent',
instructions: 'Help users with their questions.',
model: 'openai/gpt-5.6-sol',
hooks: {
beforeToolCall: ({ toolName, input }) => {
console.log(`Running ${toolName}`, input)
},
afterToolCall: ({ toolName, output, error }) => {
console.log(`Finished ${toolName}`, { output, error })
},
},
})
beforeToolCall は { proceed: false, output } を返して Tool 呼び出しを短絡できます。Agent は実行をスキップし、output を Tool の結果として使います。
const result = await agent.generate('Clean up old records', {
hooks: {
beforeToolCall: ({ toolName }) => {
if (toolName === 'deleteRecord') {
return { proceed: false, output: { blocked: true } }
}
},
},
})
Hook Context の metadata には agentId と agentName が含まれます。generate() または stream() へ渡す実行単位の Hook は、対応する Agent レベルの Hook を上書きします。Workspace でも tools.hooks が定義されている場合、Workspace Hook は Agent Hook Wrapper の内側で実行されます。
Editor による上書きEditor による上書きへの直接リンク
MastraEditor を登録すると、editor フィールドによって、コードで定義した Agent のどの部分を Editor から変更できるかを制御できます。コードが所有するフィールドは Studio で読み取り専用になり、保存する上書き値から除外されます。
editor?:
false を設定します。instructions の編集を許可するには instructions: true を設定します。Tool の所属と説明の編集を許可するには tools: true、説明の編集だけを許可するには tools: { description: true } を設定します。Agent の id、name、model は常にコードから取得され、Editor では上書きできません。使い方は Editorを参照してください。