mcp-brain

mcp-brain

A personal second brain on Cloudflare Workers that stores knowledge as a semantic graph with auto-linking, deduplication, and MCP tools for AI agents to save, search, and connect information.

Category
Visit Server

README

MCP Brain

A personal second brain that runs on Cloudflare Workers. Everything is a node in a semantic knowledge graph — thoughts, tasks, people, books, bookmarks, and any custom type you define. Nodes auto-link based on meaning, deduplicate intelligently, and are fully searchable through the Model Context Protocol (MCP).

Built for AI agents. You talk to your AI assistant, and it remembers things for you — no manual note-taking, no app-switching, no friction.

How It Works

You ←→ AI Assistant ←→ MCP Brain (Cloudflare Worker) ←→ Supabase Postgres + pgvector
                              ↕
                     Cloudflare Workers AI
                  (embeddings, dedup, synthesis)
  1. You talk to an AI assistant (Claude, GPT, or any MCP-compatible client)
  2. The assistant uses MCP tools to save, search, and connect your knowledge
  3. New nodes are automatically embedded, deduplicated, and linked to related nodes
  4. Everything is stored in your own Supabase Postgres database with vector search

Features

  • Semantic search — Find nodes by meaning, not just keywords. Works in any language.
  • Auto-linking — New nodes automatically connect to semantically similar existing nodes (cosine similarity 0.5–0.92).
  • 3-tier deduplication — Exact match → high-similarity auto-merge (>0.85) → LLM-confirmed merge (0.5–0.85) → create new.
  • Flexible types — Define any node type with a metadata schema. Ships with none — you create what you need (thought, action, person, bookmark, etc.).
  • Tag taxonomy — Organize with tags. Tags can be marked as "projects" for project management.
  • Graph exploration — Traverse connections, find forgotten nodes, consolidate sparse profiles from linked context.
  • Skills system — Store reusable instruction sets (personas, writing styles, workflows) that your AI agent can load and adopt.
  • Daily maintenance — Cron job prunes weak links automatically.
  • OAuth + API key auth — Works with browser-based MCP clients (OAuth) and CLI/API clients (Bearer token).

Prerequisites

You'll need free accounts on two platforms:

  • Cloudflare — Free plan includes Workers, Workers AI, and KV
  • Supabase — Free plan includes Postgres with pgvector

Setup

1. Clone and install

git clone https://github.com/YOUR_USERNAME/mcp-brain.git
cd mcp-brain
pnpm install

2. Set up Supabase

  1. Create a new project at supabase.com
  2. Go to SQL Editor and run the following to enable pgvector and create all tables:
-- Enable pgvector
create extension if not exists vector;

-- Node types (e.g. thought, action, person, bookmark)
create table mb_node_types (
  name text primary key,
  description text not null,
  schema jsonb not null default '{}',
  created_at timestamptz not null,
  embedding vector(1024)
);
create index mb_node_types_embedding_idx on mb_node_types
  using hnsw (embedding vector_cosine_ops);

-- Nodes (the actual knowledge)
create table mb_nodes (
  id uuid primary key,
  type text not null references mb_node_types(name),
  metadata jsonb not null default '{}',
  created_at timestamptz not null,
  embedding vector(1024),
  access_count integer not null default 0,
  last_accessed timestamptz
);
create index mb_nodes_type_idx on mb_nodes(type);
create index mb_nodes_created_at_idx on mb_nodes(created_at);
create index mb_nodes_embedding_idx on mb_nodes
  using hnsw (embedding vector_cosine_ops);

-- Links between nodes (bidirectional, scored)
create table mb_node_links (
  node_a_id uuid not null references mb_nodes(id),
  node_b_id uuid not null references mb_nodes(id),
  label text,
  metadata jsonb not null default '{}',
  created_at timestamptz not null,
  score real not null default 0.5,
  primary key (node_a_id, node_b_id)
);
create index mb_node_links_a_idx on mb_node_links(node_a_id);
create index mb_node_links_b_idx on mb_node_links(node_b_id);
create index mb_node_links_score_idx on mb_node_links(score);

