Self-hosted MCP server + dashboard giving Claude Code, Cursor & Hermes agents shared long-term memory over a git-backed markdown vault. Agent-native, Obsidian-compatible second brain — markdown RAG, no vector DB.
TypeScript agent-memoryai-agentsanthropicclaude-codecursorgitknowledge-baseknowledge-graphllmmarkdownmcpmcp-servermodel-context-protocolnote-takingobsidianpkmragsecond-brainself-hostedzettelkasten
feat: per-teammate MCP tokens (create/list/revoke) managed in the Connect page
Ronalds Palacisbd3dc288dee7
diff --git a/.env.example b/.env.exampleindex b815134..b9d24ec 100644--- a/.env.example+++ b/.env.example@@ -21,13 +21,17 @@ GIT_AUTHOR_EMAIL="[email protected]"# Dashboard: Google sign-in restricted to an email allowlist.# Leave AUTH_SECRET empty (or AUTH_DISABLED=true) to keep the dashboard OPEN (local dev).ALLOWED_EMAILS="" # comma-separated emails allowed to sign in-AUTH_SECRET="" # openssl rand -base64 32 (empty => auth off)+AUTH_SECRET="" # openssl rand -base64 32, or Railway "Generate" (empty => dashboard auth off)APP_URL="http://localhost:3000" # public base URL (Google OAuth redirect_uri = APP_URL/api/auth/callback)GOOGLE_CLIENT_ID=""GOOGLE_CLIENT_SECRET=""-# MCP: bearer token agents (Hermes, Claude) must send.+# MCP auth. Optionally set ONE shared token here, and/or create per-teammate tokens+# in the dashboard Connect page. The MCP is OPEN when no token exists (local dev).MCP_TOKEN=""+# Where per-teammate token hashes persist (kept out of the vault git). Defaults to+# <vault>/.cortex. On Railway put it on the volume, e.g. /data/.cortex.+# CORTEX_STATE_DIR="/data/.cortex"# Local/OSS single-user mode: no Google auth, MCP open. NEVER true in production.AUTH_DISABLED="false"diff --git a/.gitignore b/.gitignoreindex 7ee868a..98ee58c 100644--- a/.gitignore+++ b/.gitignore@@ -11,3 +11,7 @@ next-env.d.ts.DS_Store.vercel.gstack/+# local app state (token hashes) — never commit+.cortex/+**/.cortex/+sample-vault/.gitignorediff --git a/app/(app)/connect/page.tsx b/app/(app)/connect/page.tsxindex 9e168cb..3d68159 100644--- a/app/(app)/connect/page.tsx+++ b/app/(app)/connect/page.tsx@@ -1,8 +1,8 @@"use client";import { useEffect, useState } from "react";-import useSWR from "swr";-import { Check, Copy } from "lucide-react";+import useSWR, { useSWRConfig } from "swr";+import { Check, Copy, Trash2 } from "lucide-react";import { fetcher } from "@/lib/client";function Copyable({ text }: { text: string }) {@@ -27,31 +27,62 @@ function Copyable({ text }: { text: string }) {);}+interface TokenMeta {+ id: string;+ name: string;+ created: string;+}+export default function ConnectPage() {const [origin, setOrigin] = useState("");useEffect(() => setOrigin(window.location.origin), []);const { data: feat } = useSWR<{ mcpAuthRequired?: boolean; harness?: boolean }>("/api/features", fetcher);+ const { data: tokData } = useSWR<{ tokens: TokenMeta[] }>("/api/tokens", fetcher);+ const { mutate } = useSWRConfig();- const [tok, setTok] = useState("");- function generateToken() {- const a = new Uint8Array(32);- crypto.getRandomValues(a);- setTok(Array.from(a, (b) => b.toString(16).padStart(2, "0")).join(""));- }+ const [newName, setNewName] = useState("");+ const [creating, setCreating] = useState(false);+ const [justCreated, setJustCreated] = useState<{ name: string; token: string } | null>(null);const mcp = origin ? `${origin}/api/mcp` : "…";const needsToken = feat?.mcpAuthRequired !== false;- const tokenLine = needsToken ? ` \\\n --header "Authorization: Bearer <MCP_TOKEN>"` : "";+ const tokenForCmd = justCreated?.token ?? "<MCP_TOKEN>";+ const tokenLine = needsToken || justCreated ? ` \\\n --header "Authorization: Bearer ${tokenForCmd}"` : "";const claudeCmd = `claude mcp add --transport http cortex ${mcp}${tokenLine}`;- const hermes = `mcp_servers:\n cortex:\n url: ${mcp}\n headers:\n Authorization: "Bearer <MCP_TOKEN>"`;+ const hermes = `mcp_servers:\n cortex:\n url: ${mcp}\n headers:\n Authorization: "Bearer ${tokenForCmd}"`;++ async function create() {+ if (creating) return;+ setCreating(true);+ try {+ const res = await fetch("/api/tokens", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ name: newName.trim() || "teammate" }),+ });+ const d = await res.json();+ if (d.token) setJustCreated({ name: d.name, token: d.token });+ setNewName("");+ mutate("/api/tokens");+ mutate("/api/features");+ } finally {+ setCreating(false);+ }+ }++ async function revoke(id: string) {+ await fetch(`/api/tokens/${id}`, { method: "DELETE" });+ mutate("/api/tokens");+ mutate("/api/features");+ }return (<div className="scrollbar-none h-full overflow-y-auto"><div className="mx-auto max-w-3xl px-8 py-10"><h1 className="text-2xl font-semibold tracking-tight">Connect an agent</h1><p className="mt-2 max-w-xl text-sm text-muted-foreground">- Point any MCP client at this brain. Agents read + write over the tools below — nothing- keeps a local copy of the vault. MCP connection is configured on the agent, not here.+ Point any MCP client at this brain. Agents read + write over the tools — nothing keeps a+ local copy of the vault. MCP connection is configured on the agent, not here.</p><section className="mt-8 space-y-2">@@ -59,26 +90,69 @@ export default function ConnectPage() {<Copyable text={mcp} /></section>- <section className="mt-6 space-y-2">- <h2 className="text-sm font-medium">Generate a token</h2>+ <section className="mt-8 space-y-3">+ <h2 className="text-sm font-medium">Team access tokens</h2><p className="text-sm text-muted-foreground">- A strong random value for <code className="rounded bg-muted px-1">MCP_TOKEN</code> or{" "}- <code className="rounded bg-muted px-1">AUTH_SECRET</code>. Set it as an env var on your host — the app- reads secrets from the environment, nothing is stored in the app.+ Give each teammate or agent its own MCP key. Shown once at creation — copy it then. Revoke+ anytime. (Dashboard login is separate, set via env on deploy.)</p>- <button- onClick={generateToken}- className="rounded-md border border-border px-3 py-1.5 text-xs text-foreground transition-colors hover:bg-accent"- >- Generate- </button>- {tok && <Copyable text={tok} />}+ <div className="flex gap-2">+ <input+ value={newName}+ onChange={(e) => setNewName(e.target.value)}+ onKeyDown={(e) => e.key === "Enter" && create()}+ placeholder="name (e.g. Timur)"+ className="w-56 rounded-md border border-border bg-background px-2 py-1.5 text-xs outline-none placeholder:text-muted-foreground"+ />+ <button+ onClick={create}+ disabled={creating}+ className="rounded-md bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground disabled:opacity-50"+ >+ {creating ? "Creating…" : "Create token"}+ </button>+ </div>++ {justCreated && (+ <div className="space-y-1 rounded-lg border border-border p-3">+ <p className="text-xs text-muted-foreground">+ New token for <span className="text-foreground">{justCreated.name}</span> — copy it now, it won't be shown again:+ </p>+ <Copyable text={justCreated.token} />+ </div>+ )}++ {tokData?.tokens && tokData.tokens.length > 0 ? (+ <ul className="divide-y divide-border rounded-lg border border-border">+ {tokData.tokens.map((t) => (+ <li key={t.id} className="flex items-center justify-between px-3 py-2 text-sm">+ <span>+ {t.name}+ <span className="ml-2 text-xs text-muted-foreground">+ {new Date(t.created).toLocaleDateString()}+ </span>+ </span>+ <button+ onClick={() => revoke(t.id)}+ title="Revoke"+ className="inline-flex size-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:text-destructive"+ >+ <Trash2 size={14} />+ </button>+ </li>+ ))}+ </ul>+ ) : (+ <p className="text-xs text-muted-foreground">+ No tokens yet — the MCP is {needsToken ? "gated by env MCP_TOKEN" : "open (local)"}.+ </p>+ )}</section>- <section className="mt-6 space-y-2">+ <section className="mt-8 space-y-2"><h2 className="text-sm font-medium">Claude Code</h2><Copyable text={claudeCmd} />- <p className="text-xs text-muted-foreground">Run in a terminal. Then the brain_* tools are available in your Claude Code sessions.</p>+ <p className="text-xs text-muted-foreground">Run in a terminal; then the brain_* tools are available in your Claude Code sessions.</p></section><section className="mt-6 space-y-2">@@ -90,18 +164,12 @@ export default function ConnectPage() {<h2 className="text-sm font-medium">Cursor / other MCP clients</h2><p className="text-sm text-muted-foreground">Add an HTTP MCP server with URL <code className="rounded bg-muted px-1">{mcp}</code>- {needsToken && (- <> and header <code className="rounded bg-muted px-1">Authorization: Bearer <MCP_TOKEN></code></>+ {(needsToken || justCreated) && (+ <> and header <code className="rounded bg-muted px-1">Authorization: Bearer <token></code></>)}.</p></section>-- <p className="mt-8 text-xs text-muted-foreground">- {needsToken- ? "The MCP requires the MCP_TOKEN bearer set on the server."- : "Auth is off locally — no token needed. Set MCP_TOKEN before exposing this publicly."}- </p></div></div>);diff --git a/app/api/features/route.ts b/app/api/features/route.tsindex 02bda08..6562853 100644--- a/app/api/features/route.ts+++ b/app/api/features/route.ts@@ -1,11 +1,12 @@import { AUTH_DISABLED, AUTH_SECRET, HARNESS_ENABLED, MCP_TOKEN } from "@/lib/config";+import { hasAnyToken } from "@/lib/tokens";export const dynamic = "force-dynamic";export function GET() {return Response.json({harness: HARNESS_ENABLED,- mcpAuthRequired: MCP_TOKEN !== "",+ mcpAuthRequired: MCP_TOKEN !== "" || hasAnyToken(),dashboardAuthRequired: !AUTH_DISABLED && AUTH_SECRET !== "",});}diff --git a/app/api/mcp/route.ts b/app/api/mcp/route.tsindex f530316..3c86a49 100644--- a/app/api/mcp/route.ts+++ b/app/api/mcp/route.ts@@ -1,4 +1,5 @@import { HARNESS_ENABLED, MCP_TOKEN } from "@/lib/config";+import { hasAnyToken, verifyToken } from "@/lib/tokens";import { TOOLS, TOOL_MAP } from "@/lib/mcp/tools";export const dynamic = "force-dynamic";@@ -59,10 +60,12 @@ function jsonResponse(body: Json, status = 200) {}export async function POST(req: Request) {- // Enforce the bearer only when a token is configured (open locally when unset).+ // Enforce the bearer only when auth is configured (env MCP_TOKEN or any team token).+ // Open locally when nothing is set.const token = (req.headers.get("authorization") || "").replace(/^Bearer\s+/i, "").trim();- if (MCP_TOKEN && token !== MCP_TOKEN) {- return jsonResponse(rpc(null, undefined, { code: -32001, message: "unauthorized" }), 401);+ if (MCP_TOKEN !== "" || hasAnyToken()) {+ const ok = (MCP_TOKEN !== "" && token === MCP_TOKEN) || verifyToken(token);+ if (!ok) return jsonResponse(rpc(null, undefined, { code: -32001, message: "unauthorized" }), 401);}let body: Json;diff --git a/app/api/tokens/[id]/route.ts b/app/api/tokens/[id]/route.tsnew file mode 100644index 0000000..61078c0--- /dev/null+++ b/app/api/tokens/[id]/route.ts@@ -0,0 +1,9 @@+import { revokeToken } from "@/lib/tokens";++export const dynamic = "force-dynamic";++export async function DELETE(_req: Request, { params }: { params: Promise<{ id: string }> }) {+ const { id } = await params;+ revokeToken(id);+ return Response.json({ ok: true });+}diff --git a/app/api/tokens/route.ts b/app/api/tokens/route.tsnew file mode 100644index 0000000..4b7fc2a--- /dev/null+++ b/app/api/tokens/route.ts@@ -0,0 +1,13 @@+import { createToken, listTokens } from "@/lib/tokens";++export const dynamic = "force-dynamic";++export function GET() {+ return Response.json({ tokens: listTokens() });+}++export async function POST(req: Request) {+ const { name } = await req.json().catch(() => ({}));+ // Returns the plaintext token ONCE — only its hash is stored.+ return Response.json(createToken(typeof name === "string" ? name : "token"));+}diff --git a/lib/tokens.ts b/lib/tokens.tsnew file mode 100644index 0000000..6a9b31f--- /dev/null+++ b/lib/tokens.ts@@ -0,0 +1,89 @@+import crypto from "node:crypto";+import fs from "node:fs";+import path from "node:path";+import { VAULT_DIR } from "@/lib/config";++// App state (token hashes) lives beside the vault but is kept OUT of the vault's+// git history — so per-teammate keys never land in the knowledge repo.+const STATE_DIR = process.env.CORTEX_STATE_DIR || path.join(VAULT_DIR, ".cortex");+const TOKENS_FILE = path.join(STATE_DIR, "tokens.json");++interface StoredToken {+ id: string;+ name: string;+ hash: string;+ created: string;+}++export interface TokenMeta {+ id: string;+ name: string;+ created: string;+}++const hash = (t: string) => crypto.createHash("sha256").update(t).digest("hex");++function ensureStateDir() {+ fs.mkdirSync(STATE_DIR, { recursive: true });+ // Make sure git-sync never commits the state dir into the vault repo.+ try {+ const gi = path.join(VAULT_DIR, ".gitignore");+ let content = "";+ try {+ content = fs.readFileSync(gi, "utf8");+ } catch {+ /* none yet */+ }+ if (!content.split(/\r?\n/).some((l) => l.trim() === ".cortex/")) {+ fs.writeFileSync(gi, `${content && !content.endsWith("\n") ? `${content}\n` : content}.cortex/\n`);+ }+ } catch {+ /* best effort */+ }+}++function load(): StoredToken[] {+ try {+ return JSON.parse(fs.readFileSync(TOKENS_FILE, "utf8"));+ } catch {+ return [];+ }+}++function save(tokens: StoredToken[]) {+ ensureStateDir();+ fs.writeFileSync(TOKENS_FILE, JSON.stringify(tokens, null, 2));+}++export function listTokens(): TokenMeta[] {+ return load().map(({ id, name, created }) => ({ id, name, created }));+}++/** Create a token. Returns the plaintext value ONCE — only the hash is stored. */+export function createToken(name: string): { id: string; name: string; token: string } {+ const token = crypto.randomBytes(32).toString("hex");+ const rec: StoredToken = {+ id: crypto.randomUUID(),+ name: name?.trim() || "token",+ hash: hash(token),+ created: new Date().toISOString(),+ };+ const all = load();+ all.push(rec);+ save(all);+ return { id: rec.id, name: rec.name, token };+}++export function revokeToken(id: string): void {+ save(load().filter((t) => t.id !== id));+}++export function verifyToken(bearer: string): boolean {+ if (!bearer) return false;+ const h = hash(bearer);+ return load().some((t) => t.hash === h);+}++export function hasAnyToken(): boolean {+ return load().length > 0;+}