Add personal API keys, superbrain-mcp, and fix Markdown prose styling
API keys & MCP (the mcpserver-link prerequisite from STRATEGY.md): - ApiKey table (migration 017 + schema.sql): hash-only storage of personal "sb_..." Bearer credentials, unique keyHash, owner cascade. - internal/auth/apikeys.go + AuthMiddleware fork: keys resolve before the assertion/cookie channels; gated on the mcp-core connector at issuance AND at every use (downgrade 403s); independent of tokenVersion so "sign out everywhere" never breaks a gateway link; view-as stays browser-only. - /api/keys GET/POST/DELETE: plaintext shown exactly once, 10-key cap under the user lock, owner-scoped revocation; Settings -> API Keys tab. - mcp/: superbrain-mcp, a pip-installable stdio MCP server (listmonk-mcp pattern) with bookmarks/tags/pages tools, version-safe updates; the federated gateway spawns it via config_mcpserver_superbrain() in deploy/federated/lib-superbrain.sh (mints the gateway key in-db, points it at http://superbrain-app:8080). STRATEGY.md records the remaining suite-side registry work. - Tests: TestAPIKeys (plan gate, cap, revocation, tokenVersion semantics, downgrade-at-use); full DB-backed suite, db-converge, live MCP-client smoke all pass. Markdown (Gitea issue #3): add @tailwindcss/typography and enable it in tailwind.config.ts. The prose wrapper was a no-op without it, so Tailwind Preflight flattened headings/blockquotes to body text while bold/italic survived - exactly the reported symptom. Verified in the built CSS. Gitea: #2 and #3 closed with reference notes; #1 stays open pending the Superpanel core-AI walkthrough.
This commit is contained in:
@@ -0,0 +1,73 @@
|
||||
# superbrain-mcp
|
||||
|
||||
MCP (Model Context Protocol) server for Superbrain — exposes bookmarks,
|
||||
tags and Markdown pages to AI tools over the Superbrain REST API. Same
|
||||
shape as the other federated-suite MCP servers (e.g. `listmonk-mcp`): a
|
||||
pip-installable stdio server configured entirely by environment variables.
|
||||
|
||||
## Run
|
||||
|
||||
```sh
|
||||
pip install ./mcp # or: pipx install ./mcp
|
||||
export SUPERBRAIN_API_URL=http://localhost:8080 # the Go API, directly
|
||||
export SUPERBRAIN_API_KEY=sb_... # Settings → API Keys
|
||||
superbrain-mcp
|
||||
```
|
||||
|
||||
`SUPERBRAIN_API_URL` must point at the **Go API**, not the web UI: the
|
||||
Next.js proxy signs browser assertions and never forwards a Bearer key.
|
||||
On a federated core the gateway uses `http://superbrain-app:8080`
|
||||
(container-name DNS on the `core` network).
|
||||
|
||||
API keys require the tenant's plan to include the `mcp-core` connector
|
||||
(core plan). Keys are issued in the web UI (Settings → API Keys) or, for
|
||||
suite automation, by `config_mcpserver_superbrain()` in
|
||||
`deploy/federated/lib-superbrain.sh`.
|
||||
|
||||
## MCP client config (e.g. Claude Desktop/Code)
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"superbrain": {
|
||||
"command": "superbrain-mcp",
|
||||
"env": {
|
||||
"SUPERBRAIN_API_URL": "https://superbrain.example.tld:8080",
|
||||
"SUPERBRAIN_API_KEY": "sb_..."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Tools
|
||||
|
||||
| Tool | Description |
|
||||
|---|---|
|
||||
| `search_bookmarks` | free-text + tag filter over bookmarks |
|
||||
| `get_bookmark` / `get_bookmark_markdown` | one bookmark (JSON / Markdown) |
|
||||
| `create_bookmark` | save a link with title/notes/due date/tags (missing tags are created) |
|
||||
| `update_bookmark` | partial update under the `version` contract; `""` clears nullable fields |
|
||||
| `delete_bookmark` | move to Trash |
|
||||
| `list_tags` / `create_tag` | tag inventory |
|
||||
| `list_pages` / `get_page` / `get_page_markdown` | page inventory and bodies |
|
||||
| `create_page` / `update_page` / `append_to_page` | write Markdown pages (version-safe read-modify-write) |
|
||||
|
||||
Concurrent-edit conflicts surface as tool errors mentioning 409 — re-read
|
||||
and retry.
|
||||
|
||||
## Federated mcpserver gateway
|
||||
|
||||
The suite gateway (`federatedcomputer/mcpserver`) spawns this package when
|
||||
its `.env` carries `SUPERBRAIN_API_URL` (the registry entry in its
|
||||
`apps_registry.py` is `"superbrain": {required_env: "SUPERBRAIN_API_URL",
|
||||
command: "superbrain-mcp", args: []}`). Linking on a core host:
|
||||
|
||||
```sh
|
||||
/federated/bin/installapp-mcpserver superbrain
|
||||
```
|
||||
|
||||
which runs `config_mcpserver_superbrain()` (mints a dedicated `mcpserver`
|
||||
key for the admin account, directly in the database — the house pattern
|
||||
for apps whose credential creation is not a public API) and restarts the
|
||||
gateway so `mcphub` and Hermes pick the tools up.
|
||||
@@ -0,0 +1,24 @@
|
||||
[build-system]
|
||||
requires = ["setuptools>=68"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "superbrain-mcp"
|
||||
# Versioned in lockstep with the Superbrain release it speaks to (house
|
||||
# tooling tracks one version per app); the federated mcpserver gateway
|
||||
# installs this package and spawns `superbrain-mcp` per linked instance.
|
||||
version = "1.2.0"
|
||||
description = "MCP server for Superbrain — bookmarks, tags and pages over the Superbrain REST API"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
license = { text = "MIT" }
|
||||
dependencies = [
|
||||
"mcp>=1.2",
|
||||
"httpx>=0.27",
|
||||
]
|
||||
|
||||
[project.scripts]
|
||||
superbrain-mcp = "superbrain_mcp.server:main"
|
||||
|
||||
[tool.setuptools.packages.find]
|
||||
include = ["superbrain_mcp*"]
|
||||
@@ -0,0 +1,3 @@
|
||||
"""Superbrain MCP server — bookmarks, tags and pages for AI tooling."""
|
||||
|
||||
__version__ = "1.2.0"
|
||||
@@ -0,0 +1,294 @@
|
||||
"""Superbrain MCP server.
|
||||
|
||||
Exposes a Superbrain workspace (bookmarks, tags, Markdown pages) to MCP
|
||||
clients over the plain REST API, authenticated with a personal API key
|
||||
(Settings -> API Keys in the web UI, minted as ``sb_...``).
|
||||
|
||||
Configuration (environment):
|
||||
SUPERBRAIN_API_URL base URL of the Go API, e.g.
|
||||
``http://superbrain-app:8080`` on a federated core
|
||||
network or ``http://localhost:8080`` in dev. Must
|
||||
point at the Go API directly — the Next.js web
|
||||
proxy signs browser assertions and never forwards
|
||||
a Bearer API key.
|
||||
SUPERBRAIN_API_KEY the personal API key (``sb_...``).
|
||||
|
||||
Transport is stdio, matching how the federated ``mcpserver`` gateway
|
||||
spawns per-app MCP servers (see its apps_registry.py).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
from typing import Any, Optional
|
||||
|
||||
import httpx
|
||||
from mcp.server.fastmcp import FastMCP
|
||||
|
||||
API_URL = os.environ.get("SUPERBRAIN_API_URL", "").rstrip("/")
|
||||
API_KEY = os.environ.get("SUPERBRAIN_API_KEY", "")
|
||||
|
||||
mcp = FastMCP("superbrain")
|
||||
|
||||
_TIMEOUT = httpx.Timeout(30.0)
|
||||
|
||||
|
||||
def _request(method: str, path: str, **kwargs: Any) -> Any:
|
||||
"""Call the Superbrain API and return parsed JSON (or raw text)."""
|
||||
if not API_URL or not API_KEY:
|
||||
raise RuntimeError(
|
||||
"SUPERBRAIN_API_URL and SUPERBRAIN_API_KEY must be set"
|
||||
)
|
||||
resp = httpx.request(
|
||||
method,
|
||||
API_URL + path,
|
||||
headers={"Authorization": f"Bearer {API_KEY}"},
|
||||
timeout=_TIMEOUT,
|
||||
**kwargs,
|
||||
)
|
||||
if resp.status_code >= 400:
|
||||
try:
|
||||
detail = resp.json().get("error", resp.text)
|
||||
except Exception:
|
||||
detail = resp.text
|
||||
hint = ""
|
||||
if resp.status_code == 403:
|
||||
hint = " (the key's plan may not include API/MCP access)"
|
||||
if resp.status_code == 409:
|
||||
hint = " (concurrent modification — re-read and retry)"
|
||||
raise RuntimeError(
|
||||
f"Superbrain API {method} {path} -> {resp.status_code}: {detail}{hint}"
|
||||
)
|
||||
ctype = resp.headers.get("content-type", "")
|
||||
if "json" in ctype:
|
||||
return resp.json()
|
||||
return resp.text
|
||||
|
||||
|
||||
def _resolve_tag_ids(names: list[str]) -> list[str]:
|
||||
"""Map tag names to ids, creating missing tags (tag sharing is
|
||||
group-wide in Superbrain, so names are the natural handle)."""
|
||||
existing = {
|
||||
(t.get("name") or "").lower(): t["id"] for t in _request("GET", "/api/tags")
|
||||
}
|
||||
ids: list[str] = []
|
||||
for name in names:
|
||||
key = name.strip().lower()
|
||||
if not key:
|
||||
continue
|
||||
if key in existing:
|
||||
ids.append(existing[key])
|
||||
else:
|
||||
created = _request("POST", "/api/tags", json={"name": name.strip()})
|
||||
ids.append(created["id"])
|
||||
existing[key] = created["id"]
|
||||
return ids
|
||||
|
||||
|
||||
# --- Bookmarks -------------------------------------------------------------
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
def search_bookmarks(search: str = "", tag: str = "", limit: int = 25) -> Any:
|
||||
"""Search Superbrain bookmarks (saved links with notes, tags, due dates).
|
||||
|
||||
Args:
|
||||
search: free-text query over URL/title/description/notes (empty = all).
|
||||
tag: only bookmarks carrying this exact tag name.
|
||||
limit: max results, 1-200.
|
||||
"""
|
||||
params: dict[str, Any] = {"limit": max(1, min(int(limit), 200))}
|
||||
if search:
|
||||
params["search"] = search
|
||||
if tag:
|
||||
tags = _request("GET", "/api/tags")
|
||||
match = next((t["id"] for t in tags if (t.get("name") or "") == tag), None)
|
||||
if match is None:
|
||||
return []
|
||||
params["tagId"] = match
|
||||
return _request("GET", "/api/bookmarks", params=params)
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
def get_bookmark(bookmark_id: str) -> Any:
|
||||
"""Fetch one bookmark by id (full owner projection: notes, tags, dates)."""
|
||||
return _request("GET", f"/api/bookmarks/{bookmark_id}")
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
def get_bookmark_markdown(bookmark_id: str) -> Any:
|
||||
"""Fetch one bookmark rendered as a Markdown document."""
|
||||
return _request("GET", f"/api/bookmarks/{bookmark_id}/markdown")
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
def create_bookmark(
|
||||
url: str,
|
||||
title: str = "",
|
||||
description: str = "",
|
||||
notes: str = "",
|
||||
due_date: str = "",
|
||||
tags: Optional[list[str]] = None,
|
||||
) -> Any:
|
||||
"""Save a new bookmark (link) to Superbrain.
|
||||
|
||||
Args:
|
||||
url: the link to save (http/https, required).
|
||||
title: optional title (defaults to the fetched page title in the UI).
|
||||
description: optional short description.
|
||||
notes: optional Markdown notes.
|
||||
due_date: optional due date, YYYY-MM-DD (or RFC3339).
|
||||
tags: optional tag names; missing tags are created.
|
||||
"""
|
||||
body: dict[str, Any] = {"url": url}
|
||||
if title:
|
||||
body["title"] = title
|
||||
if description:
|
||||
body["description"] = description
|
||||
if notes:
|
||||
body["notes"] = notes
|
||||
if due_date:
|
||||
body["dueDate"] = due_date
|
||||
if tags:
|
||||
body["tagIds"] = _resolve_tag_ids(tags)
|
||||
return _request("POST", "/api/bookmarks", json=body)
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
def update_bookmark(
|
||||
bookmark_id: str,
|
||||
title: Optional[str] = None,
|
||||
description: Optional[str] = None,
|
||||
notes: Optional[str] = None,
|
||||
due_date: Optional[str] = None,
|
||||
tags: Optional[list[str]] = None,
|
||||
) -> Any:
|
||||
"""Update fields of an existing bookmark; omitted fields stay unchanged.
|
||||
|
||||
Pass an empty string to CLEAR a nullable field (description, notes,
|
||||
due_date). Pass tags=[] to detach all tags. The current version is read
|
||||
automatically (Superbrain's optimistic-concurrency contract); a 409
|
||||
means someone edited it concurrently — retry.
|
||||
"""
|
||||
current = _request("GET", f"/api/bookmarks/{bookmark_id}")
|
||||
body: dict[str, Any] = {"version": current.get("version", 1)}
|
||||
if title is not None:
|
||||
body["title"] = title or None
|
||||
if description is not None:
|
||||
body["description"] = description or None
|
||||
if notes is not None:
|
||||
body["notes"] = notes or None
|
||||
if due_date is not None:
|
||||
body["dueDate"] = due_date or None
|
||||
if tags is not None:
|
||||
body["tagIds"] = _resolve_tag_ids(tags)
|
||||
return _request("PUT", f"/api/bookmarks/{bookmark_id}", json=body)
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
def delete_bookmark(bookmark_id: str) -> Any:
|
||||
"""Delete a bookmark (moves it to the owner's Trash in the UI)."""
|
||||
return _request("DELETE", f"/api/bookmarks/{bookmark_id}")
|
||||
|
||||
|
||||
# --- Tags ------------------------------------------------------------------
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
def list_tags() -> Any:
|
||||
"""List the workspace's tags with bookmark counts."""
|
||||
return _request("GET", "/api/tags")
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
def create_tag(name: str, color: str = "") -> Any:
|
||||
"""Create a tag. Color is optional #RRGGBB."""
|
||||
body: dict[str, Any] = {"name": name}
|
||||
if color:
|
||||
body["color"] = color
|
||||
return _request("POST", "/api/tags", json=body)
|
||||
|
||||
|
||||
# --- Pages -----------------------------------------------------------------
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
def list_pages(search: str = "") -> Any:
|
||||
"""List Markdown pages (pinned first), optionally filtered by a
|
||||
title/content substring."""
|
||||
params = {"search": search} if search else {}
|
||||
return _request("GET", "/api/pages", params=params)
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
def get_page(page_id: str) -> Any:
|
||||
"""Fetch one page: content plus its linked bookmarks, backlinks and
|
||||
resolved outgoing links."""
|
||||
return _request("GET", f"/api/pages/{page_id}")
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
def get_page_markdown(page_id: str) -> Any:
|
||||
"""Fetch one page's body as raw Markdown."""
|
||||
return _request("GET", f"/api/pages/{page_id}/markdown")
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
def create_page(title: str, content: str = "", parent_id: str = "") -> Any:
|
||||
"""Create a Markdown page. parent_id must be an existing owned page."""
|
||||
body: dict[str, Any] = {"title": title}
|
||||
if content:
|
||||
body["content"] = content
|
||||
if parent_id:
|
||||
body["parentId"] = parent_id
|
||||
return _request("POST", "/api/pages", json=body)
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
def update_page(
|
||||
page_id: str, title: Optional[str] = None, content: Optional[str] = None
|
||||
) -> Any:
|
||||
"""Update a page's title and/or FULL content (replacement, not a patch).
|
||||
|
||||
The current version is read automatically; a 409 means the page changed
|
||||
concurrently — re-read and retry. Use append_to_page to add text.
|
||||
"""
|
||||
body: dict[str, Any] = {}
|
||||
if title is not None:
|
||||
body["title"] = title
|
||||
if content is not None:
|
||||
current = _request("GET", f"/api/pages/{page_id}")
|
||||
body["content"] = content
|
||||
body["version"] = current.get("version", 1)
|
||||
if not body:
|
||||
raise RuntimeError("nothing to update: pass title and/or content")
|
||||
return _request("PATCH", f"/api/pages/{page_id}", json=body)
|
||||
|
||||
|
||||
@mcp.tool()
|
||||
def append_to_page(page_id: str, text: str) -> Any:
|
||||
"""Append Markdown text to the end of a page's content (read-modify-write
|
||||
under the page's version contract)."""
|
||||
current = _request("GET", f"/api/pages/{page_id}")
|
||||
existing = current.get("content") or ""
|
||||
merged = f"{existing}\n\n{text}" if existing else text
|
||||
return _request(
|
||||
"PATCH",
|
||||
f"/api/pages/{page_id}",
|
||||
json={"content": merged, "version": current.get("version", 1)},
|
||||
)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
if not API_URL or not API_KEY:
|
||||
print(
|
||||
"superbrain-mcp: SUPERBRAIN_API_URL and SUPERBRAIN_API_KEY must be set",
|
||||
file=sys.stderr,
|
||||
)
|
||||
raise SystemExit(2)
|
||||
mcp.run() # stdio transport
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user