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
访问服务器

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

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选