# /// script # requires-python = ">=3.11" # dependencies = ["mcp>=1.20,<2", "httpx>=0.27"] # /// """An MCP server for a self-hosted Mem0 REST server. Mem0's own MCP server only talks to the hosted Mem0 Platform, so this small bridge gives Claude Code, Codex, Cursor and other MCP clients four tools (add, search, list, delete) over the self-hosted API. It keeps no key of its own: each call passes on the caller's X-API-Key header, so every agent uses its own Mem0 key and the server checks it. Environment: MEM0_API_URL (default http://api:8000), MEM0_USER_ID (whose memories these are; default "me"), PORT (default 8765). From https://exe.dev/deploy/mem0 """ import os import httpx from mcp.server.fastmcp import Context, FastMCP from mcp.server.transport_security import TransportSecuritySettings API = os.environ.get("MEM0_API_URL", "http://api:8000").rstrip("/") USER = os.environ.get("MEM0_USER_ID", "me") mcp = FastMCP( "mem0", host="0.0.0.0", port=int(os.environ.get("PORT", "8765")), stateless_http=True, # exe.dev's proxy (or nginx) sets the Host header; no browser talks to this. transport_security=TransportSecuritySettings(enable_dns_rebinding_protection=False), ) async def call(ctx: Context, method: str, path: str, **kw): key = ctx.request_context.request.headers.get("x-api-key", "") if not key: raise ValueError("Send your Mem0 API key in the X-API-Key header.") async with httpx.AsyncClient(timeout=120) as client: r = await client.request(method, API + path, headers={"X-API-Key": key}, **kw) if r.status_code >= 400: raise ValueError(f"Mem0 answered {r.status_code}: {r.text[:500]}") return r.json() @mcp.tool() async def add_memory(text: str, ctx: Context, agent: str | None = None) -> dict: """Save a lasting fact, preference or decision. Mem0 extracts the memories from the text and merges them with what it already knows. `agent` names who is saving it (for example "claude-code"), if you like.""" body = {"messages": [{"role": "user", "content": text}], "user_id": USER} if agent: body["agent_id"] = agent return await call(ctx, "POST", "/memories", json=body) @mcp.tool() async def search_memories(query: str, ctx: Context, limit: int = 10) -> dict: """Search memories by meaning. Use it before answering questions about the user, their projects, or earlier decisions.""" body = {"query": query, "filters": {"user_id": USER}, "top_k": limit} return await call(ctx, "POST", "/search", json=body) @mcp.tool() async def list_memories(ctx: Context, limit: int = 100) -> dict: """List stored memories.""" return await call(ctx, "GET", "/memories", params={"user_id": USER, "top_k": limit}) @mcp.tool() async def delete_memory(memory_id: str, ctx: Context) -> dict: """Delete one memory by its id.""" return await call(ctx, "DELETE", f"/memories/{memory_id}") if __name__ == "__main__": mcp.run(transport="streamable-http")