AI Integration

SourceBrain is built to feed your codebase knowledge to AI agents. There are three ways to do it, from a one-line copy-paste to a live two-way connection: the context export, the built-in MCP server, and the HTTP API.

MethodBest forDirection
Context export (sourcebrain context)Pasting a bundle into any chat windowRead-only
MCP server (sourcebrain mcp)Claude Desktop, Cursor, and other agentic toolsRead & write
HTTP APICustom scripts and integrationsRead & write

1. Context export

The simplest integration. sourcebrain context searches your lessons and bundles the matches into a single Markdown document you can paste straight into any AI chat.

sourcebrain context "authentication"        # matching lessons
sourcebrain context                          # everything
sourcebrain context "auth" -o context.md     # write to a file

No account or configuration required; it works in local mode too. This is the right choice when you just want to give a model a snapshot of the relevant knowledge.


2. MCP server

The Model Context Protocol (MCP) is an open standard that lets AI tools call external tools. sourcebrain mcp starts an MCP server over stdio, giving an agent live, two-way access to your knowledge base: it can search and read lessons before answering, and write new lessons when it learns something worth keeping.

đź’ˇ
Because the MCP server can write lessons, your knowledge base grows on its own: an agent that discovers an architecture decision or a gotcha during a session can save it with add_lesson so the next session (yours or a teammate's) already knows it.

Setup

  1. 1

    Pick your backend

    The MCP server uses the same auto-detection as every other command. For a cloud workspace, log in and select it first:

    sourcebrain login
    sourcebrain workspace use my-team

    For a local-only knowledge base, just make sure you launch your AI tool from a directory that contains a .sourcebrain/ folder.

  2. 2

    Add SourceBrain to your AI tool

    In Claude Desktop, edit claude_desktop_config.json (Cursor and other MCP-capable editors use an equivalent settings file):

    claude_desktop_config.json
    {
      "mcpServers": {
        "sourcebrain": {
          "command": "sourcebrain",
          "args": ["mcp"]
        }
      }
    }

    Make sure the sourcebrain binary is on your PATH, or use an absolute path for command.

  3. 3

    Restart your AI tool

    Restart the app so it picks up the new server. SourceBrain's tools will appear in the tool list, and the agent can start using them.

Available tools

The server exposes a full set of tools, grouped below. A well-behaved agent calls get_workspace_info first to orient itself, then searches, reads, and navigates as needed.

ToolArgumentsWhat it does
get_workspace_infononeReturns an orientation document: the team’s AI instructions, the full lesson index, and an API reference. Call this first.
list_lessonskind?, status?Lists every lesson path. kind="plan" lists status-tracked plans (filter with status), kind="schema" lists data-model references.
search_lessonsquery, limit?Searches by relevance and returns the full text of the top matches (default 5), ranked, with further matches listed by path. Includes semantic (by-meaning) matches when an embed key is configured.
get_lessonpath, format?Returns the full content of one lesson, prefixed with a staleness warning if its referenced code has changed since the lesson was written. format="schema" returns a schema node’s data model as structured JSON instead.
get_lesson_historypath, diff_from?, diff_to?Lists every saved version of a lesson, newest first, with timestamps and notes. Pass diff_from/diff_to for a unified diff between two versions instead.
lessons_for_filefileGiven a source file, lists the lessons anchored to it (and the exact symbol/line); the inverse of staleness. Call before editing a file. Needs the local repo.
get_graphpath?Returns the whole [[wikilink]] graph as JSON: nodes (lessons) and directed edges. With a path, shows just that lesson’s backlinks and outgoing links (broken links flagged).
add_lessonpath, content, kind?, project?Creates a new lesson or saves a new version of an existing one. kind="plan" creates a status-tracked plan (a private draft until proposed); kind="schema" creates a data-model reference.
edit_lessonpath, old_string, new_stringMakes a targeted edit by replacing an exact string in a lesson, saved as a new version. Prefer it over add_lesson for changing part of a lesson.
trashaction, path?Manages the lesson trash: delete (a soft, recoverable delete), restore, or list.
suggest_lessonfile, lines?AI-drafts a lesson from a file (or line range) for review, not saved. Pro, cloud feature.
check_lessonschanged_files?Without arguments, reports which lessons are stale (referenced code changed or was deleted since the lesson was written). With changed_files, reports the lessons a specific change may have invalidated: those anchored to a changed file and those whose content is about what changed even if not anchored to it. Call the changed_files form right after editing code. Needs the server running inside the local repo.
set_plan_statuspath, statusAdvances a plan (draft → proposed → accepted → in_progress → done, or archived). Cloud/team feature.

add_lesson, edit_lesson, list_lessons, search_lessons, and get_lesson also accept scope: "personal" to use your private My Lessons space on request. get_workspace_info leads with your active plans, so an agent has current-work context before it starts.

đź’ˇ
Agents can tell when knowledge is stale. Keeping a knowledge base trustworthy is the whole game; a confidently-cited but outdated lesson is worse than no lesson. So staleness is surfaced to the model, not just to humans running doctor: get_lesson prepends a warning when the code a lesson references has changed since it was written, and check_lessons lets an agent audit the whole base. And after the agent changes code, it can call check_lessons with changed_files to find the lessons that edit may have invalidated, including ones not anchored to the file it touched, and update them in the same session. Stale knowledge gets surfaced at the moment of change instead of rotting silently, with the fix in the agent's hands. The default AI instructions tell the agent to verify flagged lessons against the current code and offer to update them. (Staleness needs the code on disk, so the MCP server must run inside the repository, the normal case for an editor or agent.)

Workspace AI instructions

In cloud mode you can steer how agents use a workspace. Open the workspace's AI Settings page in the web UI and write Workspace AI Instructions: naming conventions, what to check before making suggestions, which namespaces matter most. These instructions are returned at the top of get_workspace_info, so every agent that connects sees them.

If you leave the field blank, SourceBrain uses a sensible built-in default that tells the agent to search before answering and to save new knowledge as it goes. Example of your own instructions:

Always check the auth/ namespace before suggesting authentication changes.
Our API follows REST conventions documented at api/conventions.
Path format for this team: layer/feature, e.g. backend/auth, frontend/routing.
When you add a lesson, use clear headers and include code examples.
ℹ️
The AI Settings page also shows a live AI Context Preview: exactly what an agent receives from get_workspace_info, plus the MCP config snippet to copy.

The organization layer (Pro)

Workspaces grouped in an organization get two extra inputs to the AI context, both managed on the org page:

Org AI instructions apply across every workspace in the org and are included before the workspace's own instructions, which take precedence where they conflict. Shared context designates one org-visible workspace (say, platform) as the cross-repo conventions space: search, ask, the context bundle, and MCP retrieval then rank its lessons alongside the current workspace's own, slightly down-weighted so repo-specific knowledge wins ties. Shared lessons appear under their qualified path (ws:platform/errors), which get_lesson reads directly, and lessons can link across workspaces the same way, with [[ws:platform/errors]].


How agents get context: the layers

Guidance reaches the agent in two ways. Instructions are pasted into every agent's orientation document the moment it connects. Knowledge is retrieved by relevance while it works. Knowing which is which tells you where any piece of guidance belongs.

Always in context

Assembled top to bottom into the get_workspace_info document. Where layers conflict, the more specific one wins.

1

Tool contractbuilt in

Ships with the MCP server itself: search before answering, save lessons as you work, verify stale knowledge. You never need to restate this.

2

Organization AI instructionsorg admins

Rules for every repo in the org. Also the place to point agents at the shared context workspace, for example "cross-repo conventions live in ws:platform".

3

Workspace AI instructionsworkspace admins

This repo’s specifics. Included after the org layer, and they win where the two conflict.

Retrieved when relevant

Not pasted into context. Ranked by search as the agent works, and repo-specific knowledge wins ties.

4

Shared context workspaceorg admins pick it

One org-visible workspace of cross-repo conventions. Its lessons are searched alongside this workspace’s own, slightly down-weighted so repo-specific knowledge wins ties.

5

Workspace lessonseveryone in the workspace

The knowledge itself. Indexed up front so the agent can judge relevance; full text retrieved by search when it matters.

6

File anchorsreferences on a lesson

Lessons pinned to specific files or symbols, surfaced by lessons_for_file at the moment an agent is about to edit that code.

The rule of thumb: if the agent must always see it, it's an instruction; if it should be found when relevant, it's a lesson. If you find yourself writing the same sentence in several workspaces' instructions, it belongs in the org layer or the shared context workspace; if your instructions are explaining one function's behavior, that's a lesson with an anchor, not an instruction.

You want to…Put it in
Set a rule for every repo in the org ("never log PII")Org AI instructions
Share conventions between reposA lesson in the org’s shared context workspace
State this repo’s conventions ("check auth/ before touching login")Workspace AI instructions
Record knowledge worth retrieving ("why we fork the parser")A lesson
Warn about one specific file or functionA lesson with a reference to that code
đź’ˇ
Every workspace's AI Settings page shows this stack assembled for real: the AI Context Preview is the exact document agents receive, with your org and workspace layers in place.

3. HTTP API

Every workspace is reachable over a small REST API, so you can wire SourceBrain into custom scripts or your own agent. Authenticate with the token saved at ~/.sourcebrain/config.json after sourcebrain login.

Authorization: Bearer <token>
ActionMethodPath
Full context bundleGET/api/w/{workspace}/context
Search lessonsGET/api/w/{workspace}/context?q={query}
List all pathsGET/api/w/{workspace}/nodes
Read one lessonGET/api/w/{workspace}/node?path={path}
Add / update a lessonPOST/api/w/{workspace}/nodes
Version historyGET/api/w/{workspace}/history?path={path}
AI context documentGET/api/w/{workspace}/ai-context
ℹ️
The same API reference is embedded in the get_workspace_info / ai-context output, so an agent always knows how to reach the workspace it's working in.

How retrieval works

Every search, whether from the web UI, sourcebrain search, sourcebrain context, or an agent calling search_lessons, runs through the same relevance ranking, so an agent gets the lessons that actually matter instead of the whole knowledge base.

ModeHow it ranksRequirements
Keyword (default)Lexical scoring: exact path-segment matches, partial matches, term frequency, and exact-phrase boosts.None (always on, works offline in local mode)
Semantic (Pro)Blends the keyword score with embedding similarity (Reciprocal Rank Fusion), so conceptually related lessons surface even without shared keywords.A Pro workspace

On a Pro workspace, semantic search is on automatically: lessons are embedded as they're written, and existing lessons are backfilled in the background. If it's ever unavailable, search transparently falls back to keyword ranking, so nothing breaks.

đź’ˇ
Semantic search is what lets the knowledge base scale past a few dozen lessons: keyword search needs the right words, embeddings find the right meaning.

Lesson suggestion (Pro)

Writing the first draft of a lesson is the part people skip. SourceBrain can do it for you: point it at a file or a range of lines and it returns a draft { path, content } describing that code. It's a starting point; nothing is ever saved automatically. You review and edit the draft, then save it like any other lesson.

SurfaceHow to use it
CLI (sourcebrain suggest)Run sourcebrain suggest <file> --lines 40-58; review the draft, then save it with sourcebrain add.
VS CodeSelect code → right-click → “SourceBrain: Add lesson from selection”, then press Draft with AI (or Ctrl+Alt+G). The AI fills the draft in place; save to keep it.

It's server-side and Pro-gated: the selected code is sent to the server, which calls a configured AI model and returns the draft. The feature is metered: each workspace gets a monthly quota of suggestions on Pro (Enterprise is unlimited).

ℹ️
Lesson suggestion is a hosted AI feature. If the AI model is ever unavailable, it reports as such and the rest of SourceBrain is unaffected.

Codebase scan (Pro)

A new workspace starts empty, and nobody wants to hand-write dozens of lessons. The codebase scanner bootstraps it: pick a set of files and SourceBrain drafts lessons for them in bulk, capturing the durable, non-obvious knowledge in each. As always, nothing is saved until you review and accept it.

Because your source code lives only on your machine, the scan is a handshake between the CLI (which can read your files) and the web app (where you pick files and review drafts):

  1. 1

    Run the scan from your repo

    In a logged-in Pro workspace, run sourcebrain scan inside your project. The CLI sends a manifest (file paths and sizes only, never contents) and prints a link.

    sourcebrain scan
  2. 2

    Pick files in the browser

    Open the printed link. The first time, you opt in to scanning for the workspace. Choose the files to scan from a folder-grouped list; already-lessoned files are marked, and a utilization bar tracks the estimated token cost against your budget so a scan can't run away.

  3. 3

    CLI uploads, server drafts

    Once you start, the still-running CLI uploads just the selected files' contents. The server drafts 0 or more lessons per file (skipping anything trivial), pins each to the symbol or line range it describes, then runs a linking pass that weaves [[wikilinks]] between related drafts. File contents are never stored, only the drafts and the lessons you keep.

  4. 4

    Review and accept

    Back in the browser, edit, accept, or reject each draft (or accept all). Accepted drafts become real lessons, anchored to their source code so doctor and refs work immediately, and already cross-linked so they show up as a connected knowledge graph from the very first scan.

Like lesson suggestion, scanning is metered: each workspace gets a one-time onboarding token grant plus a monthly scan budget on Pro (Enterprise is unlimited), and a per-scan cap bounds any single run.

ℹ️
The scanner uses the same AI model as lesson suggestion, and only sends file contents after the one-time workspace opt-in.

Answering questions (Pro)

Sometimes you just want an answer, not a bundle to read. sourcebrain ask takes a natural-language question and returns an answer synthesized from your workspace's lessons, with citations to the lessons it used.

sourcebrain ask "how does authentication work?"
sourcebrain ask why do we cache the workspace plan
sourcebrain ask "what is the deploy process" --json

It runs the same relevance ranking as search to retrieve only the lessons most relevant to the question (not the whole knowledge base), then asks the configured AI model to answer from those lessons, so the answer stays grounded and cheap. When the workspace is in an organization with a shared context, those cross-repo lessons are considered too. --json returns a { answer, sources } object for tooling.

ℹ️
Like lesson suggestion and codebase scan, ask is a Pro, cloud feature: you must be logged in with a workspace selected, and it is metered per workspace (Enterprise is unlimited).

Recommended workflow

Connect SourceBrain as an MCP server and write a short set of Workspace AI Instructions. From then on, ask your agent questions normally, and it searches the knowledge base before answering, cites the lessons it used, and saves anything new it figures out. Over time the workspace becomes a shared memory that every agent and teammate benefits from.

For the task-shaped version of all this, see Recipes: how to import the memory files you already have, install the hooks so lessons reach the agent without being asked, and run the read-then-capture loop day to day.

SourceBrain Docs · SourceBrain