# Mastra AI

> Mastra AI integration example.

Canonical page: https://xmemory.ai/mastra-ai/

[Mastra](https://mastra.ai/) supports MCP servers natively, which makes adding xmemory straightforward — paste a prompt into your AI-assisted IDE and the integration is done.

For the full tool reference, see the [MCP](https://xmemory.ai/mcp/) guide. For direct HTTP API usage, see the [TypeScript](https://xmemory.ai/typescript/) guide.

---

## Setup

**API key:** To use xmemory APIs or integrations, you need an API key. Get one from the [xmemory console](https://console.xmemory.ai). Copy and securely store the key. Never share your API key publicly.

Scaffold a Mastra project and add MCP support:

```bash
npm create mastra@latest my-xmemory-agent
cd my-xmemory-agent
npm install @mastra/mcp
```

Add your keys to `.env`:

```bash
XMEM_API_KEY=your-api-key-here
XMEM_INSTANCE_ID=your-instance-id
ANTHROPIC_API_KEY=your-anthropic-key
```

---

## Add xmemory

From your Mastra project directory, give this prompt to an AI-assisted IDE (Cursor, Windsurf, Claude Code, etc.):

```text
Integrate the `xmemory` MCP server with this Mastra instance.

Add `@mastra/mcp` to package.json if not already present.

Create an MCP client that:
- Reads XMEM_API_KEY and XMEM_INSTANCE_ID from the environment (throw if missing).
- Connects to https://mcp.xmemory.ai/instance/<XMEM_INSTANCE_ID> with the API key as the Bearer auth header.

Load the MCP tools via listTools() and export them.

Create an `xmemory` Agent wired to those tools with these instructions:

> You are the xmemory assistant. You help users manage and query their
> xmemory instance:
> - Create and configure new instances, generate or enhance schemas,
>   connect and disconnect from instances.
> - Use the xmemory_admin_* tools to perform administrative and schema
>   operations as requested.
> - Be concise and confirm what you did after each action.

Register the agent in the Mastra instance alongside any existing agents.
```

That's it. The exact set of tools the agent sees depends on the **connection type** chosen at MCP login. With the *instance* connection type, the agent gets 10 default tools — 7 bound (`get_instance_id`, `get_instance_schema`, `get_setup_instructions`, `write`, `write_async`, `write_status`, `read`) and the 3-tool schema-evolution suggestion engine (`review_suggestions`, `decide_suggestions`, `apply_pending_decisions`) — plus an opt-in **Schema management** group (5 more). With the *admin* connection type it instead gets the schema and instance-management tools (`admin_*`). See the [MCP — Tools](https://xmemory.ai/mcp/#tools) reference for full details.

> **Note on auth.** This headless setup sends your account **API key** directly as the Bearer token on the `/instance/<instance_id>` shortcut path — no OAuth exchange needed. The instance is bound by the URL path, so tool calls don't pass `instance_id`. See the [MCP guide](https://xmemory.ai/mcp/#authentication) for the other connection options.

---

## Reference

The prompt above produces files like the ones below. Use these to verify the output or to set things up manually.

**MCP client** — `src/mastra/mcp.ts`

```typescript

if (!process.env.XMEM_API_KEY || !process.env.XMEM_INSTANCE_ID) {
  throw new Error('XMEM_API_KEY and XMEM_INSTANCE_ID environment variables are required');
}

export const xmemoryMcp = new MCPClient({
  id: 'xmemory',
  servers: {
    xmemory: {
      url: new URL(`https://mcp.xmemory.ai/instance/${process.env.XMEM_INSTANCE_ID}`),
      requestInit: {
        headers: {
          Authorization: `Bearer ${process.env.XMEM_API_KEY}`,
        },
      },
    },
  },
});
```

**Tool loader** — `src/mastra/tools/xmemory.ts`

```typescript

let xmemoryTools: Record<string, any> = {};
try {
  xmemoryTools = await xmemoryMcp.listTools();
} catch (err) {
  console.error('Failed to load xmemory MCP tools:', err);
}

export { xmemoryTools };
```

**Agent** — `src/mastra/agents/xmemory.ts`

```typescript

export const xmemoryAgent = new Agent({
  name: 'xmemory-agent',
  model: anthropic('claude-sonnet-4-6'),
  instructions:
    'You are the xmemory assistant. You help users manage and query their xmemory instance: ' +
    'create and configure new instances, generate or enhance schemas, connect and disconnect from instances. ' +
    'Use the xmemory_admin_* tools to perform administrative and schema operations as requested. ' +
    'Be concise and confirm what you did after each action.',
  tools: { ...xmemoryTools },
});
```

**Registration** — `src/mastra/index.ts`

```typescript

export const mastra = new Mastra({
  agents: { xmemoryAgent },
});
```
