> Documentation index: https://metorial.com/llms.txt. Every page is available as Markdown by adding .md to its URL.

# Add Metorial tools to a Mastra agent with MCPClient
URL: https://metorial.com/docs/build/frameworks/mastra

Create a Metorial session, give its connection URL to Mastra MCPClient with an Authorization header, and pass mcp.listTools() to the Agent tools option.

---

This guide takes you from an empty folder to a Mastra agent that searches the web through Metorial. You create a Metorial session, add its connection URL to Mastra's `MCPClient` with your API key in `requestInit.headers`, and pass `await mcp.listTools()` to the agent.

**What you'll learn**

* How to create an API key and a provider deployment from the CLI
* How to connect Mastra's `MCPClient` to a Metorial session
* How to see the tool calls the agent made

**Before you start**

* [Install the CLI and sign in](https://metorial.com/docs/build/sandboxes#install-the-tools)
* An OpenAI API key
* Node.js 22.13 or later

## Set up Metorial with the CLI

### 1. Find your instance

An instance is one environment of a project. List yours and note the ID of the one the agent should use:

```bash
metorial-admin instance list
```

### 2. Create an API key

```bash
metorial-admin api-keys create \
  --type instance_access_token_secret \
  --instance-id <instance-id> \
  --name my-agent
```

Copy the secret from the output. It starts with `metorial_sk_` and is shown only once.

### 3. Deploy a provider

Metorial Search is a built-in web search provider that needs no credentials.

```bash
metorial-admin providers deployments create \
  --provider-id metorial-search \
  --name "Metorial Search"
```

Copy the deployment ID from the output. It starts with `pde_`.

### 4. Export the values

```bash
export METORIAL_API_KEY="metorial_sk_..."
export METORIAL_PROVIDER_DEPLOYMENT_ID="pde_..."
export OPENAI_API_KEY="sk-..."
```

## Build the agent

### 1. Create the project

```bash
mkdir my-agent && cd my-agent
npm init -y
npm pkg set type=module
npm install metorial @mastra/core @mastra/mcp
npm install --save-dev tsx
```

### 2. Write the agent

Save this as `agent.ts`. The Metorial SDK creates the session, and Mastra's own MCP client connects to it over Streamable HTTP.

```typescript
import { Agent } from '@mastra/core/agent';
import { MCPClient } from '@mastra/mcp';
import Metorial from 'metorial';

let apiKey = process.env.METORIAL_API_KEY!;
let metorial = new Metorial({ apiKey });

let session = await metorial.sessions.create({
  providers: [{ providerDeploymentId: process.env.METORIAL_PROVIDER_DEPLOYMENT_ID! }]
});

let mcp = new MCPClient({
  id: 'metorial-mcp-client',
  servers: {
    metorial: {
      url: new URL(session.connectionUrl),
      requestInit: { headers: { Authorization: `Bearer ${apiKey}` } }
    }
  }
});

try {
  let tools = await mcp.listTools();
  console.log('Metorial tools:', Object.keys(tools).join(', '));

  let agent = new Agent({
    id: 'research-assistant',
    name: 'Research assistant',
    instructions: 'Use the Metorial tools to answer the question.',
    model: 'openai/gpt-6.1-sol',
    tools
  });

  let result = await agent.generate(
    'Search the web for the latest news about AI agents and summarize the top 3 stories.'
  );
  console.log(result.text);
} finally {
  await mcp.disconnect();
}
```

### 3. Run it

```bash
npx tsx agent.ts
```

## Check it worked

The first line lists the tools, then the agent prints its summary. Mastra prefixes each tool with the server key `metorial`. Metorial prefixes it with the provider name and adds `metorial_connection_status`, a diagnostic tool, to every session.

```text
Metorial tools: metorial_metorial_connection_status, metorial_metorial_search_getWebContent, metorial_metorial_search_webSearch
<a summary of three news stories>
```

List the tool calls Metorial recorded for the deployment:

```bash
metorial-admin sessions tool-calls list \
  --provider-deployment-id $METORIAL_PROVIDER_DEPLOYMENT_ID \
  --limit 5
```

## Use other apps and each user's own account

Find a provider and deploy it the same way, then add its deployment ID to `providers`. All of them arrive through the one `metorial` server.

```bash
metorial-admin providers list --search slack
metorial-admin providers deployments create --provider-id <provider-id> --name "Slack"
```

Apps such as Slack need a sign-in. Pass the user's provider auth config as `providerAuthConfigId` next to the deployment ID. [Let each user connect their own account](https://metorial.com/docs/build/sdk/oauth) shows how to get one for each user.

For per-user agents, create one session and one `MCPClient` per user, and pass `await mcp.listToolsets()` as `toolsets` when you call the agent. Mastra's `authenticate()` OAuth flow is for servers that sign a person in through the browser. A Metorial session uses the API key header instead.

## Troubleshooting

### The tool list is empty or `listTools()` fails

Call `mcp.listToolsWithErrors()` and read `errors` and `errorDetails`. They name each server that failed to connect, with the HTTP status when there is one. A missing or wrong `Authorization` header is the usual cause.

### `[METORIAL ERROR]: unauthorized - Invalid API key`

`sessions.create` rejected the key. Check that `METORIAL_API_KEY` holds the full secret and belongs to the instance where you created the deployment.

### `Provider requires an auth config to be provided`

A provider deployment in the session needs a sign-in and got no provider auth config. Add the user's `providerAuthConfigId` to that entry.

## Next steps

* [Let each user connect their own account](https://metorial.com/docs/build/sdk/oauth): per-user OAuth for Slack, Gmail, GitHub and other apps
* [Limit the tools an agent can use](https://metorial.com/docs/build/guides/limit-agent-tools): keep write or delete tools out of the session
* [Connect any MCP client](https://metorial.com/docs/build/guides/connect-any-mcp-client): the session URL, headers and tokens in detail
* [Use Metorial with the Vercel AI SDK](https://metorial.com/docs/build/providers/ai-sdk): the adapter for `generateText` and `streamText`