Skip to main content

Sending signals

Send a message when a user has something to say, queue a follow-up when the current answer should finish first, or send a typed signal when your application has context to add. All three target a thread. You receive the agent's output through its thread stream.

The examples use the Agent and thread from the overview quickstart. To call an agent on a running server, use the client SDK or server routes. The Agent reference lists method parameters and return values.

Send a message
Direct link to Send a message

Pass the thread identifiers to sendMessage() for user input:

src/mastra/signals.ts
const result = agent.sendMessage('Compare that with the previous option.', {
resourceId: 'user_123',
threadId: 'thread_456',
})

await result.accepted

sendMessage() returns right away. Await result.accepted to wait for Mastra's routing decision and catch routing failures. Control when input arrives lists the possible actions.

Mastra checks the thread first. An idle thread starts a run. An active run takes the message, and the model sees it on the next request. With memory, it's stored for later runs and your UI. When the agent sees your input covers interruption.

Add attributes when several people share a thread:

const result = agent.sendMessage(
{
contents: 'Use the latest customer note too.',
attributes: { name: 'Jane', sentFrom: 'slack' },
},
{ resourceId: 'user_123', threadId: 'thread_456' },
)

await result.accepted

The model receives <user name="Jane" sentFrom="slack">Use the latest customer note too.</user>.

Tell the agent the user's time zone
Direct link to Tell the agent the user's time zone

Put the user's IANA time zone in attributes.timeZone:

const result = agent.sendMessage(
{ contents: 'Remind me after lunch.', attributes: { timeZone: 'Europe/Paris' } },
{ resourceId: 'user_123', threadId: 'thread_456' },
)

The model sees the attribute on the user's message, as <user timeZone="Europe/Paris">. A TimeSignalProvider on the agent also reads it and adds a line with the time there to its <current-time> tag. The provider also reads metadata.timeZone. That keeps the zone off the user's message, but the <current-time> tag still shows the zone and its time.

Queue a follow-up
Direct link to Queue a follow-up

Use queueMessage() when the current answer should finish before the agent sees the next message:

src/mastra/signals.ts
const result = agent.queueMessage('Also check whether the tests need updates.', {
resourceId: 'user_123',
threadId: 'thread_456',
})

await result.accepted

Queued input waits for the active run to finish, then starts a new run. On an idle thread it starts immediately. cancelQueuedMessages() removes input that no run has taken yet, without stopping the active run. Its awaited result lists the IDs this process cancelled, including ones it deleted from memory storage when it knows the thread's store: this process started the thread's current run and that run hasn't ended, or the agent's memory is a fixed instance and this process knows the thread's run keeps its signals in storage. Other processes cancel matching input when they get the request, and those IDs aren't in the result. Input a run already took stays delivered.

queueSignal() queues typed context with the same behavior but keeps the signal's type, tagName, and attributes.

Send context from a system
Direct link to Send context from a system

Use sendSignal() to add context from your application, such as a background job result. The signal's type and XML tag identify the context:

src/mastra/signals.ts
const result = agent.sendSignal(
{
type: 'reactive',
tagName: 'ci-result',
contents: 'CI failed on main: 3 tests failed.',
},
{ resourceId: 'user_123', threadId: 'thread_456' },
)

await result.accepted

type describes the source: reactive for context from your system or a processor, notification for an external event. tagName sets the XML tag; without it Mastra uses the type name, except reactive defaults to system-reminder.

Mastra passes contents as written and XML-escapes attribute values. A closing tag matching the signal's own tag is escaped so content can't end it early; this isn't a prompt-injection defense, so treat forwarded third-party text as untrusted. Use XML-safe tagName and attribute names with letters, numbers, periods, hyphens, or the underscore character, starting with a letter or underscore.

Like sendMessage(), sendSignal() delivers by default. Set transient: true to apply context only to the current request. Mastra never saves a transient signal as a message, so later turns don't find it in the history. When the run keeps its signals in memory storage, the signal waits there as a row of the messages table under the reserved thread ID mastra-queue:pending:<threadId>, and under mastra-queue:taken:<threadId> once a run takes it, with no resource ID, and no message read by thread or resource returns it. The row is deleted when the run that took it ends. One no run took waits for the thread's next turn. A run whose failure carries no saved progress, such as a step that runs out of deliveries with storageVersion: 2, gives back the signals it took, and the thread's next turn receives them again, so a transient signal can be seen twice. When the step that took a signal crashes before saving its state in a run that never recovers or ends, or when the storage call that settles the run's signals at its end fails, the thread's next run takes the signal again. Transient signals can't be state signals. The Agent reference covers attributes, metadata, and providerOptions.

Input that outlives the conversation
Direct link to Input that outlives the conversation

Use sendNotificationSignal() when an event needs a durable inbox record, delivery policy, and later reading. It can also merge related pending events. Sending sendSignal({ type: 'notification' }) adds context without creating an inbox record. See Notifications for the setup and delivery rules.

