> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cedarcopilot.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Extending Mastra

> Connecting Cedar-OS with Mastra

Mastra is a full-featured typescript framework to build agents. It provides memory, tool calls, knowledge base, and more. It's our personal recommended choice when building complex agents.

## Initial Configuration

<Steps>
  <Step title="Set up your project">
    Run `plant-seed` and select either:

    * **Mastra starter** - for a complete setup with both frontend and backend
    * **Mastra reference repo** - to see a full implementation example

    If you already have a Mastra backend, use the **blank frontend cedar repo** option instead.

    For reference, you can still follow the official Mastra guide: [Install using the `create-mastra` CLI](https://mastra.ai/en/docs/getting-started/installation#install-using-the-create-mastra-cli).
  </Step>

  <Step title="Wrap your app with CedarCopilot">
    Wrap your application with the CedarCopilot provider to connect to your Mastra backend:

    ```tsx theme={null}
    import { CedarCopilot } from 'cedar-os';
    function App() {
    	return (
    		<CedarCopilot
    			llmProvider={{
    				provider: 'mastra',
    				baseURL: 'http://localhost:4111', // default dev port for Mastra
    				apiKey: process.env.NEXT_PUBLIC_MASTRA_API_KEY, // optional — only for backend auth
    			}}>
    			<YourApp />
    		</CedarCopilot>
    	);
    }
    ```
  </Step>

  <Step title="Configure Mastra endpoints to talk to Cedar">
    Configure your Mastra backend to work with Cedar by following the Mastra-specific configuration options: [Mastra Configuration Options](https://docs.cedarcopilot.com/agent-backend-connection/agent-backend-connection#mastra-configuration-options)

    [Register API routes](https://mastra.ai/en/examples/deployment/custom-api-route) in your Mastra server so Cedar's chat components have something to talk to:

    ```ts mastra/src/index.ts theme={null}
    import { registerApiRoute } from '@mastra/core/server';

    // POST /chat
    // The chat's non-streaming default endpoint
    registerApiRoute('/chat', {
    	method: 'POST',
    	// …validate input w/ zod
    	handler: async (c) => {
    		/* your agent.generate() logic */
    	},
    });

    // POST /chat/stream (SSE)
    // The chat's streaming default endpoint
    registerApiRoute('/chat/stream', {
    	method: 'POST',
    	handler: async (c) => {
    		/* stream agent output in SSE format */
    	},
    });
    ```
  </Step>

  <Step title="Add Cedar Chat">
    Drop a Cedar chat component into your frontend – see [Chat Overview](https://docs.cedarcopilot.com/chat/chat-overview).
    Your backend and frontend are now linked! You're ready to start bringing the power of your Mastra agentic workflows to your UI.
  </Step>
</Steps>

## Type Safety

Mastra backends support full end-to-end type safety using `MastraParams<T, E>`:

```typescript theme={null}
// Use MastraParams for type-safe requests
type MastraParams<
	T extends Record<string, unknown> = Record<string, never>,
	E = object
> = BaseParams<T, E> & {
	route: string;
	resourceId?: string;
	threadId?: string;
};
```

The `MastraParams` type allows you to:

* **T**: Define types for your `additionalContext` data
* **E**: Define types for custom fields (userId, sessionId, etc.)

For complete type safety implementation, validation with Zod schemas, and detailed examples, see [Typing Agent Requests](/type-safety/typing-agent-requests).

## Features to explore

Now that you have Cedar-OS connected to Mastra, explore these powerful features:

* **[State Access & Manipulation](https://docs.cedarcopilot.com/state-access/agentic-state-access)** - Use the `useRegisterState` hook for communicating frontend state and letting agents manipulate your frontend state
* **[Mentions & Context](https://docs.cedarcopilot.com/agent-context/mentions)** - Send @ mentions to your backend using the `useStateBasedMentionProvider`

## New to Mastra? Here are a few primitives to understand

<Tabs>
  <Tab title="Agent">
    ```ts theme={null}
    // Agents encapsulate instructions, model, memory and tools
    export const roadmap = new Agent({
      name: 'Roadmap',
      model: openai('gpt-4o-mini'),
      tools: { upvoteTool },
      instructions: `You are …`,
    });
    // Docs: https://mastra.ai/en/docs/agents/overview
    ```
  </Tab>

  <Tab title="Tool">
    ```ts theme={null}
    // Tools expose type-safe side effects
    export const upvoteTool = createTool({
      id: 'upvote-feature',
      inputSchema: z.object({ id: z.string() }),
      execute: async ({ context }) => { /* … */ },
    });
    // Docs: https://mastra.ai/en/docs/tools-mcp/overview
    ```
  </Tab>

  <Tab title="Workflow">
    ```ts theme={null}
    // Orchestrate multi-step logic
    const roadmapWorkflow = createWorkflow({ id: 'roadmap-analysis' })
      .then(step1)
      .then(step2);
    roadmapWorkflow.commit();
    // Docs: https://mastra.ai/en/docs/workflows/overview
    ```
  </Tab>

  <Tab title="index.ts">
    ```ts theme={null}
    // Register all your Mastra primitives here, and configure agent memory, message storage, etc.
    export const mastra = new Mastra({
      agents: { roadmap },
      server: { apiRoutes },
      workflows: { roadmapWorkflow }
      storage: new LibSQLStore({ url: ':memory:' }),
    });
    ```
  </Tab>
</Tabs>

## Deployment

The recommended deployment setup is:

* **Frontend**: Deploy to [Vercel](https://vercel.com) for optimal performance and seamless integration
* **Backend**: Use [Mastra Cloud](https://mastra.ai/cloud) for hosting your Mastra server

## Next Steps

* Clone & run the [cedar-mastra-starter](https://github.com/CedarCopilot/cedar-mastra-starter) to see everything in action.
* Explore the official Mastra docs for further customisation.
