|
| 1 | +--- |
| 2 | +title: Memobase MCP |
| 3 | +--- |
| 4 | + |
| 5 | +> [Full Code](https://github.com/memodb-io/memobase/tree/dev/src/mcp) |
| 6 | +
|
| 7 | +The [Model Context Protocol (MCP)](https://modelcontextprotocol.io) is revolutionizing how AI agents interact with external systems and data sources. |
| 8 | +In this tutorial, we'll explore how to integrate **Memobase with MCP** to give your AI agents persistent, long-term memory capabilities. |
| 9 | + |
| 10 | +Memobase MCP server enables AI agents to store, retrieve, and search memories using semantic search, making your agents truly stateful and context-aware across conversations. |
| 11 | + |
| 12 | +## What is MCP? |
| 13 | + |
| 14 | +The Model Context Protocol is an open standard that enables AI assistants to securely connect to external data sources and tools. Instead of being limited to their training data, AI agents can now access real-time information, execute functions, and maintain persistent state through MCP servers. |
| 15 | + |
| 16 | + |
| 17 | +## Why Memobase + MCP? |
| 18 | + |
| 19 | +Traditional AI conversations are stateless - each interaction starts fresh without memory of previous exchanges. Memobase MCP changes this by providing: |
| 20 | + |
| 21 | +1. **Persistent Memory**: Store conversation history and user preferences across sessions |
| 22 | +2. **Semantic Search**: Find relevant context using natural language queries |
| 23 | +3. **User Profiles**: Build comprehensive understanding of users over time |
| 24 | +4. **Cross-Platform**: Works with any MCP-compatible client (Claude Desktop, Cursor, Windsurf, etc.) |
| 25 | + |
| 26 | +## Setup |
| 27 | + |
| 28 | +### Prerequisites |
| 29 | +- Python 3.11+ |
| 30 | +- A Memobase backend (local or cloud) |
| 31 | + |
| 32 | +### Get Your Memobase Credentials |
| 33 | + |
| 34 | +You'll need: |
| 35 | +- **Project URL**: `http://localhost:8019` (local) or `https://api.memobase.dev` (cloud) |
| 36 | +- **API Key**: `secret` (local) or `sk-proj-xxxxxx` (cloud) |
| 37 | + |
| 38 | +Get free cloud credits at [Memobase Dashboard](https://www.memobase.io/en) or [deploy locally](../server/readme.md). |
| 39 | + |
| 40 | +### Installation Options |
| 41 | + |
| 42 | +#### Option 1: Using uv (Recommended) |
| 43 | + |
| 44 | +```bash |
| 45 | +# Install uv if you don't have it |
| 46 | +pip install uv |
| 47 | + |
| 48 | +# Clone the repository |
| 49 | +git clone https://github.com/memodb-io/memobase |
| 50 | +cd memobase/src/mcp |
| 51 | + |
| 52 | +# Install dependencies |
| 53 | +uv pip install -e . |
| 54 | + |
| 55 | +# Configure environment |
| 56 | +cp .env.example .env |
| 57 | +# Edit .env with your Memobase credentials |
| 58 | +``` |
| 59 | + |
| 60 | +#### Option 2: Using Docker |
| 61 | + |
| 62 | +```bash |
| 63 | +# Build the Docker image |
| 64 | +docker build -t memobase-mcp --build-arg PORT=8050 . |
| 65 | + |
| 66 | +# Create and configure .env file |
| 67 | +cp .env.example .env |
| 68 | +# Edit .env with your credentials |
| 69 | +``` |
| 70 | + |
| 71 | +### Environment Configuration |
| 72 | + |
| 73 | +Configure your `.env` file: |
| 74 | + |
| 75 | +```bash |
| 76 | +TRANSPORT=sse |
| 77 | +HOST=0.0.0.0 |
| 78 | +PORT=8050 |
| 79 | +MEMOBASE_API_KEY=your_api_key_here |
| 80 | +MEMOBASE_BASE_URL=https://api.memobase.dev |
| 81 | +``` |
| 82 | + |
| 83 | +## Running the MCP Server |
| 84 | + |
| 85 | +### Using uv |
| 86 | + |
| 87 | +```bash |
| 88 | +# Start the server |
| 89 | +uv run src/main.py |
| 90 | +``` |
| 91 | + |
| 92 | +### Using Docker |
| 93 | + |
| 94 | +```bash |
| 95 | +# Run with environment file |
| 96 | +docker run --env-file .env -p 8050:8050 memobase-mcp |
| 97 | +``` |
| 98 | + |
| 99 | +The server will start on `http://localhost:8050` and provide an SSE endpoint at `/sse`. |
| 100 | + |
| 101 | +## Integration with MCP Clients |
| 102 | + |
| 103 | +### Cursor Configuration |
| 104 | + |
| 105 | +Add this to your `.cursor/mcp.json`: |
| 106 | + |
| 107 | +```json |
| 108 | +{ |
| 109 | + "mcpServers": { |
| 110 | + "memobase": { |
| 111 | + "transport": "sse", |
| 112 | + "url": "http://localhost:8050/sse" |
| 113 | + } |
| 114 | + } |
| 115 | +} |
| 116 | +``` |
| 117 | + |
| 118 | +### Windsurf Configuration |
| 119 | + |
| 120 | +For Windsurf, use `serverUrl` instead: |
| 121 | + |
| 122 | +```json |
| 123 | +{ |
| 124 | + "mcpServers": { |
| 125 | + "memobase": { |
| 126 | + "transport": "sse", |
| 127 | + "serverUrl": "http://localhost:8050/sse" |
| 128 | + } |
| 129 | + } |
| 130 | +} |
| 131 | +``` |
| 132 | + |
| 133 | +### Claude Desktop Configuration |
| 134 | + |
| 135 | +For stdio transport with Claude Desktop: |
| 136 | + |
| 137 | +```json |
| 138 | +{ |
| 139 | + "mcpServers": { |
| 140 | + "memobase": { |
| 141 | + "command": "python", |
| 142 | + "args": ["path/to/mcp/src/main.py"], |
| 143 | + "env": { |
| 144 | + "TRANSPORT": "stdio", |
| 145 | + "MEMOBASE_API_KEY": "your-api-key", |
| 146 | + "MEMOBASE_BASE_URL": "https://api.memobase.dev" |
| 147 | + } |
| 148 | + } |
| 149 | + } |
| 150 | +} |
| 151 | +``` |
| 152 | + |
| 153 | +## Available Tools |
| 154 | + |
| 155 | +The Memobase MCP server provides three powerful tools: |
| 156 | + |
| 157 | +### 1. `save_memory` |
| 158 | + |
| 159 | +Store any information in long-term memory with semantic indexing. |
| 160 | + |
| 161 | +```python |
| 162 | +# Example usage in your AI agent |
| 163 | +await save_memory("User prefers dark mode and uses Python for backend development") |
| 164 | +``` |
| 165 | + |
| 166 | +**Use cases:** |
| 167 | +- Store user preferences |
| 168 | +- Remember important facts from conversations |
| 169 | +- Save project details and requirements |
| 170 | + |
| 171 | +### 2. `search_memories` |
| 172 | + |
| 173 | +Find relevant context using natural language queries. |
| 174 | + |
| 175 | +```python |
| 176 | +# Search for relevant memories |
| 177 | +context = await search_memories("What programming languages does the user prefer?") |
| 178 | +``` |
| 179 | + |
| 180 | +**Parameters:** |
| 181 | +- `query`: Natural language search query |
| 182 | +- `max_length`: Maximum content length (default: 1000) |
| 183 | + |
| 184 | +### 3. `get_user_profiles` |
| 185 | + |
| 186 | +Retrieve complete user profiles with organized topics and subtopics. |
| 187 | + |
| 188 | +```python |
| 189 | +# Get comprehensive user profile |
| 190 | +profiles = await get_user_profiles() |
| 191 | +``` |
| 192 | + |
| 193 | +Returns structured information about the user organized by topics. |
| 194 | + |
| 195 | +## Code Breakdown |
| 196 | + |
| 197 | +Let's examine the core implementation: |
| 198 | + |
| 199 | +### Server Setup |
| 200 | + |
| 201 | +```python |
| 202 | +from mcp.server.fastmcp import FastMCP, Context |
| 203 | +from memobase import AsyncMemoBaseClient, ChatBlob |
| 204 | +from memobase.utils import string_to_uuid |
| 205 | + |
| 206 | +# Initialize FastMCP server with Memobase context |
| 207 | +mcp = FastMCP( |
| 208 | + "memobase-mcp", |
| 209 | + description="MCP server for long term memory storage and retrieval with Memobase", |
| 210 | + lifespan=memobase_lifespan, |
| 211 | + host=os.getenv("HOST", "0.0.0.0"), |
| 212 | + port=os.getenv("PORT", 8050), |
| 213 | +) |
| 214 | +``` |
| 215 | + |
| 216 | +### Memory Storage Tool |
| 217 | + |
| 218 | +```python |
| 219 | +@mcp.tool() |
| 220 | +async def save_memory(ctx: Context, text: str) -> str: |
| 221 | + """Save information to your long-term memory.""" |
| 222 | + try: |
| 223 | + memobase_client = ctx.request_context.lifespan_context.memobase_client |
| 224 | + messages = [{"role": "user", "content": text}] |
| 225 | + u = await memobase_client.get_or_create_user(DEFAULT_USER_ID) |
| 226 | + await u.insert(ChatBlob(messages=messages)) |
| 227 | + await u.flush() |
| 228 | + return f"Successfully saved memory: {text[:100]}..." |
| 229 | + except Exception as e: |
| 230 | + return f"Error saving memory: {str(e)}" |
| 231 | +``` |
| 232 | + |
| 233 | +### Memory Search Tool |
| 234 | + |
| 235 | +```python |
| 236 | +@mcp.tool() |
| 237 | +async def search_memories(ctx: Context, query: str, max_length: int = 1000) -> str: |
| 238 | + """Search user memories using semantic search.""" |
| 239 | + try: |
| 240 | + memobase_client = ctx.request_context.lifespan_context.memobase_client |
| 241 | + u = await memobase_client.get_or_create_user(DEFAULT_USER_ID) |
| 242 | + context = await u.context( |
| 243 | + chats=[{"role": "user", "content": query}], |
| 244 | + max_token_size=max_length |
| 245 | + ) |
| 246 | + return context |
| 247 | + except Exception as e: |
| 248 | + return f"Error searching memories: {str(e)}" |
| 249 | +``` |
| 250 | + |
| 251 | +### User Profile Tool |
| 252 | + |
| 253 | +```python |
| 254 | +@mcp.tool() |
| 255 | +async def get_user_profiles(ctx: Context) -> str: |
| 256 | + """Get full user profiles with organized topics and subtopics.""" |
| 257 | + try: |
| 258 | + memobase_client = ctx.request_context.lifespan_context.memobase_client |
| 259 | + u = await memobase_client.get_or_create_user(DEFAULT_USER_ID) |
| 260 | + profiles = await u.profile() |
| 261 | + return "\n".join([f"- {p.describe}" for p in profiles]) |
| 262 | + except Exception as e: |
| 263 | + return f"Error retrieving profiles: {str(e)}" |
| 264 | +``` |
| 265 | + |
| 266 | +This tool retrieves structured user profiles that Memobase automatically generates from conversation history. The profiles are organized by topics and subtopics, providing a comprehensive overview of what the system knows about the user. |
| 267 | + |
| 268 | +**Key features:** |
| 269 | +- **Automatic Organization**: Memobase intelligently categorizes information into topics |
| 270 | +- **Structured Output**: Returns formatted profiles with clear descriptions |
| 271 | +- **Comprehensive View**: Provides a complete picture of stored user information |
| 272 | + |
| 273 | +## Real-World Example |
| 274 | + |
| 275 | +Here's how the Memobase MCP transforms AI interactions: |
| 276 | + |
| 277 | +**Without Memory:** |
| 278 | +``` |
| 279 | +User: "I prefer Python for backend development" |
| 280 | +AI: "That's great! Python is excellent for backend work." |
| 281 | +
|
| 282 | +[Later conversation] |
| 283 | +User: "What's the best language for my new API?" |
| 284 | +AI: "There are many options like Python, Node.js, Go..." |
| 285 | +``` |
| 286 | + |
| 287 | +**With Memobase MCP:** |
| 288 | +``` |
| 289 | +User: "I prefer Python for backend development" |
| 290 | +AI: "That's great! I'll remember your Python preference." |
| 291 | +[Memory saved: "User prefers Python for backend development"] |
| 292 | +
|
| 293 | +[Later conversation] |
| 294 | +User: "What's the best language for my new API?" |
| 295 | +AI: [Searches memories] "Based on your preference for Python, I'd recommend using Python with FastAPI or Django for your new API." |
| 296 | +``` |
| 297 | + |
| 298 | +## Best Practices |
| 299 | + |
| 300 | +1. **Error Handling**: Always wrap MCP tools in try-catch blocks |
| 301 | +2. **Memory Efficiency**: Use appropriate `max_length` parameters for searches |
| 302 | +3. **User Privacy**: Implement proper user isolation for multi-user scenarios |
| 303 | +4. **Performance**: Use async operations for better concurrency |
| 304 | +5. **Monitoring**: Add logging for debugging and monitoring |
| 305 | + |
| 306 | +## Conclusion |
| 307 | + |
| 308 | +The Memobase MCP server bridges the gap between stateless AI interactions and truly intelligent, context-aware agents. By providing persistent memory capabilities through the standardized MCP protocol, you can build AI applications that learn and remember across conversations. |
| 309 | + |
| 310 | +Whether you're building customer service bots, personal assistants, or complex AI workflows, the combination of Memobase and MCP provides the foundation for more intelligent and personalized AI experiences. |
| 311 | + |
| 312 | +Get started today by deploying your own Memobase MCP server and transforming your AI agents from forgetful assistants into intelligent, memory-enabled companions. |
| 313 | + |
| 314 | +> For more advanced configurations and examples, check out the [Full Code](https://github.com/memodb-io/memobase/tree/dev/src/mcp) and explore the [Memobase documentation](https://docs.memobase.io). |
0 commit comments