Local-first π§ memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly π΄ dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.
TypeScript
/**
* MCP tool registry. As of v0.10.8 the advertised surface is composed
* from four sibling slices:
*
* - Core read/health tools (`second_brain_status`,
* `second_brain_query`, `vault_health`) β defined inline in this
* file because they only need `ServerContext` and the shared
* coercion helpers.
* - Brain tools (`brain_feedback`, `brain_apply_evidence`,
* `brain_note`, `brain_dream`, `brain_digest`, `brain_query`,
* `brain_doctor`, `brain_backlinks`) β `./brain-tools.ts`
* (`BRAIN_TOOLS`).
* - Brain Search (`brain_search`) β `./search-tools.ts`
* (`SEARCH_TOOLS`).
* - Brain schema administration (`schema_*`) β `./schema-tools.ts`
* (`SCHEMA_TOOLS`).
* - Brain watchdog recovery probes (`brain_watchdog`) β
* `./watchdog-tools.ts` (`WATCHDOG_TOOLS`).
*
* Each slice owns its own handlers and tool definitions; this file
* only assembles them in a stable order and applies scope filtering.
*/
import { ConfigReadError, discoverConfig } from "../core/config.ts";
import { redactConfigMapping } from "../core/egress/guard.ts";
import { resolvedSecretLiterals } from "../core/secret-resolver.ts";
import type { ConfigDiscovery } from "../core/types.ts";
import { REMOVED_TOOLS } from "../core/removed-surfaces.ts";
import { computeBrainStatus } from "../core/brain/status.ts";
import { TRANSPORT_REACH } from "../core/graph/transport-reach.ts";
import { doctor } from "../core/doctor.ts";
import { nextCommandField } from "../core/brain/next-step.ts";
import { collectRuntimeNotices } from "../core/brain/runtime-notices.ts";
import { probeVaultDirectory, type UnresolvedField } from "../core/vault-presence.ts";
import { resolveVaultScope, walkVaultScope } from "../core/vault-scope/index.ts";
import { BRAIN_TOOLS } from "./brain-tools.ts";
import { cursorOffsetArg, CURSOR_SCHEMA } from "./brain/pagination.ts";
import { pageSlice } from "../core/brain/offset-cursor.ts";
import { WIRING_TOOLS } from "./wiring-tools.ts";
import { SEARCH_TOOLS, buildSearchStatusBlock } from "./search-tools.ts";
import { buildStoreStatusBlock } from "../core/store/store-status.ts";
import { storeStatusForCaller } from "./brain/device-path.ts";
import { SCHEMA_TOOLS } from "./schema-tools.ts";
import { WATCHDOG_TOOLS } from "./watchdog-tools.ts";
import { SKILL_TOOLS } from "./skill-tools.ts";
import { buildHydrateTool, TOOL_HYDRATE_NAME } from "./hydrate-tool.ts";
import { normalizeAgentArgument, PLACEHOLDER_AGENT_VALUES } from "../core/agent-identity.ts";
import { vaultRelative } from "../core/path-safety.ts";
import { isOwnerVisible, normalizeAgentScope, pageOwner } from "../core/graph/agent-scope.ts";
import { listVaultPages } from "../core/vault.ts";
import { DEGRADATION_CODE, type DegradationNotice } from "../core/integrity/degradation.ts";
import { TOOL_CEILING_KINDS } from "../core/runtime/host-facts.ts";
import { inventoryStateSurfaces } from "../core/state/surfaces.ts";
import { INVALID_PARAMS, METHOD_NOT_FOUND, MCPError } from "./protocol.ts";
import { AGENT_SCOPE_SCHEMA, coerceAgentScope, coerceStr, coerceInt } from "./coerce.ts";
import type { OutputSchema } from "./output-contract.ts";
import { MCP_PREVIEW_BUDGET } from "./preview-budget.ts";
import { CAPABILITY_DIAGNOSTIC_TOOL } from "./capabilities.ts";
import { unresolvedField, vaultPathField } from "./vault-path-field.ts";
import {
TOOL_SCOPE,
TOOL_SCOPES,
contextReach,
contextVault,
type ServerContext,
type ToolCapabilityReport,
type ToolDefinition,
type ToolScope,
} from "./tool-contract.ts";
// PLACEHOLDER_AGENT_VALUES + normalizeAgentArgument live in
// `src/core/agent-identity.ts` so the OpenClaw native plugin can import
// the same constants without reaching across to the MCP module. Re-exported
// at the bottom of this file for callers that previously imported them
// from here.
/**
* Wrapper that swallows path-escape errors and returns the raw input β
* used in tool *output* paths where we'd rather hand back the unsafe
* string than throw mid-render. Keep this as a separate verb so callers
* deliberately opt into the lenient behaviour.
*/
function vaultRelpath(target: string, vault: string): string {
try {
return vaultRelative(target, vault);
} catch {
return target;
}
}
// The `vault_path` field and its unresolved-value shape live in
// `./vault-path-field.ts`: every module that emits the field has to be
// able to reach the one function that enforces its contract, and this
// aggregator imports those modules, so it cannot be the one that holds
// it. `unresolvedField` comes back from there too, so the degraded-value
// shape has one definition as well.
// ββ Tool implementations ββββββββββββββββββββββββββββββββββββββββββββββββββββ
/**
* `discoverConfig`, or the reason it could not answer.
*
* `second_brain_status` exists to report what this install sees in its
* config, so a config it cannot read is the tool's SUBJECT, not a reason to
* fail: raising here cost the caller `config_path`, `config_exists`,
* `config_keys` and `config` - every field that answers the question - and
* returned an error naming nothing the operator could act on beyond what
* the payload would have said anyway.
*/
function discoverConfigOrReason(configPath: string | undefined): ConfigDiscovery | ConfigReadError {
try {
return discoverConfig(configPath);
} catch (err) {
if (err instanceof ConfigReadError) return err;
throw err;
}
}
async function toolStatus(ctx: ServerContext): Promise<Record<string, unknown>> {
const discovered = discoverConfigOrReason(ctx.configPath ?? undefined);
const broken = discovered instanceof ConfigReadError ? discovered : null;
// `exists: true` on the broken branch is the whole point of the read
// split: the file IS there, and `false` would say this install was never
// configured. `config_keys` and `config` cannot be known, so they carry
// the reason rather than an empty list an agent would read as "no keys".
const discovery: ConfigDiscovery =
broken === null
? (discovered as ConfigDiscovery)
: { path: broken.path, exists: true, data: {} };
// Three blocks below are gated on this answer, and on the UNEXAMINABLE
// branch each is built carrying the reason rather than skipped: an
// omitted block reads as the same confident negative the bare `false`
// did, which is precisely what the probe could not determine. The absent
// branch keeps omitting them, because there the omission IS the answer.
// A server with no vault (design D14) reports that, not a refusal: the
// vault-gated blocks are absent and the store block answers alone.
const served = contextVault(ctx);
const { present: vaultExists, unexaminable } =
served === null ? { present: false, unexaminable: null } : probeVaultDirectory(served);
const configKeys =
broken === null ? Object.keys(discovery.data).toSorted() : unresolvedField(broken);
// Safe to call on a vault that has no Brain layer yet β returns
// `present: false` with zero counts.
const brain = vaultExists
? computeBrainStatus(ctx.vault, {
withholdsPrivate: contextReach(ctx) !== TRANSPORT_REACH.local,
})
: unexaminable;
// On the broken branch this gate is unresolvable, so the block is built
// rather than skipped: `buildSearchStatusBlock` resolves its own config
// and degrades to `{ exists: false, error }` naming the same file. A skip
// would have been the silent omission - a missing block reads as "search
// is off", which is exactly the answer the gate could not give.
const searchDisabled = discovery.data["search_enabled"] === "false";
const search = searchDisabled
? null
: vaultExists
? await buildSearchStatusBlock(ctx)
: unexaminable;
// v0.10.9 β `vault` block exposes the shared exclusion policy plus
// aggregate include/exclude counts. Per-path detail lives in the CLI
// (`o2b vault status`); MCP payloads stay small.
//
// `resolveVaultScope` fails closed when `_brain.yaml` is malformed
// (design Β§5) β the right call for walkers that would otherwise
// silently drop the operator's policy. But this MCP tool is a
// read-only diagnostic, and the operator wants the brain / search /
// config blocks visible even when the vault scope cannot be
// resolved. Catch and degrade to `{ error: "..." }` instead of
// taking the whole `second_brain_status` payload down with it.
let vault: Record<string, unknown> | UnresolvedField | null = unexaminable;
if (vaultExists) {
try {
const scope = resolveVaultScope(ctx.vault);
const walk = walkVaultScope(ctx.vault, scope);
vault = {
ignore_source: scope.source,
rules: scope.rules.ignore.map((r) => ({ raw: r.raw, kind: r.kind })),
included: { files: walk.includedFiles, dirs: walk.includedDirs },
excluded: {
dirs: walk.excludedDirs.length,
files: walk.excludedFiles.length,
},
};
} catch (err) {
vault = { error: (err as Error)?.message ?? String(err) };
}
}
return {
config_path: String(discovery.path),
config_exists: discovery.exists,
config_keys: configKeys,
// The mapping passes with the vault's KNOWN resolved values: a
// credential the custody store holds, echoed under a quiet config key
// the shape passes cannot see, is scrubbed by the literal pass. An
// absent, empty or locked store contributes nothing, and the mapping
// is byte-identical to the bare single-argument call.
config:
broken === null
? redactConfigMapping(discovery.data, {
resolvedLiterals: served === null ? [] : resolvedSecretLiterals(served),
})
: unresolvedField(broken),
vault_path: vaultPathField(ctx),
// `boolean | { error }`. Both answerable cases keep their exact literal
// - `true` when the directory is there, `false` when it is genuinely
// not - and the third value exists only for the case that previously
// impersonated the second.
vault_exists: unexaminable ?? vaultExists,
...(vault ? { vault } : {}),
...(brain ? { brain } : {}),
...(search ? { search } : {}),
// The brain store block (design D12) comes last, so every field above
// keeps its place. It is always present: a store that does not exist
// yet, or cannot be used, is what the block reports.
store: storeStatusForCaller(
ctx,
buildStoreStatusBlock({
vault: vaultExists ? served : null,
configPath: ctx.configPath,
}),
),
};
}
async function toolQuery(
ctx: ServerContext,
args: Record<string, unknown>,
): Promise<Record<string, unknown>> {
// Refusing either way, but not with the same reason: an operator told
// their vault is missing goes and creates one, which is the wrong move
// when the directory is there behind a parent it cannot traverse.
const presence = probeVaultDirectory(ctx.vault);
if (presence.unexaminable !== null) {
throw new MCPError(INVALID_PARAMS, presence.unexaminable.error);
}
if (!presence.present) {
throw new MCPError(INVALID_PARAMS, `vault directory missing: ${ctx.vault}`);
}
const pattern = coerceStr(args, "pattern", false);
const limit = coerceInt(args, "limit", 50, 1, 500);
const offset = cursorOffsetArg("second_brain_query", args);
// Owner-scope isolation (context-integrity-gates, Unit A). This
// surface lists pages straight off the filesystem rather than through
// search, so it applies the rule itself - over the frontmatter
// `listVaultPages` has already parsed, so an unscoped call does no
// extra work and returns exactly what it always did.
//
// FAILS CLOSED, matching `isPathOwnerVisible` on the search path: the
// walk's diagnostic sink names every page whose file it could not read,
// and an unreadable page has an unknowable owner. Without the sink an
// unreadable page parses to empty metadata, reads as ownerless, and is
// shared with every scope. The sink is collected only under an active
// scope, so an unscoped call allocates nothing extra.
const scope = normalizeAgentScope(coerceAgentScope(ctx, args, false));
const notices: DegradationNotice[] = [];
// Root B: the reach the transport minted for this caller. A page
// reserved against remote reads never reaches the ownership filter
// below, and never reaches the count either.
const reach = contextReach(ctx);
const listed =
scope === null
? listVaultPages(ctx.vault, { reach })
: listVaultPages(ctx.vault, { notices, reach });
const unreadable = new Set(
notices
.filter((n) => n.code === DEGRADATION_CODE.frontmatterUnreadable)
.map((n) => n.path)
.filter((path): path is string => path !== undefined),
);
const pages =
scope === null
? listed
: listed.filter(
(p) => !unreadable.has(p.path) && isOwnerVisible(pageOwner(p.metadata), scope),
);
const needle = pattern ? pattern.toLowerCase() : null;
// The whole matched set is collected (no early break) so the offset
// window cuts one page and `next_cursor` continues the walk; keeping
// the loop open is what makes a cursor past the first page work.
const matched: Array<Record<string, unknown>> = [];
for (const p of pages) {
if (needle !== null && !p.title.toLowerCase().includes(needle)) continue;
matched.push({
title: p.title,
path: vaultRelpath(p.path, ctx.vault),
metadata: p.metadata,
});
}
const page = pageSlice(matched, offset, limit);
return {
vault_path: vaultPathField(ctx),
total_pages: pages.length,
returned: page.items.length,
limit,
pattern,
pages: page.items,
next_cursor: page.next_cursor,
};
}
async function toolVaultHealth(
ctx: ServerContext,
args: Record<string, unknown>,
): Promise<Record<string, unknown>> {
const repoArg = coerceStr(args, "repo", false);
const repoRoot = repoArg ?? ctx.repoRoot;
const results = doctor({
vault: ctx.vault,
config: ctx.configPath,
repoRoot: repoRoot ?? null,
});
const payload = results.map((r) => ({
name: r.name,
ok: r.ok,
message: r.message,
...(r.fix !== undefined ? { fix: r.fix } : {}),
}));
// Runtime-state notices (transient operational conditions) surfaced for
// pull consumers, mirroring the proactive SessionStart injection push.
// The projection carries the notice's structured next command when it has
// one, so a machine consumer reads the exit as a field instead of parsing
// it back out of `message`; a condition with no registered exit
// contributes no key at all.
const notices = collectRuntimeNotices(ctx.vault, {
configPath: ctx.configPath ?? undefined,
}).map((n) => ({
code: n.code,
severity: n.severity,
message: n.message,
...nextCommandField(n.code),
}));
return {
vault_path: vaultPathField(ctx),
config_path: ctx.configPath ? String(ctx.configPath) : null,
repo_root: repoRoot ? String(repoRoot) : null,
ok: payload.every((c) => c.ok),
checks: payload,
notices,
// Where this vault keeps its state, measured the same way and from
// the same value `o2b state status` renders. It rides `vault_health`
// rather than a tool of its own because the question it answers -
// "what is here, is it reachable, and what put it there" - is the
// question a caller already asked; a second tool would be a second
// place for the two answers to disagree. It is a sibling FIELD, not a
// contribution to `ok`: an absent surface is normal on a young vault
// and an unchecked one carries its own reason.
state_surfaces: inventoryStateSurfaces({
vault: ctx.vault,
env: process.env,
config: readConfigForStateSurfaces(ctx.configPath),
}),
};
}
/**
* The machine config the state overrides are read from.
*
* An unreadable config resolves to the strict fallback - no overrides -
* rather than propagating, because this is a READER: refusing the whole
* health report over a config file it could not parse would remove the
* one surface that could have said so. The `checks` array already carries
* the config fault by name.
*/
function readConfigForStateSurfaces(configPath: string | null): Readonly<Record<string, string>> {
try {
return discoverConfig(configPath ?? undefined).data;
} catch {
return {};
}
}
async function toolArtifactGet(
ctx: ServerContext,
args: Record<string, unknown>,
): Promise<Record<string, unknown>> {
const artifactId = coerceStr(args, "artifact_id", true) as string;
if (!ctx.artifactStore) {
throw new Error("artifact store unavailable in this context");
}
// Replay carries no reach or caller binding of its own - it is
// content-hash addressed and answers any caller - so the fence
// guarantee rests entirely on the parking side: every tool that parks
// shapes its stored text through the delivery binding BEFORE the
// serialized bytes are stored, and what replays here is the fenced
// copy. Binding artifacts to the minting session or re-shaping at
// replay is the recorded follow-up if a parking surface ever ships
// unshaped.
let content: string | null;
try {
content = ctx.artifactStore.get(artifactId);
} catch (err) {
// Malformed id (path-traversal attempt) β invalid params.
throw new MCPError(INVALID_PARAMS, (err as Error)?.message ?? String(err));
}
if (content === null) {
// Well-formed but absent / expired β tool-level error envelope.
throw new Error(`unknown or expired artifact_id: ${artifactId}`);
}
return { artifact_id: artifactId, full_chars: content.length, content };
}
function toolCapabilities(ctx: ServerContext): ToolCapabilityReport {
if (!ctx.capabilityReport) {
throw new Error("capability report unavailable in this context");
}
return ctx.capabilityReport;
}
const ARTIFACT_GET_OUTPUT_SCHEMA: OutputSchema = {
type: "object",
required: ["artifact_id", "full_chars", "content"],
properties: {
artifact_id: { type: "string" },
full_chars: { type: "integer" },
content: { type: "string" },
},
};
const CAPABILITIES_OUTPUT_SCHEMA: OutputSchema = {
type: "object",
required: [
"scope",
"server_name",
"static_tool_count",
"available_tool_count",
"advertised_tool_count",
"host_ceiling",
"available",
"withheld",
],
properties: {
scope: { type: "string", enum: TOOL_SCOPES },
server_name: { type: "string" },
static_tool_count: { type: "integer" },
available_tool_count: { type: "integer" },
advertised_tool_count: { type: "integer" },
// Every field but `kind` is nullable, and the shape vocabulary
// types a node with one `type` rather than a union - so those
// nodes declare presence and leave the kind to `kind`, which is
// the field that says which of them carry a value.
host_ceiling: {
type: "object",
required: ["target", "kind", "max_tools", "source", "reason", "within_ceiling"],
properties: {
kind: { type: "string", enum: TOOL_CEILING_KINDS },
},
},
available: {
type: "array",
items: {
type: "object",
required: ["name", "reason"],
properties: { name: { type: "string" }, reason: { type: "string" } },
},
},
withheld: {
type: "array",
items: {
type: "object",
required: ["name", "reason"],
properties: { name: { type: "string" }, reason: { type: "string" } },
},
},
},
};
/**
* Tombstones for the deprecated aliases removed in 1.0.0 (epic
* t_a77ade0a). The token-diet pass (t_3920db77) consolidated these 18
* tools into `brain_brief` / `brain_analytics` / `schema_inspect`
* views and kept the old names callable as hidden aliases; the 1.0.0
* sweep deletes the alias layer entirely. Calling a tombstoned name
* answers INVALID_PARAMS with the exact replacement instead of a
* generic METHOD_NOT_FOUND, so a stale client learns the migration
* from the error message itself. Zero token cost: tombstones are
* never advertised. The canonical map lives in core
* (src/core/removed-surfaces.ts) so `brain_doctor` shares it without
* importing the MCP layer; re-exported here for the server and tests.
*/
export { REMOVED_TOOLS };
// The set is named after the original payload (mutating writers). As
// of v0.10.10 it also hosts `brain_context`, which has to be
// always-loaded to be useful at session start. It was admitted here as
// "a reader tool" back then, but its handler regenerates the shared
// `Brain/active.md`, so under the write-mode-dominant concurrency kind
// (`tool-contract.ts`) it is a writer too and the set name now
// describes it exactly. Renaming the MCP server itself is deferred β
// see `docs/plans/2026-05-20-v0.10.10-design.md` Β§12.
const WRITER_TOOL_NAMES: ReadonlySet<string> = new Set([
"brain_apply_evidence",
"brain_context",
"brain_feedback",
"brain_note",
"brain_pinned_context",
]);
// First-pass surface of the two-pass catalog scope (Agent Surface
// Suite): the always-available diagnostic, the writer set, and the
// hydration tool. Everything else stays callable but unadvertised.
const CATALOG_ADVERTISED_NAMES: ReadonlySet<string> = new Set([
CAPABILITY_DIAGNOSTIC_TOOL,
...WRITER_TOOL_NAMES,
TOOL_HYDRATE_NAME,
]);
export function buildToolTable(scope: ToolScope = TOOL_SCOPE.full): ToolDefinition[] {
const all: ToolDefinition[] = [
{
name: CAPABILITY_DIAGNOSTIC_TOOL,
kind: "read",
description:
"Report runtime MCP tool availability and withheld-tool reasons for this server process.",
inputSchema: {
type: "object",
properties: {},
additionalProperties: false,
},
outputSchema: CAPABILITIES_OUTPUT_SCHEMA,
handler: toolCapabilities,
},
{
name: "second_brain_status",
kind: "read",
description: "Report Open Second Brain configuration and vault status.",
inputSchema: {
type: "object",
properties: {},
additionalProperties: false,
},
// No previewBudget: a vault with an indexed search and a populated
// Brain layer easily exceeds the default MCP preview cap, and
// the `search.*` / `brain.*` blocks are the whole point of the
// tool. Without this override, large payloads came back wrapped
// in a `{ preview_truncated, artifact_id, bytes_preview }`
// envelope β tests parsing `content[0].text` as JSON then lost
// every block the operator asked for.
handler: toolStatus,
},
{
name: "second_brain_query",
kind: "read",
description: "List vault pages with optional title substring filter.",
inputSchema: {
type: "object",
properties: {
pattern: {
type: "string",
description: "Optional case-insensitive substring matched against page titles.",
},
limit: {
type: "integer",
minimum: 1,
maximum: 500,
description: "Maximum number of matched pages to return (default 50).",
},
cursor: CURSOR_SCHEMA,
agent_scope: AGENT_SCOPE_SCHEMA,
},
additionalProperties: false,
},
previewBudget: MCP_PREVIEW_BUDGET,
handler: toolQuery,
},
// `second_brain_capture` and `event_log_append` were retired from
// the MCP surface in Β§32 (v0.10.8); Brain tools replace agent-side
// writes.
...BRAIN_TOOLS,
...SEARCH_TOOLS,
{
name: "vault_health",
kind: "read",
description:
"Run vault, config, and plugin manifest health checks, and report every state surface in the vault with its path, reachability, and the override that placed it.",
inputSchema: {
type: "object",
properties: {
repo: {
type: "string",
description: "Optional repository root to validate plugin manifests.",
},
},
additionalProperties: false,
},
handler: toolVaultHealth,
},
{
name: "brain_artifact_get",
kind: "read",
description:
"Fetch the full payload of a previously preview-truncated tool result by its artifact_id. Read-only.",
inputSchema: {
type: "object",
properties: {
artifact_id: {
type: "string",
description: "The artifact_id returned in a preview-truncated tool result envelope.",
},
},
required: ["artifact_id"],
additionalProperties: false,
},
outputSchema: ARTIFACT_GET_OUTPUT_SCHEMA,
handler: toolArtifactGet,
},
...SCHEMA_TOOLS,
...WATCHDOG_TOOLS,
...SKILL_TOOLS,
...WIRING_TOOLS,
];
if (scope === TOOL_SCOPE.writer) return all.filter((t) => WRITER_TOOL_NAMES.has(t.name));
// The hydrate tool closes over the finished table (itself included)
// so its catalog and schema lookups always reflect this process's
// real surface.
all.push(buildHydrateTool(() => all));
if (scope === TOOL_SCOPE.full) return all;
// Catalog scope: the compact first-pass set stays advertised; every
// other tool keeps `hidden` semantics - callable, not listed.
return all.map((t) =>
CATALOG_ADVERTISED_NAMES.has(t.name) || t.hidden === true ? t : { ...t, hidden: true },
);
}
export function findTool(tools: ReadonlyArray<ToolDefinition>, name: string): ToolDefinition {
const tool = tools.find((t) => t.name === name);
if (!tool) {
const tombstone = REMOVED_TOOLS[name];
if (tombstone !== undefined) {
throw new MCPError(
INVALID_PARAMS,
`${name} was removed in ${tombstone.removedIn}; call ${tombstone.target} with view="${tombstone.view}"`,
);
}
throw new MCPError(METHOD_NOT_FOUND, `unknown tool: ${name}`);
}
return tool;
}
// Re-export for callers that previously imported these from here. The
// canonical home is `src/core/agent-identity.ts`; new code should import
// from there.
export { PLACEHOLDER_AGENT_VALUES, normalizeAgentArgument };