Skip to main content

Mastra.getAgentById()

The .getAgentById() method retrieves a registered agent by its id. It first searches registered agents by agent.id. If no agent matches, it falls back to Mastra.getAgent() and treats the provided value as the agent registry key.

Use mastra.getAgentById(id) to retrieve the code-defined agent. Use await mastra.getAgentById(id, version) to retrieve a versioned agent.

Usage example
Direct link to Usage example

The following example registers an agent, retrieves it by ID, and uses the returned agent.

src/mastra/index.ts
import { Agent } from '@mastra/core/agent'
import { Mastra } from '@mastra/core/mastra'

const supportAgent = new Agent({
id: 'support-agent-id',
name: 'Support Agent',
instructions: 'Answer support questions clearly and concisely.',
model: 'openai/gpt-5.5',
})

export const mastra = new Mastra({
agents: {
supportAgent,
},
})

const agent = mastra.getAgentById('support-agent-id')

const response = await agent.generate('How can I reset my password?')

Parameters
Direct link to Parameters

id:

string
The ID of the agent to retrieve. Mastra first searches registered agents by agent.id. If none match, it uses this value as the agent registry key and calls getAgent().

version?:

{ versionId: string } | { status?: 'draft' | 'published' }
Optional version selector for retrieving a versioned agent. When provided, the method returns a promise.
VersionSelector

versionId:

string
The ID of a specific agent version to retrieve.

status?:

'draft' | 'published'
Select the latest agent version with this publication status.

Returns
Direct link to Returns

agent:

TAgents[TAgentName]
The agent instance with the specified ID when version is omitted.

agent:

Promise<TAgents[TAgentName]>
A promise that resolves to the versioned agent instance when version is provided.

Throws a MastraError when no agent is found by ID or registry key.

On this page