agentmemory-mcp-gateway
Enables remote MCP clients to securely access AgentMemory tools like memory_recall, memory_smart_search, and memory_save through OAuth 2.1 and Streamable HTTP, while keeping the AgentMemory backend secret private.
README
agentmemory-mcp-gateway
Single-user OAuth 2.1 gateway that exposes a small AgentMemory MCP tool set to remote clients.
MCP clients authenticate to this service. This service authenticates to AgentMemory. The AgentMemory backend secret never leaves the gateway.
What it does
- Speaks remote MCP over Streamable HTTP at
/mcp - Acts as the OAuth authorization server and protected resource
- Allows exactly one pre-seeded human to sign in and grant consent
- Forwards allowlisted
tools/listandtools/calltraffic to AgentMemory REST - Fails closed when AgentMemory is unavailable
Intended clients: ChatGPT, Notion Custom Agents, Codex cloud, and other standards-compliant remote MCP clients.
Public URL shape:
https://memory-mcp.example.com/mcp
Architecture
MCP client
-> HTTPS gateway (this service)
-> private AgentMemory REST API
Trust boundaries:
- MCP clients see only the public HTTPS origin, OAuth metadata, and allowlisted tool schemas/results.
- AgentMemory stays on Railway private networking. Clients never receive
AGENTMEMORY_URLorAGENTMEMORY_SECRET. - Incoming
Authorizationheaders are used only to validate the client access token. The gateway always builds a newAuthorization: Bearer ${AGENTMEMORY_SECRET}header for upstream calls. - SQLite stores authentication and OAuth state only. It is not a memory database.
This is a separate Railway service from AgentMemory. Run exactly one replica.
Why REST instead of @agentmemory/mcp
@agentmemory/mcp can fall back to a local memory database when upstream is unreachable. That is unacceptable for a remote personal gateway.
This service calls only:
GET /agentmemory/mcp/toolsPOST /agentmemory/mcp/callwith{ "name": string, "arguments": object }
If AgentMemory is down, malformed, or times out, the gateway returns a safe MCP error. It does not create, open, or write another memory store.
Why SQLite exists
SQLite at DATABASE_PATH (default /data/oauth.sqlite) holds:
- the one user and password hash
- sessions and consent
- OAuth client registrations
- authorization codes
- access/refresh-token and revocation state
- signing keys / JWKS
It never stores AgentMemory observations or embeddings.
The in-memory rate limiter is also single-replica only. Do not scale this service horizontally.
Strict single-user model
- Email/password only
- No GitHub, social login, magic links, invitations, or password recovery
- No public signup and no user-management API
- Client registration (CIMD / DCR) is not human registration
- Only the seeded user's durable ID may sign in, approve consent, or receive usable MCP tokens
- Production startup fails if the user table does not contain exactly one row
Authentication errors are generic. They do not disclose whether an email exists.
Environment
| Variable | Required | Purpose |
|---|---|---|
PUBLIC_URL |
yes | Canonical public origin. No path, query, fragment, or credentials. HTTPS except loopback. |
BETTER_AUTH_SECRET |
yes | Better Auth signing/encryption secret, 32+ characters |
DATABASE_PATH |
yes | SQLite file path, for example /data/oauth.sqlite |
AGENTMEMORY_URL |
yes | Private AgentMemory origin |
AGENTMEMORY_SECRET |
yes | Backend bearer for AgentMemory, 32+ characters |
ALLOWED_TOOLS |
no | Default memory_recall,memory_smart_search,memory_save |
PORT |
no | Listen port. Railway sets this. Default 8080 |
ADMIN_EMAIL |
seed only | Administrator email |
ADMIN_PASSWORD |
seed only | Strong generated password, 20+ characters |
PUBLIC_URL is the single issuer and the origin for /mcp. The protected resource identifier is ${PUBLIC_URL}/mcp.
Copy .env.example. It contains placeholders only.
Local development
nvm install
cp .env.example .env
# fill local loopback values, for example PUBLIC_URL=http://127.0.0.1:8080
npm install
npm run seed-admin
# remove ADMIN_PASSWORD from .env
npm run dev
Useful checks:
npm run format
npm run lint
npm run typecheck
npm test
npm run build
Secure one-time administrator seeding
railway run only injects variables into a local command. It cannot write to the Railway volume. Seed inside the deployed container after /data is mounted.
Local
npm run seed-admin
# remove ADMIN_PASSWORD from .env
Production image / Railway
The image includes dist/seed-admin.js and starts with node dist/start.js.
- Generate a long random password in 1Password. Do not store it in git, SQLite, Docker, or logs.
- Set temporary
ADMIN_EMAILandADMIN_PASSWORD(20+ characters) on the service. - Deploy or restart so the container runs with
/datamounted. - With those variables set,
node dist/start.jsrunsnode dist/seed-admin.jsin-process, prints the durable user ID, and exits0without opening the HTTP port. - Remove
ADMIN_PASSWORDandADMIN_EMAIL, then restart. The process then serves HTTP. - If both variables are still set after a user exists, startup logs that they must be removed and exits
0so Railway does not crash-loop. - If only one of
ADMIN_EMAILorADMIN_PASSWORDis set, startup fails closed and does not serve HTTP.
Manual in-container equivalent after the volume exists:
railway ssh -- node dist/seed-admin.js
Do not use railway run npm run seed-admin for production seeding. That command runs on your machine.
The production HTTP process will not start until that one user exists and the seed variables are gone.
Docker
docker build -t agentmemory-mcp-gateway .
docker run --rm -p 8080:8080 \
-e PUBLIC_URL=http://127.0.0.1:8080 \
-e BETTER_AUTH_SECRET=... \
-e DATABASE_PATH=/data/oauth.sqlite \
-e AGENTMEMORY_URL=http://127.0.0.1:3111 \
-e AGENTMEMORY_SECRET=... \
-v gateway-data:/data \
agentmemory-mcp-gateway
The entrypoint starts as root, verifies DATABASE_PATH is an absolute file under /data (or RAILWAY_VOLUME_MOUNT_PATH), chowns only that directory plus the SQLite/WAL/SHM files, then drops to UID/GID 10001 before node runs. It never recursively chowns / or other parents. Mount a persistent volume at /data.
Railway
- Create a new service from this repository. Do not deploy onto the AgentMemory service.
- Use the Dockerfile /
railway.jsonin the repo root. - Attach a persistent volume mounted at
/data. Railway mounts volumes as root and replaces the image/datadirectory. - Set
RAILWAY_RUN_UID=0so the entrypoint canchown/data, then drop to UID10001. Leaving the process as root is a tradeoff; this image does not keep root after startup. - Set replicas to 1. A single SQLite volume cannot be shared safely.
- Set the environment variables above. Use the private AgentMemory URL, such as
http://<agentmemory-service>.railway.internal:3111. - Attach the public custom domain and set
PUBLIC_URLto that exacthttps://origin. - Seed the administrator once with the in-container path above, then delete the temporary password variables.
- Confirm
GET /healthzreturns{"ok":true}.
Do not put AgentMemory on the public internet for this flow. The gateway is the only public MCP endpoint.
Connecting ChatGPT
- Deploy with a stable HTTPS origin and
/mcp. - In ChatGPT, add a remote MCP / connector URL:
https://<your-domain>/mcp. - Prefer CIMD if ChatGPT offers it. DCR remains enabled as a fallback.
- Complete the hosted sign-in and consent screens as the seeded user.
- Confirm
memory_recall,memory_smart_search, andmemory_saveappear.
ChatGPT discovers /.well-known/oauth-protected-resource and the authorization-server metadata automatically.
Connecting Notion Custom Agents
- Enable custom MCP servers in the Notion workspace if required.
- Add a custom MCP server URL:
https://<your-domain>/mcp. - Notion uses OAuth and typically DCR unless a client is preregistered.
- Sign in as the seeded user and approve consent.
- Enable only the tools that agent should use.
Basic end-to-end verification
curl -sS https://<your-domain>/healthz
curl -sS https://<your-domain>/.well-known/oauth-authorization-server
curl -sS https://<your-domain>/.well-known/oauth-protected-resource
curl -sS -D- https://<your-domain>/mcp \
-H 'content-type: application/json' \
-H 'accept: application/json, text/event-stream' \
-d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}'
The /mcp call must return 401 with a WWW-Authenticate challenge that points at protected-resource metadata. After a real client login, tools/list must show only the allowlisted tools.
Revoking clients and tokens
SQLite is the source of truth for OAuth clients, refresh tokens, and consent.
- Delete or rotate
BETTER_AUTH_SECRETonly if you intend to invalidate signing material and re-seed carefully. - Removing an
oauthClientrow, related tokens, and consent records revokes that client. - Replacing the SQLite file logs every client out.
There is no admin API. Use a one-off sqlite3 session against the volume if you need to revoke a specific client.
Backup and recovery
Copy /data/oauth.sqlite and the -wal/-shm files together while the service is stopped, or use sqlite3 .backup. A lost volume means every OAuth client must reconnect and the administrator must be seeded again. This backup is authentication state, not AgentMemory.
Known limitations
- One replica only. Rate limits are in-memory.
- No password reset. If the password is lost, restore SQLite from backup or delete the user table and seed again.
- No dashboard and no multi-user support.
- The MCP handler keeps official SDK legacy (
2025) protocol support in stateless mode so ChatGPT and Notion are not rejected. The OAuth stack follows current Better Auth MCP APIs, including CIMD plus explicit DCR. - mTLS client authentication advertised by ChatGPT is terminated at the HTTPS edge, not verified inside this process.
Cloud agents
Cursor Cloud uses .cursor/environment.json:
- Dockerfile — Ubuntu 24.04, Node 24 (nvm), npm, and agentfiles
- install — refreshes agentfiles and runs
npm ciwhenpackage-lock.jsonexists
Local development uses the same Node version via .nvmrc for the cloud image. The gateway runtime itself targets Node 22.
Recommended Servers
playwright-mcp
A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.
Magic Component Platform (MCP)
An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.
Audiense Insights MCP Server
Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.
VeyraX MCP
Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.
graphlit-mcp-server
The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.
Kagi MCP Server
An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.
E2B
Using MCP to run code via e2b.
Neon Database
MCP server for interacting with Neon Management API and databases
Exa Search
A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.
Qdrant Server
This repository is an example of how to create a MCP server for Qdrant, a vector search engine.