Use sendStateSignal() for named context that changes over time, such as the current browser page. Instead of adding a chat message, you send a full snapshot or a description of what changed. State signals explains how to keep that context current.

Control when input arrives
Direct link to Control when input arrives

Applications usually keep the defaults: active threads receive input and idle threads wake. Override them only for a different result.

Thread stateDefaultOther options
ActiveDeliver to the active runPersist without delivering, or discard
IdleWake a new runPersist without running, or discard

Set the behavior with ifActive.behavior or ifIdle.behavior. For example, an event that should be available next time but shouldn't start a run on its own can be persisted:

src/mastra/signals.ts
const result = agent.sendSignal(
{
type: 'notification',
contents: 'A new pull request is ready for review.',
},
{
...thread,
ifIdle: { behavior: 'persist' },
},
)

const { action } = await result.accepted

if (action === 'persist') {
await result.persisted
}

Only idle threads persist here. An active thread still delivers to the active run, so persisted is set only when the action is persist.

Message and signal sends return an accepted promise. It resolves when Mastra decides what to do, not when a run finishes. sendNotificationSignal() includes accepted only when its delivery policy emits a signal, so check decision first. sendStateSignal() omits it when it skips an unchanged snapshot.

The accepted promise resolves with one of these actions:

  • wake: this process started a run for the input.
  • deliver: the input was sent to a run, or another process accepted responsibility for starting one.
  • persist: the input is to be stored without delivery or a new run. Wait for persisted to confirm the write.
  • discard: the input was dropped.
  • blocked: the signal couldn't start or join a run, and Mastra doesn't keep it. reason is thread-blocked when another run, such as a paused or suspended one, owns the thread, or when run runId ended before a process that stores input directly could store it. reason is scope-mismatch when the signal's scopes differ from those of the run active on the thread. Resume or wait for run runId to end, then send the signal again. When the action is wake, the result carries the run's output stream. A run that fails after starting reports the error there. A routing failure rejects accepted. Use persisted to wait for a storage write.

An evented agent on storage that keeps pending signals stores input sent to its active run. When the process that receives the input writes it to storage, accepted resolves after the write and rejects when the write fails. A process that forwards the input to the process that holds the run resolves deliver before the input is stored. sendSignal() lists the cases.

When the agent sees your input
Direct link to When the agent sees your input

When input arrives during a model request, Mastra can cancel that request and retry it with the new input. For an evented agent whose request runs in another process, this needs storage that shares pending signals across processes. The interruption window stays open while the model produces only reasoning or metadata, or waits for its first token. It closes when the model produces text, a tool call, or other content. The replacement retries in the same run and step with the new input and keeps the discarded response out of history. It adds nothing to maxSteps and leaves stepNumber unchanged. There's no separate interruption limit, so repeated input can restart reasoning until the request completes, the run is cancelled, or its timeout expires.

The window closes once the request produces text, a tool call, or other content. Input then waits for the next loop boundary. Running tools aren't cancelled or repeated, and queued input never jumps ahead. If maxSteps is reached first, Mastra may save queued input without a response.

Reasoning already streamed may stay visible until the client reloads history. Input processors finish before the request is cancelled; output processors settle before the next request, and their side effects remain. Usage totals exclude interrupted requests, though providers may still bill.

Signals reach the model as XML elements: <user>, <system-reminder> for reactive context, and <notification> for external events. With Memory configured, accepted non-transient signals are written into thread history. State signals and Notifications have their own shapes.

Stop a run or clear queued input
Direct link to Stop a run or clear queued input

Aborting a run preserves queued input by default. Pass clearPendingSignals: true to drop the queue too:

subscription.abort({ clearPendingSignals: true })

Without a subscription, call agent.abortThreadStream() with the same option. Listeners stay subscribed and a later message can start a run. With shared PubSub, the clear request reaches the process that holds the run, which clears its local queue and the signals stored for the run that the run hasn't taken. cancelQueuedMessages() removes selected input without stopping the run and returns a promise of the cancelled IDs. Neither abort nor cancellation changes an accepted result that already resolved, but both can remove input answered with deliver that the run hasn't taken yet. Continuations are separate, so aborting the original doesn't cancel them.

AgentController and session
Direct link to AgentController and session

Most applications use the Agent methods directly. AgentController's Session wraps them and manages the subscription:

TaskAgentAgentController Session
Send a user messageagent.sendMessage()session.sendMessage()
Queue a user follow-upagent.queueMessage()session.queueMessage()
Send a typed signalagent.sendSignal()session.sendSignal()
Queue a typed signalagent.queueSignal()session.queueSignal()
Send a notificationagent.sendNotificationSignal()session.sendNotificationSignal()
Write a state signalagent.sendStateSignal()Not exposed on Session
Subscribe to a threadagent.subscribeToThread()Managed by Session

See Agent Controller for how Session manages threads and subscriptions.