# Your own agent

> Connect an agent you built to your Alexein memory over MCP with a personal key, so it searches what you know and saves what you tell it.

An agent you wrote yourself (a script, a bot, a service of your own) reaches your Alexein memory the same way
Claude and Cursor do: over MCP, at one URL. It sends a personal key in place of a sign-in, so it works where
nobody is there to sign in.

> **Filled in for you**
>
> [My memory › AI assistants › Your own agent](https://memory.alexein.ai/memory/assistants/custom-agent) creates the
> key and shows every example below with it filled in.

> **Run the example**
>
> A working agent that connects this way is in [mcp-own-agent](https://github.com/Alexein-AI/examples/tree/main/mcp-own-agent).

## 1. Get a key

1. Open [My memory › Personal keys](https://memory.alexein.ai/memory/keys) and select **Create key**. Label it after your
   agent, choose **Read and write** so it can save, and copy the key. It is shown once.
2. Put it in an environment variable where your agent runs, never in its code:

```bash title="Terminal"
export ALEXEIN_API_KEY="ax_..."
```

An agent that should only look things up takes a **Read** key instead: it cannot add, change or erase anything.

## 2. Connect it

Your agent's MCP client connects to the server URL over Streamable HTTP and sends two headers on every request:

```http title="Every request carries"
POST https://api.alexein.ai/v1/mcp
Authorization: Bearer ax_...
X-Alexein-User: me
```

`X-Alexein-User: me` names your own memory. Every MCP client that takes a URL and headers works. These are the
common ones:

**Python**

The official MCP SDK, version 2 or newer: `pip install "mcp>=2"`. It sends the headers through an `httpx2`
client, which comes with it.

```python title="agent.py"
import asyncio
import os

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

URL = "https://api.alexein.ai/v1/mcp"
HEADERS = {
    "Authorization": f"Bearer {os.environ['ALEXEIN_API_KEY']}",
    "X-Alexein-User": "me",
}


async def main() -> None:
    async with httpx2.AsyncClient(headers=HEADERS, timeout=httpx2.Timeout(30, read=300)) as http:
        async with streamable_http_client(URL, http_client=http) as (read, write):
            async with ClientSession(read, write) as session:
                await session.initialize()
                tools = await session.list_tools()
                print([t.name for t in tools.tools])
                result = await session.call_tool("memory_search", {"query": "What do I prefer for breakfast?"})
                print(result.content[0].text)


asyncio.run(main())
```

Hand `tools.tools` to your model as its tools, and run each call it makes with `session.call_tool`.
**TypeScript**

The official MCP SDK: `npm install @modelcontextprotocol/sdk`.

```ts title="agent.ts"
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";

const transport = new StreamableHTTPClientTransport(new URL("https://api.alexein.ai/v1/mcp"), {
  requestInit: {
    headers: {
      Authorization: `Bearer ${process.env.ALEXEIN_API_KEY}`,
      "X-Alexein-User": "me",
    },
  },
});
const client = new Client({ name: "my-agent", version: "1.0.0" });
await client.connect(transport);

const { tools } = await client.listTools();
console.log(tools.map((t) => t.name));
const result = await client.callTool({
  name: "memory_search",
  arguments: { query: "What do I prefer for breakfast?" },
});
console.log(result.content);
```

Hand `tools` to your model as its tools, and run each call it makes with `client.callTool`.
**OpenAI Agents SDK**

`pip install openai-agents`. The SDK lists the tools to the model and runs its calls.

```python title="agent.py"
import asyncio
import os

from agents import Agent, Runner
from agents.mcp import MCPServerStreamableHttp

INSTRUCTIONS = """Use Alexein as my memory.
Before you answer anything about me, my work or my plans, search it with memory_search.
When I tell you something new, save it with memory_add, without asking.
Save small details too: preferences, people, places, dates and decisions.
Never save passwords, keys or other secrets."""


async def main() -> None:
    async with MCPServerStreamableHttp(
        name="alexein",
        params={
            "url": "https://api.alexein.ai/v1/mcp",
            "headers": {
                "Authorization": f"Bearer {os.environ['ALEXEIN_API_KEY']}",
                "X-Alexein-User": "me",
            },
            "timeout": 30,
        },
        cache_tools_list=True,
    ) as memory:
        agent = Agent(name="Assistant", instructions=INSTRUCTIONS, mcp_servers=[memory])
        result = await Runner.run(agent, "What do you remember about me?")
        print(result.final_output)


asyncio.run(main())
```
**Claude Agent SDK**

`pip install claude-agent-sdk`. Name the tools the agent may call without asking.

```python title="agent.py"
import asyncio
import os

from claude_agent_sdk import ClaudeAgentOptions, query

INSTRUCTIONS = """Use Alexein as my memory.
Before you answer anything about me, my work or my plans, search it with memory_search.
When I tell you something new, save it with memory_add, without asking.
Save small details too: preferences, people, places, dates and decisions.
Never save passwords, keys or other secrets."""

options = ClaudeAgentOptions(
    system_prompt=INSTRUCTIONS,
    mcp_servers={
        "alexein": {
            "type": "http",
            "url": "https://api.alexein.ai/v1/mcp",
            "headers": {
                "Authorization": f"Bearer {os.environ['ALEXEIN_API_KEY']}",
                "X-Alexein-User": "me",
            },
        }
    },
    allowed_tools=[
        "mcp__alexein__memory_search",
        "mcp__alexein__memory_open",
        "mcp__alexein__memory_subject",
        "mcp__alexein__memory_latest",
        "mcp__alexein__memory_pending",
        "mcp__alexein__memory_summary",
        "mcp__alexein__memory_how_they_work",
        "mcp__alexein__memory_add",
        "mcp__alexein__memory_feedback",
    ],
)


async def main() -> None:
    async for message in query(prompt="What do you remember about me?", options=options):
        print(message)


asyncio.run(main())
```
**cURL**

Each request is one JSON-RPC message. List the tools, then call one:

```bash title="List the tools"
curl https://api.alexein.ai/v1/mcp \
  -H "Authorization: Bearer $ALEXEIN_API_KEY" \
  -H "X-Alexein-User: me" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}'
```

```bash title="Call one"
curl https://api.alexein.ai/v1/mcp \
  -H "Authorization: Bearer $ALEXEIN_API_KEY" \
  -H "X-Alexein-User: me" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc": "2.0", "id": 2, "method": "tools/call",
       "params": {"name": "memory_search", "arguments": {"query": "What do I prefer for breakfast?"}}}'
```

The wire format, every method and every error are on [The `/v1/mcp` endpoint](/api/mcp).

Any other framework that speaks MCP over HTTP, such as LangChain, LlamaIndex or the Vercel AI SDK, takes the
same URL and the same two headers. Choose its Streamable HTTP transport, not the older SSE one.

## 3. Teach it to use memory

The server tells every client how to use memory when it connects, but many frameworks never show that to the
model. Put these lines in your agent's system prompt or instructions, as the OpenAI and Claude examples above do:

```text title="Instructions"
Use Alexein as my memory.
Before you answer anything about me, my work or my plans, search it with memory_search.
When I tell you something new, save it with memory_add, without asking.
Save small details too: preferences, people, places, dates and decisions.
Never save passwords, keys or other secrets.
```

## 4. Check it works

1. List the tools. A **Read and write** key lists `memory_search`, `memory_add` and the other
   [tools](/mcp/tools); a **Read** key lists them without `memory_add` and `memory_feedback`.
2. Ask your agent "What do you remember about me?" It calls `memory_search` and answers from what it finds.
3. Tell it something new about you. Then open [My memory](https://memory.alexein.ai/memory): it is there within a few
   minutes.

## Good to know

- **One memory a connection.** No tool takes an account, so neither your agent nor its model can ask for anybody
  else's memory. The key and its header decide whose memory it is.
- **Keep the key on your side.** Anyone with it can read your memory, and save to it with a read and write key. Keep it on
  your computer or your server, never in a web page or a phone app you hand out. Revoke it under
  [My memory › Personal keys](https://memory.alexein.ai/memory/keys), and your agent stops at once.
- **What it costs.** `memory_search` counts 1 search against your month, and `memory_add` and
  `memory_feedback` 1 [event](/concepts/limits#what-counts) for each new item; the other read tools are free. See [How it works](/mcp#how-it-works).
- **Sign in instead.** An MCP client that signs in with OAuth needs only the URL: it opens Alexein's sign-in, and
  once you select **Allow**, it is listed under **Other AI assistants signed in** on
  [My memory › AI assistants](https://memory.alexein.ai/memory/assistants). See [Sign-in](/mcp#sign-in).
- **Building for other people?** An app whose users each keep their own memory belongs on the
  [Console](/developer-platform), with an API key and an [app user](/concepts/app-users) for each
  person. See [Integrations](/integrations) for the frameworks.

## Troubleshooting

- **`401`.** The key is missing, mistyped or revoked, or `Bearer ` is missing before it. Create a new one under
  [My memory › Personal keys](https://memory.alexein.ai/memory/keys).
- **`400`, asking for `X-Alexein-User`.** The key is a project key from the Console, not a personal key. Create a
  personal key under [My memory › Personal keys](https://memory.alexein.ai/memory/keys).
- **`405`.** The client opened the older SSE transport, which sends `GET`. Choose Streamable HTTP.
- **`memory_add` is missing.** The key is **Read**. Create a **Read and write** key.

More in [Troubleshooting](/mcp/troubleshooting).