-- Tags
create table mb_tags (
  name text primary key,
  kind text not null default 'tag',
  created_at timestamptz not null,
  embedding vector(1024)
);
create index mb_tags_embedding_idx on mb_tags
  using hnsw (embedding vector_cosine_ops);

-- Node ↔ Tag junction
create table mb_node_tags (
  node_id uuid not null references mb_nodes(id),
  tag_name text not null references mb_tags(name),
  primary key (node_id, tag_name)
);

-- Key-value settings
create table mb_settings (
  key text primary key,
  value jsonb not null
);

-- Skills (reusable instruction sets)
create table mb_skills (
  name text primary key,
  description text not null,
  content text not null,
  embedding vector(1024),
  created_at timestamptz not null,
  updated_at timestamptz not null
);
create index mb_skills_embedding_idx on mb_skills
  using hnsw (embedding vector_cosine_ops);
  1. Get your database connection string:
    • Go to Project SettingsDatabase
    • Copy the Connection string (URI format) under "Connection pooling" — it looks like:
      postgresql://postgres.xxxx:password@aws-0-region.pooler.supabase.com:6543/postgres
      
    • Make sure Connection pooling is enabled (Session mode)

3. Set up Cloudflare

  1. Install wrangler if you haven't: pnpm add -g wrangler
  2. Log in: wrangler login
  3. Create a KV namespace for OAuth state:
wrangler kv namespace create OAUTH_KV
  1. Copy the id from the output and update wrangler.jsonc:
{
  "kv_namespaces": [
    {
      "binding": "OAUTH_KV",
      "id": "YOUR_KV_NAMESPACE_ID"
    }
  ]
}
  1. Set your secrets:
# Your Supabase connection string (the pooler URI from step 2)
wrangler secret put SUPABASE_DB_URL

# An API key you choose — this is your password to the brain
wrangler secret put BRAIN_API_KEY

Pick any strong string for BRAIN_API_KEY — you'll use it to authenticate.

4. Deploy

pnpm run deploy

Your brain is now live at https://mcp-brain.YOUR_SUBDOMAIN.workers.dev.

5. Local development (optional)

Create a .dev.vars file at the project root:

SUPABASE_DB_URL=postgresql://postgres.xxxx:password@aws-0-region.pooler.supabase.com:6543/postgres
BRAIN_API_KEY=your-secret-key

Then run:

pnpm run dev

Connecting Your AI Assistant

MCP Brain exposes an MCP server. Any MCP-compatible client can connect to it.

Claude Desktop / claude.ai

Add to your MCP server configuration:

{
  "mcpServers": {
    "mcp-brain": {
      "url": "https://mcp-brain.YOUR_SUBDOMAIN.workers.dev/mcp/oauth",
      "type": "streamable-http"
    }
  }
}

When you first connect, your browser will open an authorization page. Enter your BRAIN_API_KEY to authenticate. The key can be saved in your browser's local storage for convenience.

Claude Code / CLI clients

CLI clients can skip OAuth and use Bearer token auth directly:

{
  "mcpServers": {
    "mcp-brain": {
      "url": "https://mcp-brain.YOUR_SUBDOMAIN.workers.dev/mcp",
      "type": "streamable-http",
      "headers": {
        "Authorization": "Bearer YOUR_BRAIN_API_KEY"
      }
    }
  }
}

Other MCP clients

MCP Brain supports two auth methods:

Method Endpoint Use case
OAuth 2.0 /mcp/oauth Browser-based clients (Claude Desktop, claude.ai)
Bearer token /mcp CLI tools, scripts, API calls

For Bearer auth, set the header: Authorization: Bearer YOUR_BRAIN_API_KEY

Authentication

OAuth flow (browser clients)

  1. Client initiates OAuth at /mcp/oauth
  2. User is redirected to /authorize — a simple HTML form
  3. User enters their BRAIN_API_KEY
  4. On success, an OAuth token is issued and the client is redirected back
  5. Subsequent requests use the OAuth token automatically

