Add MCP HTTP/SSE server and complete n8n integration

Major Changes:
- Implemented MCP HTTP/SSE transport server for n8n and web clients
- Created mcp_server/http_server.py with FastAPI for JSON-RPC 2.0 over HTTP
- Added health check endpoint (/health) for container monitoring
- Refactored mcp-server/ to mcp_server/ (Python module structure)
- Updated Dockerfile.mcp to run HTTP server with health checks

MCP Server Features:
- 7 memory tools exposed via MCP (add, search, get, update, delete)
- HTTP/SSE transport on port 8765 for n8n integration
- stdio transport for Claude Code integration
- JSON-RPC 2.0 protocol implementation
- CORS support for web clients

n8n Integration:
- Successfully tested with AI Agent workflows
- MCP Client Tool configuration documented
- Working webhook endpoint tested and verified
- System prompt optimized for automatic user_id usage

Documentation:
- Created comprehensive Mintlify documentation site
- Added docs/mcp/introduction.mdx - MCP server overview
- Added docs/mcp/installation.mdx - Installation guide
- Added docs/mcp/tools.mdx - Complete tool reference
- Added docs/examples/n8n.mdx - n8n integration guide
- Added docs/examples/claude-code.mdx - Claude Code setup
- Updated README.md with MCP HTTP server info
- Updated roadmap to mark Phase 1 as complete

Bug Fixes:
- Fixed synchronized delete operations across Supabase and Neo4j
- Updated memory_service.py with proper error handling
- Fixed Neo4j connection issues in delete operations

Configuration:
- Added MCP_HOST and MCP_PORT environment variables
- Updated .env.example with MCP server configuration
- Updated docker-compose.yml with MCP container health checks

Testing:
- Added test scripts for MCP HTTP endpoint verification
- Created test workflows in n8n
- Verified all 7 memory tools working correctly
- Tested synchronized operations across both stores

Version: 1.0.0
Status: Phase 1 Complete - Production Ready

🤖 Generated with Claude Code

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Claude Code
2025-10-15 13:56:41 +02:00
parent 9bca2f4f47
commit 1998bef6f4
36 changed files with 3443 additions and 71 deletions

230
docs/mcp/installation.mdx Normal file
View File

