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

# Add Metorial tools to a Claude Agent SDK agent
URL: https://metorial.com/docs/build/frameworks/claude-agent-sdk

Create a Metorial session, add its connection URL to mcpServers as an http server with your API key in the Authorization header, and allow mcp__metorial__*.

---

This guide takes you from an empty folder to a Claude Agent SDK agent that searches the web through Metorial. You create a Metorial session, pass its URL to `query()` under `mcpServers` as an `http` server with your API key in the `Authorization` header, and allow `mcp__metorial__*`.

**What you'll learn**

* How to create an API key and a provider deployment from the CLI
* How to connect the Agent SDK to a Metorial session in TypeScript and Python
* How to confirm the server connected and see the tool calls

**Before you start**

* [Install the CLI and sign in](https://metorial.com/docs/build/sandboxes#install-the-tools)
* An Anthropic API key
* Node.js 18.14 or later, or Python 3.10 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 ANTHROPIC_API_KEY="sk-ant-..."
```

## Build the agent

### 1. Create the project

**TypeScript**

```bash
mkdir my-agent && cd my-agent
npm init -y
npm pkg set type=module
npm install metorial @anthropic-ai/claude-agent-sdk
npm install --save-dev tsx
```

**Python**

```bash
mkdir my-agent && cd my-agent
python3 -m venv .venv
source .venv/bin/activate
pip install metorial claude-agent-sdk
```

### 2. Write the agent

Save this as `agent.ts` or `agent.py`. The Agent SDK does not open a browser to sign in to MCP servers, so the session URL is paired with an API key in a header. Tool names take the form `mcp__<server>__<tool>`, which is why the server key `metorial` leads to `mcp__metorial__*`.

**TypeScript**

```typescript
import { query } from '@anthropic-ai/claude-agent-sdk';
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! }]
});

for await (let message of query({
  prompt: 'Search the web for the latest news about AI agents and summarize the top 3 stories.',
  options: {
    mcpServers: {
      metorial: {
        type: 'http',
        url: session.connectionUrl,
        headers: { Authorization: `Bearer ${apiKey}` }
      }
    },
    allowedTools: ['mcp__metorial__*']
  }
})) {
  if (message.type === 'system' && message.subtype === 'init') {
    let server = message.mcp_servers.find(server => server.name === 'metorial');
    let tools = message.tools.filter(name => name.startsWith('mcp__metorial__'));
    console.log('Metorial server:', server?.status);
    console.log('Metorial tools:', tools.join(', '));
  }

  if (message.type === 'result' && message.subtype === 'success') {
    console.log(message.result);
  }
}
```

**Python**

```python
import asyncio
import os

from claude_agent_sdk import ClaudeAgentOptions, ResultMessage, SystemMessage, query
from metorial import Metorial


async def main():
    api_key = os.environ["METORIAL_API_KEY"]
    metorial = Metorial(api_key=api_key)

    session = metorial.sessions.create(
        providers=[
            {"provider_deployment_id": os.environ["METORIAL_PROVIDER_DEPLOYMENT_ID"]}
        ],
    )

    options = ClaudeAgentOptions(
        mcp_servers={
            "metorial": {
                "type": "http",
                "url": session.connection_url,
                "headers": {"Authorization": f"Bearer {api_key}"},
            }
        },
        allowed_tools=["mcp__metorial__*"],
    )

    async for message in query(
        prompt="Search the web for the latest news about AI agents and summarize the top 3 stories.",
        options=options,
    ):
        if isinstance(message, SystemMessage) and message.subtype == "init":
            servers = message.data.get("mcp_servers", [])
            status = [s.get("status") for s in servers if s.get("name") == "metorial"]
            tools = [
                name
                for name in message.data.get("tools", [])
                if name.startswith("mcp__metorial__")
            ]
            print("Metorial server:", ", ".join(status))
            print("Metorial tools:", ", ".join(tools))

        if isinstance(message, ResultMessage) and message.subtype == "success":
            print(message.result)


asyncio.run(main())
```

### 3. Run it

**TypeScript**

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

**Python**

```bash
python agent.py
```

## Check it worked

The output starts with the server status and the tool names, then the agent's summary. Metorial prefixes each tool with the provider name and adds `metorial_connection_status`, a diagnostic tool, to every session.

```text
Metorial server: connected
Metorial tools: mcp__metorial__metorial_connection_status, mcp__metorial__metorial_search_getWebContent, mcp__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 github
metorial-admin providers deployments create --provider-id <provider-id> --name "GitHub"
```

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

A portal's Magic MCP URL expects a person to sign in through the browser, so it does not fit an agent that runs unattended. Use a session and an API key, as above.

## Troubleshooting

### The server status is `needs-auth` or `failed`

The Agent SDK got an authorization challenge or could not reach the URL. Check that `headers` holds `Authorization: Bearer` followed by a secret key (`metorial_sk_`), and that `url` is the session's connection URL, unchanged.

### The server status is `pending`

The Agent SDK had not finished connecting when it sent the init message. Read the status later with `mcpServerStatus()` on the query in TypeScript, or `get_mcp_status()` on `ClaudeSDKClient` in Python.

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

`sessions.create` rejected the key. In Python the message is `Invalid API key status=401`. 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
* [Run an agent in CI or a background job](https://metorial.com/docs/build/guides/run-agents-in-ci-and-background-jobs): API keys and stored connections with no browser
* [Connect Claude Code](https://metorial.com/docs/platform/clients/claude-code): for developers who use Claude Code interactively