The authorize page supports saving your key in browser local storage so you don't re-enter it every time.

Bearer token (CLI / API)

Send your BRAIN_API_KEY as a Bearer token:

curl -X POST https://mcp-brain.YOUR_SUBDOMAIN.workers.dev/mcp \
  -H "Authorization: Bearer YOUR_BRAIN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc":"2.0","method":"tools/list","id":1}'

MCP Tools Reference

MCP Brain exposes 20 tools organized into 5 categories:

Type management

Tool Description
create_type Define a new node type with a metadata schema (e.g. "recipe", "goal")
list_types List all node types and their schemas
update_type Update a type's description or schema
delete_type Delete a type (fails if nodes of that type exist)

Node CRUD

Tool Description
create_node Save a node — auto-deduplicates, auto-links, resolves tags
search_nodes Semantic + temporal search with filters (type, tags, date, sort)
update_node Update metadata (merged) or tags (replaced)
delete_node Delete a node and all its links/tags
batch_update Add/remove tags on up to 50 nodes at once

Graph

Tool Description
link_manager Manually create or remove links between nodes
explore_connections Browse a node's connections, sort by strongest/weakest

Discovery

Tool Description
list_tags List all tags with counts and kinds, filterable by type or kind
update_tag Rename a tag or change its kind (e.g. mark as "project")
forgotten_nodes Surface least-accessed nodes you may have forgotten
consolidate_node AI-powered: extract facts from linked nodes to enrich a sparse profile
get_stats Brain overview: node counts by type, total links, total tags
set_setting Configure brain settings (currently: timezone)

Skills

Tool Description
list_skills List all stored skills
load_skill Load a skill's instructions for the AI to adopt
manage_skill Create, update, or delete skills

System Prompts

MCP Brain includes system prompts that teach your AI assistant how to use the brain naturally. Choose the one that fits your setup:

File Description
system-prompt-base.md Full behavioral guide — brain usage, anti-sycophancy, response style. Good default.
system-prompt-claude-code.md Lightweight version for dev sessions in Claude Code. Focuses on saving design decisions and architecture insights.
system-prompt-tiny.md Minimal version (~50 lines) for local models with small context windows (LM Studio, Ollama, etc.).

How to use them

Claude Desktop / claude.ai: Copy the content of your chosen system prompt into the "Custom Instructions" or "System Prompt" field in your client settings.

Claude Code: The system-prompt-claude-code.md content goes into ~/.claude/CLAUDE.md (your global instructions file).

LM Studio / Ollama / local models: Use system-prompt-tiny.md as the system message. It's optimized for small context windows.

API usage: Pass the system prompt content as the system message in your API calls.

What the system prompts do

All prompts instruct the AI to:

  1. Initialize silently — On conversation start, search for user identity, recent context, pending tasks, and the tag taxonomy
  2. Save proactively — When you share an idea, decision, task, or mention a person, the AI saves it without asking
  3. Search before guessing — For any personal question, the AI checks the brain first
  4. Update on correction — If you correct a fact, the AI updates the brain immediately
  5. Stay invisible — The AI never exposes node IDs, tool names, or database internals

Architecture

AI Models (Cloudflare Workers AI)

All AI processing runs on Cloudflare's free Workers AI tier:

Model Purpose
@cf/baai/bge-m3 Embeddings (1024-dim vectors) — multilingual, used for all semantic operations
@cf/openai/gpt-oss-20b Dedup decisions — quick LLM to confirm/deny merges in the 0.5–0.85 similarity range
@cf/qwen/qwq-32b Synthesis — extracts facts and connections from linked nodes for consolidation

Deduplication (3 tiers)

When you create a node, tag, or type, the system prevents duplicates:

  1. Exact match — If an identical name/content already exists, merge directly
  2. Auto-merge (>0.85 cosine similarity) — High confidence duplicate, merge without asking
  3. LLM confirmation (0.5–0.85) — Ambiguous range, an LLM decides if it's a match
  4. Below 0.5 — Definitely new, create it

