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
/**
* Shared MCP tool contract types. Extracted from `./tools.ts` so that
* leaf tool modules (and `./capabilities.ts`) depend only on this pure
* leaf for the handler / definition shape, instead of importing back
* from the `tools.ts` aggregator that assembles them — which formed one
* large import cycle spanning the whole `src/mcp` tool surface.
*
* `ToolScope` and the capability-report shapes live here rather than in
* `./capabilities.ts` because `ServerContext.capabilityReport` references
* `ToolCapabilityReport`, and `./capabilities.ts` in turn needs
* `ToolDefinition`; keeping the report types below both preserves a
* single downward dependency direction.
*/
import { resolvedTransportReach, type TransportReach } from "../core/graph/transport-reach.ts";
import type { OutputSchema } from "./output-contract.ts";
import type { ArtifactStore } from "./artifact-store.ts";
import type { ProgressSink } from "../core/brain/progress.ts";
import type { ToolCeilingKind } from "../core/runtime/host-facts.ts";
import type { HarnessId } from "../core/brain/scoped-rules.ts";
/**
* The tool surfaces a server process can advertise.
*
* A closed vocabulary rather than a bare union because the members were
* hand-copied into four places - the union, the `second_brain_capabilities`
* output schema, the `--scope` validity check and the `--scope` error
* message - with nothing asserting the four agreed. Every one of those
* sites now derives from this object.
*/
export const TOOL_SCOPE = Object.freeze({
/** Every tool advertised. */
full: "full",
/** The always-loaded Brain writer/reader set, and nothing else. */
writer: "writer",
/** Two-pass catalog: a compact advertised set, everything still callable. */
catalog: "catalog",
} as const);
/** Closed union over {@link TOOL_SCOPE}. */
export type ToolScope = (typeof TOOL_SCOPE)[keyof typeof TOOL_SCOPE];
/** Membership list, in widest-surface-first order. */
export const TOOL_SCOPES: ReadonlyArray<ToolScope> = Object.freeze([
TOOL_SCOPE.full,
TOOL_SCOPE.writer,
TOOL_SCOPE.catalog,
]);
/** Narrow a scope name arriving from argv, a config file or a profile. */
export function isToolScope(value: unknown): value is ToolScope {
return typeof value === "string" && (TOOL_SCOPES as ReadonlyArray<string>).includes(value);
}
export interface ToolCapabilityEntry {
readonly name: string;
readonly reason: string;
}
/**
* What the running server can say about the per-workspace tool limit of
* the host that launched it.
*
* Present on every report, including - especially - when the answer is
* "nobody has established one". A host that caps a workspace at forty
* tools and is handed a hundred and ten drops the excess in silence, so
* a report that omitted the ceiling when it did not know one would be
* indistinguishable from a host with no limit at all. `kind` never
* collapses `unknown` into `unbounded`, and `reason` carries the written
* explanation the `RUNTIME_FACTS` row owes for saying nothing.
*/
export interface HostCeilingReport {
/** The install target that launched this server; `null` when unnamed. */
readonly target: string | null;
readonly kind: ToolCeilingKind;
/** The published limit; `null` unless `kind` is `declared`. */
readonly max_tools: number | null;
/** Where the limit (or its absence) is published; `null` when unknown. */
readonly source: string | null;
/** Why there is no answer; `null` unless `kind` is `unknown`. */
readonly reason: string | null;
/** Advertised tools against `max_tools`; `null` when there is no number. */
readonly within_ceiling: boolean | null;
}
export interface ToolCapabilityReport {
readonly scope: ToolScope;
readonly server_name: string;
readonly static_tool_count: number;
readonly available_tool_count: number;
/**
* The tools a host actually LISTS: `available_tool_count` minus the
* ones marked `hidden`, which `tools/list` filters out. Under the
* `catalog` surface it is seven whatever the tool table's size - the
* capability diagnostic, the five always-loaded Brain tools and
* `tool_hydrate` - and it is this number the host's ceiling applies
* to. Stated as the relation rather than as the gap, which was a
* figure that went stale on the next tool added and twice had.
*
* Seven is the NO-WINDOW count. `evaluateToolCapabilities` applies
* the runtime capability window before counting, so a window that
* withholds one of those seven lowers this number with it - the only
* exception being the capability diagnostic, which no window
* withholds.
*/
readonly advertised_tool_count: number;
readonly host_ceiling: HostCeilingReport;
readonly available: ToolCapabilityEntry[];
readonly withheld: ToolCapabilityEntry[];
}
/**
* The launch-time facts the scoped standing rules resolve their scope
* from (`src/core/brain/scope-identity.ts`), fixed per server process.
*
* Both are owned by whoever STARTED the process - the working directory
* it was started in and the `--harness` (or `--host-target`) its packaged
* registration names - and neither can be named by a caller: no tool
* takes a harness or a workspace argument, and
* `tests/core/architecture/harness-identity-census.test.ts` keeps it so.
*/
export interface RuleScopeSources {
/** The process working directory captured at launch; `null` when none was given. */
readonly workspaceDir: string | null;
/** `--harness`, else `--host-target`, else `null`. */
readonly harness: HarnessId | null;
}
/**
* The per-request identity a transport resolved from a credential
* (write-side-trust, Task 7). The HTTP transport mints it from the
* presented bearer token or shared key; stdio and the CLI bridge pass
* none and keep the config-derived identity.
*
* It lives on this leaf module because the context carries it and every
* writer tool reads it off the context; `./server.ts` re-exports the
* type so the transport-facing spelling does not move.
*/
export interface RequestIdentity {
readonly agent: string;
readonly via: "token" | "shared-key";
}
export interface ServerContext {
/**
* The vault this server serves. On a server with no vault (design D14)
* reading it throws the uniform "this tool needs a vault" refusal, so a
* vault-adapter tool refuses at its first use of the vault and every
* other tool never notices. Read {@link contextVault} where no vault is
* an answer rather than a refusal.
*/
readonly vault: string;
/**
* The vault, or `null` when the server runs with none. Set by the live
* server; absent on a hand-built context, whose `vault` is then the
* answer.
*/
readonly vaultOrNull?: string | null;
readonly configPath: string | null;
readonly repoRoot: string | null;
readonly capabilityReport?: ToolCapabilityReport;
/**
* Per-process preview-artifact store (v0.18.0). Present on the live MCP
* server context; `brain_artifact_get` reads parked tool-result payloads
* back through it. Optional so manually-built contexts stay valid.
*/
readonly artifactStore?: ArtifactStore;
/**
* How far the caller of this process had to reach to get here, minted
* by the transport that accepted the request (see
* `src/core/graph/transport-reach.ts`).
*
* Optional on the TYPE and mandatory in EFFECT: read it through
* {@link contextReach}, never directly. A context assembled by hand -
* an embedded caller, a test - established nothing about who is asking,
* and {@link contextReach} answers that with the narrowest reach rather
* than the widest. The field is optional so those contexts stay valid;
* the reader is what makes the omission fail closed instead of silently
* granting local access.
*/
readonly reach?: TransportReach;
/**
* Resolved agent identity for this server process
* (context-integrity-gates, Unit A), from `resolveAgentName`.
*
* It exists because `brain_context` — the documented session-bootstrap
* surface — takes NO arguments at all (`{properties:{},
* additionalProperties:false}`), so it has no other way to learn who
* is asking. It is the fallback scope for the GATED preference-backed
* surfaces only: those cannot narrow anything unless the operator has
* set `integrity.owner_scope_delivery` to `fail`. The ungated
* search-backed surfaces deliberately do NOT fall back to it, because
* defaulting a scope there would narrow every search in every vault.
*
* Optional so a manually-built context stays valid and unscoped.
*/
readonly agentName?: string;
/**
* The credential-minted identity of the ONE request this context was
* built for (write-side-trust, Task 7), when the transport resolved
* one. `undefined` for stdio, the CLI bridge and every hand-built
* context: there, `agentName`'s config resolution is the caller's
* identity and nothing about the request contradicts it.
*
* A property of the per-request context, never of the server: one
* MCPServer serves concurrent HTTP requests, and this is what makes a
* token's write-side decisions - the permission subjects, the
* owner-write gate, the agent a signal or preference is stamped under
* - answer for the token's agent instead of the process config's.
*/
readonly requestIdentity?: RequestIdentity;
/**
* Where the scoped standing rules look for their scope. Optional so a
* manually-built context stays valid; absent resolves no project and
* no harness, so a hand-built context matches no scoped file.
*/
readonly ruleScope?: RuleScopeSources;
}
/**
* The dispatch class of one tool: does any operation it can run mutate
* durable vault state?
*
* Distinct from `ToolCeilingKind` (`src/core/runtime/host-facts.ts`),
* which classifies a HOST's published tool ceiling - same member name,
* unrelated fact.
*
* The rule is write-mode-dominant: a tool that CAN write is `write`,
* decided per operation family at registration, never per arguments at
* dispatch - no args parsing ever re-classifies a call. A dual-capability
* tool (`brain_watchdog` remediate, `brain_lifecycle` apply,
* `brain_dream`, `brain_receipts` fold) is `write` because of its write
* half. Fail-soft observability appends (metrics ledger samples, opt-in
* context receipts, route-latency records) do NOT make a tool `write`:
* the stdio transport runs reads concurrently and accepts losing a
* fail-open telemetry append under `ELOCKED` rather than serializing the
* read path (see `src/mcp/stdio.ts`).
*
* The field never reaches the wire: the `tools/list` projection
* (`MCPServer.handleToolsList`) picks its advertised fields explicitly,
* and `tests/mcp/mcp.test.ts` pins that exact key set.
*/
export const TOOL_KIND = Object.freeze({
/** Every operation the tool runs is a read or fail-soft telemetry. */
read: "read",
/** At least one operation the tool can run mutates durable state. */
write: "write",
} as const);
/** Closed union over {@link TOOL_KIND}. */
export type ToolKind = (typeof TOOL_KIND)[keyof typeof TOOL_KIND];
export interface ToolDefinition {
readonly name: string;
readonly description: string;
readonly inputSchema: Record<string, unknown>;
readonly outputSchema?: OutputSchema;
/**
* The dispatch class of this tool ({@link TOOL_KIND}): `read` when
* every operation it can run is a read or fail-soft telemetry,
* `write` when any operation can mutate durable vault state -
* write-mode-dominant, decided here at registration and never from
* arguments at dispatch. Required so the partition is stated where the
* tool is defined; the stdio transport treats an absent value as
* `write` (fail-closed) so a hand-built definition that casts the
* field away can only ever lose serialization, never safety. Metadata
* only: it never reaches the `tools/list` wire payload.
*/
readonly kind: ToolKind;
/**
* Optional MCP preview budget in characters (v0.18.0). When set and
* the serialized result exceeds it, the JSON-RPC `tools/call` path
* parks the full payload in the artifact store and returns a bounded
* preview envelope in `content[0].text` instead, leaving
* `structuredContent` intact. A tool with no budget is never truncated
* - opt-in only. The CLI bridge ignores the budget entirely.
*/
readonly previewBudget?: number;
/**
* When true the tool stays callable via `tools/call` but is omitted
* from `tools/list` (token-diet): deprecated aliases keep working
* for old clients without re-paying their schema in every list.
*/
readonly hidden?: boolean;
/**
* The tool's implementation.
*
* The third parameter is per-REQUEST, which is exactly why it is a
* parameter and not a `ServerContext` field: the context is built once
* per server (`MCPServer.context`), while a progress token belongs to
* the single `tools/call` that carried it.
*
* It is optional in the type, and TypeScript lets a function of fewer
* parameters satisfy a type declaring more, so none of the registered
* tools needed editing to gain it - a handler that cannot report
* progress simply keeps its two-parameter signature. `undefined` means
* the client asked for no progress, or the transport could not carry
* it; in both cases the handler behaves exactly as it did before,
* because `onProgress` is the same optional-observer idiom the core
* options interfaces already use.
*/
readonly handler: (
ctx: ServerContext,
args: Record<string, unknown>,
onProgress?: ProgressSink,
) => Promise<unknown> | unknown;
}
/**
* The reach a handler must answer at, resolved fail-closed.
*
* A context carrying no minted reach is not a context that proved local
* access; it is one where nobody established anything, and an
* unestablished trust level is not the absence of a boundary. Same
* convention `entityStatusInScope` follows for a status outside its
* vocabulary, and `owner-scope-view.ts` for an unresolved owner.
*/
export function contextReach(ctx: ServerContext): TransportReach {
return resolvedTransportReach(ctx.reach);
}
/**
* The vault a context serves, or `null` when it serves none: for the tools
* that answer without a vault (`second_brain_status`), which must not trip
* the refusal reading `ctx.vault` raises there.
*/
export function contextVault(ctx: ServerContext): string | null {
return ctx.vaultOrNull !== undefined ? ctx.vaultOrNull : ctx.vault;
}
/**
* Stable error code of the refusal a vault-adapter tool gives on a server
* with no vault: the vault adapter's own code, one definition for both.
*/
export { VAULT_ADAPTER_REQUIRED_CODE as VAULT_REQUIRED_CODE } from "../core/vault-adapter/codes.ts";
/** The refusal message of `tool` on a server with no vault. */
export function vaultRequiredToolMessage(tool: string | undefined): string {
const subject = tool === undefined ? "this request" : `\`${tool}\``;
return (
`${subject} needs a vault, and this Open Second Brain server runs without one; ` +
"configure a vault (`o2b init --vault <path>`, or `vault:` in the machine config) " +
"and restart the server. The brain store tools work without a vault."
);
}