Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Ignore unnecessary files and directories
**/__pycache__
**/*.pyc
**/*.pyo
**/.env
**/.venv
node_modules
build
1 change: 0 additions & 1 deletion .env

This file was deleted.

176 changes: 176 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
# Created by https://www.toptal.com/developers/gitignore/api/python
# Edit at https://www.toptal.com/developers/gitignore?templates=python

### Python ###
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock

# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/

### Python Patch ###
# Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration
poetry.toml

# ruff
.ruff_cache/

# LSP config files
pyrightconfig.json

# End of https://www.toptal.com/developers/gitignore/api/python
19 changes: 19 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Use the official Python image with version 3.12
FROM python:3.12-slim
# Set the working directory
WORKDIR /app

# Copy only necessary files to the container
COPY . .

# Install uv and project dependencies
RUN pip install uv && uv pip install --system .

# Set environment variable for the port
ENV PORT=8080

# Expose the correct port
EXPOSE ${PORT}

# Command to run the MCP server
CMD ["uv", "run", "main.py"]
48 changes: 45 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,17 @@ source .venv/bin/activate
uv pip install -e .
```

5. Update `.env` file in the root directory with your mem0 API key:
## Setup

Before proceeding, ensure you have created a `.env` file in the root directory with the following content:

```bash
MEM0_API_KEY=your_api_key_here
```
MEM0_API_KEY=<your-api-key>
HOST=<your-host> # Optional, defaults to 0.0.0.0
PORT=<your-port> # Optional, defaults to 8080
```

Replace `<your-api-key>`, `<your-host>`, and `<your-port>` with your actual values. These variables are required for the application to function correctly, except `HOST` and `PORT`, which have default values.

## Usage

Expand All @@ -46,6 +52,42 @@ http://0.0.0.0:8080/sse

3. Open the Composer in Cursor and switch to `Agent` mode.

## Using Docker

To run the MCP server with Docker, follow these steps:

1. Build and start the Docker container using `docker-compose`:

```bash
docker-compose up --build -d
```

This command will build the Docker image and start the container in detached mode.

2. Verify that the container is running:

```bash
docker ps
```

You should see the `mem0-server` container listed.

3. Access the MCP server at the configured endpoint:

```
http://<your-host>:<your-port>/sse
```

Replace `<your-host>` and `<your-port>` with the values you set in the `.env` file.

4. To stop the container, use:

```bash
docker-compose down
```

This will stop and remove the container.

## Demo with Cursor

https://github.com/user-attachments/assets/56670550-fb11-4850-9905-692d3496231c
Expand Down
12 changes: 12 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
version: '3.8'

services:
mem0-server:
build:
context: .
dockerfile: Dockerfile
ports:
- "${PORT:-8080}:${PORT:-8080}"
env_file:
- .env
restart: always
60 changes: 45 additions & 15 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from __future__ import annotations
from mcp.server.fastmcp import FastMCP
from starlette.applications import Starlette
from mcp.server.sse import SseServerTransport
Expand All @@ -8,6 +9,7 @@
from mem0 import MemoryClient
from dotenv import load_dotenv
import json
import os

load_dotenv()

Expand Down Expand Up @@ -107,18 +109,24 @@ async def get_all_coding_preferences() -> str:
providing answers to ensure you leverage existing knowledge."""
)
async def search_coding_preferences(query: str) -> str:
"""Search coding preferences using semantic search.

The search is powered by natural language understanding, allowing you to find:
- Code implementations and patterns
- Programming solutions and techniques
- Technical documentation and guides
- Best practices and standards
Results are ranked by relevance to your query.

Args:
query: Search query string describing what you're looking for. Can be natural language
or specific technical terms.
"""
Search coding preferences using semantic search.

Parameters
----------
query : str
Search query string describing what you're looking for. Can be natural language
or specific technical terms.

Returns
-------
str
A JSON formatted string containing the search results, ranked by relevance.

Examples
--------
>>> result = await search_coding_preferences("Python type annotations")
>>> print(result)
"""
try:
memories = mem0_client.search(query, user_id=DEFAULT_USER_ID, output_format="v1.1")
Expand All @@ -127,8 +135,29 @@ async def search_coding_preferences(query: str) -> str:
except Exception as e:
return f"Error searching preferences: {str(e)}"

# Updated type annotations to Python >3.11 style and added numpy-style docstrings with examples
def create_starlette_app(mcp_server: Server, *, debug: bool = False) -> Starlette:
"""Create a Starlette application that can server the provied mcp server with SSE."""
"""
Create a Starlette application that can serve the provided MCP server with SSE.

Parameters
----------
mcp_server : Server
The MCP server instance to serve.
debug : bool, optional
Whether to enable debug mode, by default False.

Returns
-------
Starlette
A configured Starlette application.

Examples
--------
>>> from mcp.server import Server
>>> server = Server()
>>> app = create_starlette_app(server, debug=True)
"""
sse = SseServerTransport("/messages/")

async def handle_sse(request: Request) -> None:
Expand Down Expand Up @@ -158,11 +187,12 @@ async def handle_sse(request: Request) -> None:
import argparse

parser = argparse.ArgumentParser(description='Run MCP SSE-based server')
parser.add_argument('--host', default='0.0.0.0', help='Host to bind to')
parser.add_argument('--port', type=int, default=8080, help='Port to listen on')
parser.add_argument('--host', default=os.getenv("HOST", '0.0.0.0'), help='Host to bind to')
parser.add_argument('--port', type=int, default=int(os.getenv("PORT", 8080)), help='Port to listen on')
args = parser.parse_args()

# Bind SSE request handling to MCP server
starlette_app = create_starlette_app(mcp_server, debug=True)

# Use the port from CLI arguments
uvicorn.run(starlette_app, host=args.host, port=args.port)