Auto-linking

New nodes are compared against all existing nodes. Any pair with cosine similarity between 0.5 and 0.92 gets linked automatically. The link score equals the similarity. Links below 0.92 aren't created (too similar — likely the same thing, handled by dedup). Links are bidirectional.

Daily maintenance

A cron job runs daily at 3 AM UTC and prunes links with scores below the prune_threshold setting (default: 0.2). This removes weak connections that accumulate over time.

Settings

Configure via the set_setting tool:

Setting Description Default
timezone IANA timezone for date queries (e.g. "Europe/Paris") None (required for since filter)

Internal settings (managed automatically):

Setting Description Default
decay_factor Multiplier applied to link scores during consolidation 0.7
prune_threshold Links below this score are pruned by the daily cron 0.2

Project Structure

src/
├── index.ts        # Entry point: OAuth provider, MCP handler, cron
├── mcp.ts          # All 20 MCP tool registrations
├── nodes.ts        # Node CRUD, search, auto-linking, consolidation
├── types.ts        # Node type management
├── dedup.ts        # 3-tier deduplication (types, nodes, tags)
├── ai.ts           # Workers AI calls (embeddings, LLM, synthesis)
├── schema.ts       # Drizzle ORM schema (7 tables)
├── database.ts     # Supabase postgres.js connection
├── settings.ts     # KV-cached settings layer
├── validation.ts   # Metadata schema validation
├── skills.ts       # Skills CRUD
└── env.ts          # Environment interface, thresholds

system-prompt-base.md        # Full system prompt
system-prompt-claude-code.md # Dev session variant
system-prompt-tiny.md        # Minimal for local models
wrangler.jsonc               # Cloudflare Workers config

Tips for Best Results

Getting started

After deploying, the brain is empty. Start by creating the node types you need:

"Create a 'thought' type for ideas and insights, an 'action' type for tasks, a 'person' type for people I mention, and a 'bookmark' type for links."

The AI will create these with sensible schemas. You can customize later.

Natural usage

You don't need to explicitly tell your AI to "save to brain" — the system prompt handles that. Just talk naturally:

  • "I decided to use Postgres instead of SQLite because of the vector support" → saved as a thought
  • "Remind me to update the docs next week" → saved as an action
  • "I met Sarah at the conference, she works on distributed systems at Stripe" → saved as a person
  • "Check out this article: https://example.com/good-read" → saved as a bookmark

Tags and projects

Tags emerge organically. The AI reuses existing tags when possible. To track a project:

"Mark 'mcp-brain' as a project tag."

Then ask "what are my projects?" anytime.

Rediscovery

The brain gets more valuable over time. Try:

  • "What am I forgetting?" — surfaces neglected nodes
  • "What have I been thinking about this week?" — recent thoughts
  • "How does X connect to Y?" — graph exploration
  • "Build a profile of Sarah" — consolidates everything linked to a person node

Cost

On free tiers:

  • Cloudflare Workers: 100,000 requests/day free
  • Cloudflare Workers AI: Free tier includes generous inference limits for BGE-M3, GPT-OSS-20B, and QWQ-32B
  • Supabase: 500MB database, 1GB file storage free

For personal use, you're unlikely to hit any limits.

License

MIT

Recommended Servers

playwright-mcp

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.

Official
Featured
TypeScript
Magic Component Platform (MCP)

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.

Official
Featured
Local
TypeScript
Audiense Insights MCP Server

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.

Official
Featured
Local
TypeScript
VeyraX MCP

VeyraX MCP

Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.

Official
Featured
Local
graphlit-mcp-server

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.

Official
Featured
TypeScript
Kagi MCP Server

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.

Official
Featured
Python
E2B

E2B

Using MCP to run code via e2b.

Official
Featured
Neon Database

Neon Database

MCP server for interacting with Neon Management API and databases

Official
Featured
Exa Search

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.

Official
Featured
Qdrant Server

Qdrant Server

This repository is an example of how to create a MCP server for Qdrant, a vector search engine.

Official
Featured