@@ -0,0 +1,230 @@
---
title: 'MCP Server Installation'
description: 'Install and configure the T6 Mem0 v2 MCP server'
---
# Installing the MCP Server
The MCP server can be run in two modes: HTTP/SSE for web integrations, or stdio for local tool usage.
## Prerequisites
- Python 3.11+
- Running Supabase instance (vector store)
- Running Neo4j instance (graph store)
- OpenAI API key
## Environment Setup
Create a `.env` file with required configuration:
```bash
# OpenAI
OPENAI_API_KEY=your_openai_key_here
# Supabase (Vector Store)
SUPABASE_CONNECTION_STRING=postgresql://user:pass@host:port/database
# Neo4j (Graph Store)
NEO4J_URI=neo4j://localhost:7687
NEO4J_USER=neo4j
NEO4J_PASSWORD=your_neo4j_password
# MCP Server
MCP_HOST=0.0.0.0
MCP_PORT=8765
# Mem0 Configuration
MEM0_COLLECTION_NAME=t6_memories
MEM0_EMBEDDING_DIMS=1536
MEM0_VERSION=v1.1
```
## Installation Methods
### Method 1: Docker (Recommended)
The easiest way to run the MCP server is using Docker Compose:
```bash
# Clone the repository
git clone https://git.colsys.tech/klas/t6_mem0_v2
cd t6_mem0_v2
# Copy and configure environment
cp .env.example .env
# Edit .env with your settings
# Start all services
docker compose up -d
# MCP HTTP server will be available at http://localhost:8765
```
**Health Check**:
```bash
curl http://localhost:8765/health
# {"status":"healthy","service":"t6-mem0-v2-mcp-http","transport":"http-streamable"}
```
### Method 2: Local Python
For development or local usage:
```bash
# Install dependencies
pip install -r requirements.txt
# Run HTTP server
python -m mcp_server.http_server
# Or run stdio server (for Claude Code)
python -m mcp_server.main
```
## Verify Installation
### Test HTTP Endpoint
```bash
curl -X POST "http://localhost:8765/mcp" \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/list",
"params": {}
}'
```
Expected response:
```json
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"tools": [
{
"name": "add_memory",
"description": "Add new memory from messages...",
"inputSchema": {...}
},
// ... 6 more tools
]
}
}
```
### Test stdio Server
```bash
echo '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}' | python -m mcp_server.main
```
## Docker Configuration
The MCP server is configured in `docker-compose.yml`:
```yaml
mcp-server:
build:
context: .
dockerfile: docker/Dockerfile.mcp
container_name: t6-mem0-mcp
restart: unless-stopped
ports:
- "8765:8765"
environment:
- OPENAI_API_KEY=${OPENAI_API_KEY}
- SUPABASE_CONNECTION_STRING=${SUPABASE_CONNECTION_STRING}
- NEO4J_URI=neo4j://neo4j:7687
- NEO4J_USER=${NEO4J_USER}
- NEO4J_PASSWORD=${NEO4J_PASSWORD}
- MCP_HOST=0.0.0.0
- MCP_PORT=8765
depends_on:
neo4j:
condition: service_healthy
networks:
- localai
healthcheck:
test: ["CMD-SHELL", "curl -f http://localhost:8765/health || exit 1"]
interval: 30s
timeout: 10s
retries: 3
```
## Network Configuration
For n8n integration on the same Docker network:
```yaml
# Add to your n8n docker-compose.yml
networks:
localai:
external: true
services:
n8n:
networks:
- localai
```
Then use internal Docker network IP in n8n:
```
http://172.21.0.14:8765/mcp
```
Find the MCP container IP:
```bash
docker inspect t6-mem0-mcp --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}'
```
## Troubleshooting
### Container Won't Start
Check logs:
```bash
docker logs t6-mem0-mcp --tail 50
```
Common issues:
- Missing environment variables
- Cannot connect to Neo4j or Supabase
- Port 8765 already in use
### Health Check Failing
Verify services are reachable:
```bash
# Test Neo4j connection
docker exec t6-mem0-mcp curl http://neo4j:7474
# Test from host
curl http://localhost:8765/health
```
### n8n Can't Connect
1. Verify same Docker network:
```bash
docker network inspect localai
```
2. Test connectivity from n8n container:
```bash
docker run --rm --network localai alpine/curl:latest \
curl -s http://172.21.0.14:8765/health
```
## Next Steps
<CardGroup cols={2}>
<Card title="Tool Reference" icon="wrench" href="/mcp/tools">
Learn about available MCP tools
</Card>
<Card title="n8n Integration" icon="workflow" href="/examples/n8n">
Use MCP in n8n workflows
</Card>
</CardGroup>

117
docs/mcp/introduction.mdx Normal file
View File

