mastra-ai/mastra · error

list-available-agents requires a Mastra context.

Error message

list-available-agents requires a Mastra context.

What it means

list-available-agents is a Mastra tool whose execute destructures the runtime context and requires a `mastra` instance to enumerate registered agents. The library throws this Error when the tool is executed without a Mastra context, which happens when the tool runs outside a Mastra server/agent runtime (e.g. invoked directly, or registered on a non-Mastra execution harness). It is a fail-fast guard because without the instance there is no registry to read agents from.

Source

Thrown at mastracode/sdk/src/tools/workflows/list-available-agents.ts:29

export const listAvailableAgentsTool = createTool({
  id: 'list-available-agents',
  description:
    'Returns the agents currently registered on the Mastra instance. The agent ids returned here are the only valid values you can put in `{ type: "agent", agentId }` graph entries. `outputShape` describes the default text output; an entry-level `outputSchema` replaces that default with structured output.',
  inputSchema: z.object({}),
  outputSchema: z.object({
    agents: z.array(
      z.object({
        id: z.string(),
        description: z.string().optional(),
        // Human-readable string in v1. Could become a JSON Schema now that
        // structuredOutput round-trips through the rehydrator
        // (packages/core/src/workflows/rehydrate-workflow.ts).
        outputShape: z.string(),
      }),
    ),
  }),
  execute: async (_input, { mastra }) => {
    if (!mastra) throw new Error('list-available-agents requires a Mastra context.');
    const all = (mastra as { listAgents?: () => Record<string, unknown> }).listAgents?.() ?? {};
    return {
      agents: Object.entries(all)
        .filter(([id]) => !WORKFLOW_BUILDER_NOISE_AGENTS.has(id))
        .map(([id, a]) => ({
          id,
          description: (a as { description?: string } | undefined)?.description,
          outputShape: 'Default: { text: string }. An entry-level outputSchema produces that schema instead.',
        })),
    };
  },
});

View on GitHub (pinned to 75dd419e61)

Solutions

  1. Run the tool through a Mastra runtime (Mastra agent, server, or Studio) so the context carries the `mastra` instance.
  2. In custom code, pass an executionContext that includes `mastra: new Mastra({ agents: ... })` when calling tool.execute.
  3. If testing, construct the context with a real or minimal Mastra instance instead of omitting it.
  4. Verify you are not calling the tool's execute directly before Mastra initialization (e.g. before `await mastra.startServers()` or agent construction).

Example fix

// before
await tool.execute({ workflowId: 'x' }, {} as any); // no mastra
// after
import { Mastra } from '@mastra/core';
const mastra = new Mastra({ agents: { myAgent } });
await tool.execute({ workflowId: 'x' }, { mastra, requestContext: new RequestContext() });
Defensive patterns

Strategy: try-catch

Validate before calling

// before invoking the tool
if (!ctx || typeof ctx !== 'object' || !('mastra' in ctx) || !ctx.mastra) {
  throw new Error('list-available-agents must run inside a Mastra runtime context.');
}

Type guard

function hasMastraContext(ctx: unknown): ctx is { mastra: NonNullable<unknown>; requestContext?: unknown } {
  return (
    typeof ctx === 'object' &&
    ctx !== null &&
    'mastra' in ctx &&
    (ctx as { mastra?: unknown }).mastra != null
  );
}

Try / catch

try {
  const res = await tool.execute(input, ctx);
} catch (err) {
  if (err instanceof Error && err.message.includes('requires a Mastra context')) {
    // re-run inside a Mastra runtime or inject `mastra` into the context
  } else {
    throw err;
  }
}

Prevention

When it happens

Trigger: Executing the list-available-agents tool with a runtime context whose `mastra` property is undefined — e.g. calling `tool.execute()` manually without a Mastra-bound context, registering the tool in a harness that does not inject Mastra, or running it in tests with a stubbed executionContext.

Common situations: Unit tests invoking the tool with a fake context object missing `mastra`; embedding the SDK tool in a custom runner/framework (not Mastra Studio or a Mastra agent) that omits context injection; calling execute before server/agent initialization completes.

Related errors


AI-assisted analysis of mastra-ai/mastra@75dd419e61 (2026-08-30). Data as JSON: /api/errors/899455dbf786e64d. Report an issue: GitHub.