Skip to main content

Overview

The MastraAgent wraps a Mastra Agent (from @mastra/core) and streams AG-UI compatible events for @ag-kit/server. Provide a runnableFactory that constructs and returns a Mastra Agent when invoked. Key capabilities:
  • Run any Mastra Agent created with @mastra/core
  • Stream BaseEvent types (text chunks, tool calls/results)
  • Forward client-provided tools from agent.run(…) to Mastra

Installation

pnpm add @ag-kit/agents @ag-kit/adapter-mastra @mastra/core @ai-sdk/openai-compatible @mastra/memory @mastra/libsql

Exports

All exports are available from @ag-kit/adapter-mastra: Exports:
  • MastraAgent – Main agent class for Mastra integration

Quick start

import { MastraAgent } from "@ag-kit/adapter-mastra";
import { Agent } from "@mastra/core/agent";
import { createOpenAICompatible } from "@ai-sdk/openai-compatible";

function createAgenticChatAgent(): Agent {
  const openaiCompatible = createOpenAICompatible({
    name: "custom",
    baseURL: process.env.OPENAI_BASE_URL!,
    apiKey: process.env.OPENAI_API_KEY!,
    includeUsage: true,
  });
  return new Agent({
    name: "agentic-chat-agent",
    description: "A helpful AI assistant",
    model: openaiCompatible(process.env.OPENAI_MODEL!),
    instructions: "You are a helpful assistant.",
  });
}

export const agent = new MastraAgent({
  runnableFactory: () => createAgenticChatAgent(),
  name: "mastra-agent",
  description: "Mastra-backed agent",
});

Server integration

import { run } from "@ag-kit/server";
import { agent } from "./agent";

run({ createAgent: () => ({ agent }) });

API

class MastraAgent

new MastraAgent(config: AgentConfig & {
  runnableFactory: () => Agent;
})
name
string
Unique identifier for the agent.
description
string
Human-readable description of the agent.
runnableFactory
() => Agent
required
Factory that returns a Mastra Agent instance. It will be invoked at run time to create the runnable.

Methods

run()
run(input: RunAgentInput): Observable<BaseEvent>
Executes the underlying Mastra agent and emits BaseEvent values from @ag-ui/client.
  • input – RunAgentInput containing messages, runId, threadId, tools, etc.
  • returns – Observable<BaseEvent>
Note: Event types and semantics match the LangGraph Agent reference.

Examples

  • Agentic chat (TS): project path typescript-sdk/packages/examples/agents/mastra/agentic-chat
  • Human-in-the-loop workflow (TS): project path typescript-sdk/packages/examples/agents/mastra/human-in-the-loop

See also