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

# Connect any MCP client to Metorial without the SDK
URL: https://metorial.com/docs/build/guides/connect-any-mcp-client

Create a session with POST /sessions, then connect your MCP client over Streamable HTTP to its connection_url with your secret API key as a Bearer token.

---

To use Metorial from any MCP client, create a session and connect the client over Streamable HTTP to the session's `connection_url`. Send `Authorization: Bearer <your secret API key>` on every request. This guide does it with the official MCP SDK in TypeScript and Python and no Metorial SDK.

**What you'll learn**

* The endpoint, the headers and the two tokens it accepts
* How to create a session from the CLI or over REST
* How to list and call tools with the MCP SDK

**Before you start**

* [Install the CLI and sign in](https://metorial.com/docs/build/sandboxes#install-the-tools)
* A secret [API key](https://metorial.com/docs/build/api) in `METORIAL_API_KEY`
* Node.js 20 or later, or Python 3.10 or later

## The endpoint and headers

| What             | Value                                                                                                               |
| ---------------- | ------------------------------------------------------------------------------------------------------------------- |
| Create a session | `POST https://api.metorial.com/sessions`                                                                            |
| REST headers     | `Authorization: Bearer <secret API key>`, `Metorial-Version: 2026-01-01-magnetar`, `Content-Type: application/json` |
| MCP URL          | The session's `connection_url`, in the form `https://api.metorial.com/connect/mcp/<session-id>`                     |
| MCP transport    | Streamable HTTP                                                                                                     |
| MCP auth         | `Authorization: Bearer <secret API key>`, or the session's `client_secret`                                          |

The `client_secret` starts with `metorial_fk_` and works only for its own session. Use it when the MCP client runs somewhere you do not want to place your API key. Clients that cannot set headers can append it to the URL as `?key=<client_secret>`.

## With the CLI

### 1. Deploy a provider

Metorial Search is a built-in web search provider that needs no credentials. Copy the deployment ID (`pde_...`) from the output.

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

### 2. Create a session

```bash
metorial-admin sessions create \
  --providers '[{"provider_deployment_id": "pde_your_deployment_id"}]'
```

The output contains the session ID, the `connection_url` and the `client_secret`. Paste the URL into any MCP client that supports Streamable HTTP and a Bearer token.

## With an MCP SDK

### 1. Create the project

**TypeScript**

```bash
mkdir mcp-client && cd mcp-client
npm init -y
npm pkg set type=module
npm install @modelcontextprotocol/client
npm install --save-dev tsx
```

**Python**

```bash
mkdir mcp-client && cd mcp-client
python3 -m venv .venv
source .venv/bin/activate
pip install mcp
```

### 2. Write the client

Save this as `client.ts` or `client.py`. It creates a session over REST, connects, lists the tools, and calls the first one whose name contains `search` with a `query` argument. Change the tool and arguments for other providers.

**TypeScript**

```typescript
import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client';

let apiKey = process.env.METORIAL_API_KEY!;

let response = await fetch('https://api.metorial.com/sessions', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${apiKey}`,
    'Metorial-Version': '2026-01-01-magnetar',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    providers: [{ provider_deployment_id: process.env.METORIAL_PROVIDER_DEPLOYMENT_ID! }]
  })
});
if (!response.ok) {
  throw new Error(`Metorial returned ${response.status}: ${await response.text()}`);
}
let session = (await response.json()) as { id: string; connection_url: string };

let transport = new StreamableHTTPClientTransport(new URL(session.connection_url), {
  requestInit: { headers: { Authorization: `Bearer ${apiKey}` } }
});
let client = new Client({ name: 'my-agent', version: '1.0.0' });
await client.connect(transport);

let { tools } = await client.listTools();
console.log('Tools:', tools.map(tool => tool.name).join(', '));

let tool = tools.find(tool => /search/i.test(tool.name));
if (!tool) throw new Error('The session has no search tool.');

let result = await client.callTool({
  name: tool.name,
  arguments: { query: 'Model Context Protocol' }
});
console.log(JSON.stringify(result.content, null, 2));

await client.close();
```

**Python**

```python
import asyncio
import os

import httpx2
from mcp import Client
from mcp.client.streamable_http import streamable_http_client


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

    async with httpx2.AsyncClient(
        headers={"Authorization": f"Bearer {api_key}"},
        timeout=httpx2.Timeout(30.0, read=300.0),
    ) as http_client:
        response = await http_client.post(
            "https://api.metorial.com/sessions",
            headers={"Metorial-Version": "2026-01-01-magnetar"},
            json={
                "providers": [
                    {"provider_deployment_id": os.environ["METORIAL_PROVIDER_DEPLOYMENT_ID"]}
                ]
            },
        )
        response.raise_for_status()
        session = response.json()

        transport = streamable_http_client(session["connection_url"], http_client=http_client)
        async with Client(transport) as client:
            listed = await client.list_tools()
            print("Tools:", ", ".join(tool.name for tool in listed.tools))

            tool = next((t for t in listed.tools if "search" in t.name.lower()), None)
            if tool is None:
                raise RuntimeError("The session has no search tool.")

            result = await client.call_tool(tool.name, {"query": "Model Context Protocol"})
            print(result.content)


asyncio.run(main())
```

### 3. Run it

**TypeScript**

```bash
export METORIAL_PROVIDER_DEPLOYMENT_ID="pde_..."
npx tsx client.ts
```

**Python**

```bash
export METORIAL_PROVIDER_DEPLOYMENT_ID="pde_..."
python client.py
```

To act as one user, add `provider_auth_config_id` to that provider's entry when you create the session. [Let each user connect their own account](https://metorial.com/docs/build/sdk/oauth) shows where the ID comes from.

## Check it worked

The program prints the tool names, then the content of the search result. Metorial prefixes each tool with the provider name and adds `metorial_connection_status`, a diagnostic tool, to every session.

```text
Tools: metorial_connection_status, metorial_search_getWebContent, metorial_search_webSearch
```

See the session and its tool calls from the CLI:

```bash
metorial-admin sessions list --limit 5
metorial-admin sessions tool-calls list --session-id <session-id>
```

## Troubleshooting

### `Invalid API key`

The Bearer token is not a key Metorial knows. `API key is expired or has been revoked` means the key existed and no longer works. Create a new one with `metorial-admin api-keys create`.

### `Secret API key required for MCP session connections`

You sent a publishable key (`metorial_pk_`). Use a secret key (`metorial_sk_`) or the session's `client_secret`.

### `Fine grained token is not authorized for this session`

You sent the `client_secret` of a different session.

### `Session has been archived or deleted`

Create a new session and connect to its `connection_url`.

### `TypeError: streamable_http_client() got an unexpected keyword argument 'headers'`

Version 2 of the MCP Python SDK takes headers on the `httpx2.AsyncClient` you pass as `http_client`, as in the sample. Version 1 used `streamablehttp_client(url, headers=...)`.

## Next steps

* [Choose between the SDK, the REST API and plain MCP](https://metorial.com/docs/build/guides/sdk-rest-api-or-mcp): when an adapter saves you this work
* [Limit the tools an agent can use](https://metorial.com/docs/build/guides/limit-agent-tools): serve only some of a provider's tools
* [Set up a Magic MCP server](https://metorial.com/docs/platform/integrations/setup-magic-mcp-server): one fixed MCP URL with its own token, no session per run
* [API reference](https://metorial.com/api): every endpoint, including sessions