@@ -0,0 +1,117 @@
---
title: 'MCP Server Introduction'
description: 'Model Context Protocol server for AI-powered memory operations'
---
# MCP Server Overview
The T6 Mem0 v2 MCP (Model Context Protocol) server provides a standardized interface for AI assistants and agents to interact with the memory system. It exposes all memory operations as MCP tools that can be used by any MCP-compatible client.
## What is MCP?
Model Context Protocol (MCP) is an open protocol that standardizes how applications provide context to LLMs. Created by Anthropic, it enables:
- **Universal tool access** - One protocol works across all AI assistants
- **Secure communication** - Structured message format with validation
- **Rich capabilities** - Tools, resources, and prompts in a single protocol
## Features
- ✅ **7 Memory Tools** - Complete CRUD operations for memories
- ✅ **HTTP/SSE Transport** - Compatible with n8n and web-based clients
- ✅ **stdio Transport** - Compatible with Claude Code and terminal-based clients
- ✅ **Synchronized Operations** - Ensures both Supabase and Neo4j stay in sync
- ✅ **Type-safe** - Full schema validation for all operations
## Available Tools
| Tool | Description |
|------|-------------|
| `add_memory` | Store new memories from conversation messages |
| `search_memories` | Semantic search across stored memories |
| `get_memory` | Retrieve a specific memory by ID |
| `get_all_memories` | Get all memories for a user or agent |
| `update_memory` | Update existing memory content |
| `delete_memory` | Delete a specific memory |
| `delete_all_memories` | Delete all memories for a user/agent |
## Transport Options
### HTTP/SSE Transport
Best for:
- n8n workflows
- Web applications
- REST API integrations
- Remote access
**Endpoint**: `http://localhost:8765/mcp`
### stdio Transport
Best for:
- Claude Code integration
- Local development tools
- Command-line applications
- Direct Python integration
**Usage**: Run as a subprocess with JSON-RPC over stdin/stdout
## Quick Example
```javascript
// Using n8n MCP Client Tool
{
"endpointUrl": "http://172.21.0.14:8765/mcp",
"serverTransport": "httpStreamable",
"authentication": "none",
"include": "all"
}
```
```python
# Using Python MCP SDK
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
server_params = StdioServerParameters(
command="python",
args=["-m", "mcp_server.main"]
)
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
# List available tools
tools = await session.list_tools()
# Call a tool
result = await session.call_tool(
"add_memory",
arguments={
"messages": [
{"role": "user", "content": "I love Python"},
{"role": "assistant", "content": "Noted!"}
],
"user_id": "user_123"
}
)
```
## Next Steps
<CardGroup cols={2}>
<Card title="Installation" icon="download" href="/mcp/installation">
Set up the MCP server locally or in Docker
</Card>
<Card title="Tool Reference" icon="wrench" href="/mcp/tools">
Detailed documentation for all available tools
</Card>
<Card title="n8n Integration" icon="workflow" href="/examples/n8n">
Use MCP tools in n8n AI Agent workflows
</Card>
<Card title="Claude Code" icon="code" href="/examples/claude-code">
Integrate with Claude Code for AI-powered coding
</Card>
</CardGroup>

384
docs/mcp/tools.mdx Normal file
View File

@@ -0,0 +1,384 @@
---
title: 'MCP Tool Reference'
description: 'Complete reference for all 7 memory operation tools'
---
# MCP Tool Reference
The T6 Mem0 v2 MCP server provides 7 tools for complete memory lifecycle management. All tools use JSON-RPC 2.0 protocol and support both HTTP/SSE and stdio transports.
## add_memory
Store new memories extracted from conversation messages.
### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `messages` | Array | Yes | Array of message objects with `role` and `content` |
| `user_id` | String | No | User identifier for memory association |
| `agent_id` | String | No | Agent identifier for memory association |
| `metadata` | Object | No | Additional metadata to store with memories |
### Example Request
```json
{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {
"name": "add_memory",
"arguments": {
"messages": [
{"role": "user", "content": "I love Python programming"},
{"role": "assistant", "content": "Great! I'll remember that."}
],
"user_id": "user_123",
"metadata": {"source": "chat", "session_id": "abc-123"}
}
}
}
```
### Example Response
```json
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"content": [
{
"type": "text",
"text": "Added 1 memories for user user_123"
}
]
}
}
```
## search_memories
Search memories using semantic similarity matching.
### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `query` | String | Yes | Search query text |
| `user_id` | String | No | Filter by user ID |
| `agent_id` | String | No | Filter by agent ID |
| `limit` | Integer | No | Maximum results (default: 10, max: 50) |
### Example Request
```json
{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/call",
"params": {
"name": "search_memories",
"arguments": {
"query": "What programming languages does the user like?",
"user_id": "user_123",
"limit": 5
}
}
}
```
### Example Response
```json
{
"jsonrpc": "2.0",
"id": 2,
"result": {
"content": [
{
"type": "text",
"text": "Found 2 memories:\n1. ID: mem_abc123 - User loves Python programming (score: 0.92)\n2. ID: mem_def456 - User interested in JavaScript (score: 0.78)"
}
]
}
}
```
## get_memory
Retrieve a specific memory by its ID.
### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `memory_id` | String | Yes | Unique memory identifier |
### Example Request
```json
{
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "get_memory",
"arguments": {
"memory_id": "mem_abc123"
}
}
}
```
### Example Response
```json
{
"jsonrpc": "2.0",
"id": 3,
"result": {
"content": [
{
"type": "text",
"text": "Memory: User loves Python programming\nCreated: 2025-10-15T10:30:00Z\nUser: user_123"
}
]
}
}
```
## get_all_memories
Retrieve all memories for a specific user or agent.
### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `user_id` | String | No* | User identifier |
| `agent_id` | String | No* | Agent identifier |
*At least one of `user_id` or `agent_id` must be provided.
### Example Request
```json
{
"jsonrpc": "2.0",
"id": 4,
"method": "tools/call",
"params": {
"name": "get_all_memories",
"arguments": {
"user_id": "user_123"
}
}
}
```
### Example Response
```json
{
"jsonrpc": "2.0",
"id": 4,
"result": {
"content": [
{
"type": "text",
"text": "Found 3 memories for user user_123:\n1. User loves Python programming\n2. User interested in JavaScript\n3. User works as software engineer"
}
]
}
}
```
## update_memory
Update the content of an existing memory.
### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `memory_id` | String | Yes | Unique memory identifier |
| `data` | String | Yes | New memory content |
### Example Request
```json
{
"jsonrpc": "2.0",
"id": 5,
"method": "tools/call",
"params": {
"name": "update_memory",
"arguments": {
"memory_id": "mem_abc123",
"data": "User is an expert Python developer"
}
}
}
```
### Example Response
```json
{
"jsonrpc": "2.0",
"id": 5,
"result": {
"content": [
{
"type": "text",
"text": "Memory mem_abc123 updated successfully"
}
]
}
}
```
## delete_memory
Delete a specific memory by ID.
### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `memory_id` | String | Yes | Unique memory identifier |
### Example Request
```json
{
"jsonrpc": "2.0",
"id": 6,
"method": "tools/call",
"params": {
"name": "delete_memory",
"arguments": {
"memory_id": "mem_abc123"
}
}
}
```
### Example Response
```json
{
"jsonrpc": "2.0",
"id": 6,
"result": {
"content": [
{
"type": "text",
"text": "Memory mem_abc123 deleted successfully from both vector and graph stores"
}
]
}
}
```
## delete_all_memories
Delete all memories for a specific user or agent.
### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `user_id` | String | No* | User identifier |
| `agent_id` | String | No* | Agent identifier |
*At least one of `user_id` or `agent_id` must be provided.
<Warning>
This operation is irreversible. All memories for the specified user/agent will be permanently deleted from both Supabase (vector store) and Neo4j (graph store).
</Warning>
### Example Request
```json
{
"jsonrpc": "2.0",
"id": 7,
"method": "tools/call",
"params": {
"name": "delete_all_memories",
"arguments": {
"user_id": "user_123"
}
}
}
```
### Example Response
```json
{
"jsonrpc": "2.0",
"id": 7,
"result": {
"content": [
{
"type": "text",
"text": "Deleted 3 memories for user user_123"
}
]
}
}
```
## Error Responses
All tools return standardized error responses:
```json
{
"jsonrpc": "2.0",
"id": 1,
"error": {
"code": -32603,
"message": "Internal error: Memory not found",
"data": {
"type": "MemoryNotFoundError",
"details": "No memory exists with ID mem_xyz789"
}
}
}
```
### Common Error Codes
| Code | Description |
|------|-------------|
| `-32700` | Parse error - Invalid JSON |
| `-32600` | Invalid request - Missing required fields |
| `-32601` | Method not found - Unknown tool name |
| `-32602` | Invalid params - Invalid arguments |
| `-32603` | Internal error - Server-side error |
## Synchronized Operations
<Info>
All delete operations (both `delete_memory` and `delete_all_memories`) are synchronized across both storage backends:
- **Supabase (Vector Store)**: Removes embeddings and memory records
- **Neo4j (Graph Store)**: Removes nodes and relationships
This ensures data consistency across the entire memory system.
</Info>
## Next Steps
<CardGroup cols={2}>
<Card title="n8n Integration" icon="workflow" href="/examples/n8n">
Use MCP tools in n8n workflows
</Card>
<Card title="Claude Code" icon="code" href="/examples/claude-code">
Integrate with Claude Code
</Card>
</CardGroup>