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
/**
* Skill surface MCP tools (Agent Surface Suite).
*
* `list_skills` / `get_skill` let any MCP-connected agent discover and
* load the skills Open Second Brain ships in `skills/` (plus optional
* vault-local skills under `Brain/skills/`) without shell access or
* prior knowledge of skill names. `skills_attach` is the deterministic
* per-turn relevance surface: gated by the `skill_auto_attach` config
* key (default off), it scores skills against the current turn text
* with the shared lexical scorer and returns a char-budgeted block.
*/
import {
discoverConfig,
resolveSkillAutoAttach,
resolveSkillsDir,
resolveSkillsAttachTriggers,
resolveSkillsAttachUsageOrdering,
resolveTokenImpactLedgerEnabled,
} from "../core/config.ts";
import {
decisionModelModeFor,
resolveDecisionModelConfig,
type ResolvedDecisionModelConfig,
} from "../core/decision-model/config.ts";
import { deriveSkillUsage, skillUsageRankingWeights } from "../core/brain/skill-usage.ts";
import { buildSkillAttachment, type SkillAttachment } from "../core/surface/skill-attach.ts";
import {
buildSkillAttachmentWithDecision,
type SkillDecisionInfo,
} from "../core/surface/skill-attach-decision.ts";
import { isSkillOfferId, SKILL_OFFER_ID_KEY } from "../core/surface/skill-offer.ts";
import {
discoverSkills,
readSkillFile,
skillRoots,
SkillError,
type SkillErrorCode,
} from "../core/surface/skills.ts";
import { coerceInt, coerceStr } from "./coerce.ts";
import { MCP_PREVIEW_BUDGET } from "./preview-budget.ts";
import { INVALID_PARAMS, MCPError } from "./protocol.ts";
import { contextVault, type ServerContext, type ToolDefinition } from "./tool-contract.ts";
import { TOOL_ERROR_CODE, type ToolErrorCode } from "./tool-error-codes.ts";
/**
* The wire code for each `SkillError` kind. Total over the core union, so
* a new kind fails the type check until it is mapped here. The core's
* bare `NOT_FOUND` / `INVALID_PATH` never reached the wire and would be
* ambiguous in a cross-tool registry, so they are spelled per surface.
*/
const SKILL_ERROR_WIRE_CODE: Readonly<Record<SkillErrorCode, ToolErrorCode>> = Object.freeze({
NOT_FOUND: TOOL_ERROR_CODE.skillNotFound,
INVALID_PATH: TOOL_ERROR_CODE.skillInvalidPath,
});
function rootsFor(ctx: ServerContext): string[] {
const skillsDir = resolveSkillsDir(ctx.configPath ?? undefined);
return skillRoots({ repoRoot: ctx.repoRoot, vault: contextVault(ctx), skillsDir });
}
function toolListSkills(ctx: ServerContext): Record<string, unknown> {
const skills = discoverSkills(rootsFor(ctx));
return {
count: skills.length,
skills: skills.map((s) => ({
name: s.name,
description: s.description,
path: s.path,
// Same-named skills in an earlier root: the entry that won, plus where
// the copies it hid live. Empty means discovery found none.
shadowed: s.shadowed,
})),
};
}
/**
* The offer this fetch cites, or undefined when it cites none.
*
* A present-but-malformed value is refused rather than dropped: the caller is
* here and can be told, and silently continuing would put a skill fetch into
* the runtime's session log looking exactly like one that cited no offer.
*/
function readCitedOffer(args: Record<string, unknown>): string | undefined {
const raw = args[SKILL_OFFER_ID_KEY];
if (raw === undefined || raw === null) return undefined;
if (!isSkillOfferId(raw)) {
throw new MCPError(
INVALID_PARAMS,
`${SKILL_OFFER_ID_KEY} must be an offer id returned by skills_attach`,
);
}
return raw;
}
function toolGetSkill(ctx: ServerContext, args: Record<string, unknown>): Record<string, unknown> {
const name = coerceStr(args, "name", true)!;
const filePath = coerceStr(args, "file_path", false) ?? undefined;
const citedOffer = readCitedOffer(args);
const skills = discoverSkills(rootsFor(ctx));
const skill = skills.find((s) => s.name === name);
if (skill === undefined) {
const known = skills.map((s) => s.name).join(", ") || "(none)";
throw new MCPError(INVALID_PARAMS, `unknown skill: ${name}. Known skills: ${known}`, {
code: TOOL_ERROR_CODE.unknownSkill,
});
}
let content: string;
try {
content = readSkillFile(skill, filePath);
} catch (err) {
if (err instanceof SkillError) {
throw new MCPError(INVALID_PARAMS, err.message, { code: SKILL_ERROR_WIRE_CODE[err.code] });
}
throw err;
}
return {
name: skill.name,
description: skill.description,
path: skill.path,
...(filePath !== undefined ? { file_path: filePath } : {}),
...(citedOffer !== undefined ? { [SKILL_OFFER_ID_KEY]: citedOffer } : {}),
content,
};
}
/**
* The decision-model config when the `skills` use is not off, else null.
* Never throws: an unreadable config leaves today's path untouched.
*/
function skillsDecisionConfig(ctx: ServerContext): ResolvedDecisionModelConfig | null {
try {
const cfg = resolveDecisionModelConfig({
config: discoverConfig(ctx.configPath ?? undefined).data,
// With no vault there is no vault opt-out to read; `ctx.vault` would
// refuse there and the catch below would turn the use off.
vault: contextVault(ctx),
});
return decisionModelModeFor(cfg, "skills") === "off" ? null : cfg;
} catch {
return null;
}
}
function attachResult(
attachment: SkillAttachment,
decisionModel?: SkillDecisionInfo | null,
): Record<string, unknown> {
return {
enabled: true,
block: attachment.block,
// Identity of this offer, for the agent to cite back on get_skill so the
// invocation can be joined to it. Null when nothing was offered.
[SKILL_OFFER_ID_KEY]: attachment.offerId,
skills: attachment.items.map((item) => ({
name: item.name,
description: item.description,
path: item.path,
score: item.score,
})),
// Present only while the optional `skills` decision-model use is on.
...(decisionModel !== undefined && decisionModel !== null
? { decision_model: decisionModel }
: {}),
};
}
function toolSkillsAttach(
ctx: ServerContext,
args: Record<string, unknown>,
): Record<string, unknown> | Promise<Record<string, unknown>> {
const query = coerceStr(args, "query", true)!;
const maxSkills = coerceInt(args, "max_skills", 3, 1, 10);
if (!resolveSkillAutoAttach(ctx.configPath ?? undefined)) {
return { enabled: false, block: "", skills: [], [SKILL_OFFER_ID_KEY]: null };
}
const includeTriggers = resolveSkillsAttachTriggers(ctx.configPath ?? undefined);
const skills = discoverSkills(rootsFor(ctx));
// Usage-ordered offers (t_5d1ec8a8), default off: with the ordering knob
// on, the whole continuity store is read exactly once per attach call and
// the same weight map feeds both build paths, so the deterministic and
// decision-model offers stay coherent. Off, the vault is never read here.
// The map is the ranking weight (skillUsageRankingWeights), not the decay
// weight deriveSkillUsage reports: that one clamps at 1, so among recently
// used skills frequency was invisible and the name tie-break decided. One
// pinned clock feeds both derivations, so the counts and the recency half
// of the weight never disagree about what "now" is.
// With no vault there is no continuity store to read: the offers keep
// the deterministic order.
const nowMs = Date.now();
const usageVault = contextVault(ctx);
const usageWeight =
usageVault !== null && resolveSkillsAttachUsageOrdering(ctx.configPath ?? undefined)
? skillUsageRankingWeights(
deriveSkillUsage(usageVault, { nowMs }),
new Set(skills.map((s) => s.name)),
{ nowMs },
)
: undefined;
const attachmentOpts = {
query,
skills,
maxSkills,
includeTriggers,
...(usageWeight !== undefined ? { usageWeight } : {}),
};
const decisionConfig = skillsDecisionConfig(ctx);
if (decisionConfig === null) {
return attachResult(buildSkillAttachment(attachmentOpts));
}
return buildSkillAttachmentWithDecision({
...attachmentOpts,
config: decisionConfig,
tokenImpact: resolveTokenImpactLedgerEnabled(ctx.configPath ?? undefined),
}).then((attachment) => attachResult(attachment, attachment.decisionModel));
}
export const SKILL_TOOLS: ReadonlyArray<ToolDefinition> = [
{
name: "list_skills",
kind: "read",
description:
"List agent skills shipped with Open Second Brain (and vault-local Brain/skills/) with one-line descriptions. Each entry carries a shadowed array naming the same-named skill directories it overrode, empty when discovery found none. Read-only.",
inputSchema: {
type: "object",
properties: {},
additionalProperties: false,
},
previewBudget: MCP_PREVIEW_BUDGET,
handler: (ctx) => toolListSkills(ctx),
},
{
name: "get_skill",
kind: "read",
description:
"Fetch a skill's SKILL.md content by name; optional file_path reads an auxiliary file inside the same skill directory. An offer_id from skills_attach is echoed back on the result; a malformed one is refused, never dropped. Read-only.",
inputSchema: {
type: "object",
properties: {
name: {
type: "string",
description: "Skill name as returned by list_skills.",
},
file_path: {
type: "string",
description: "Optional relative path to an auxiliary file inside the skill directory.",
},
[SKILL_OFFER_ID_KEY]: {
type: "string",
description:
"Optional offer_id from skills_attach, recording which offer this fetch came from.",
},
},
required: ["name"],
additionalProperties: false,
},
handler: (ctx, args) => toolGetSkill(ctx, args),
},
{
name: "skills_attach",
kind: "read",
description:
"Score skills against the turn text; returns a char-budgeted block of relevant summaries and the offer_id to cite on get_skill (null when none). Candidates without a discriminating term are dropped. Usage-ordered when skills_attach_usage_ordering is on. enabled:false unless skill_auto_attach is set.",
inputSchema: {
type: "object",
properties: {
query: {
type: "string",
description: "Current turn text to score skills against.",
},
max_skills: {
type: "integer",
minimum: 1,
maximum: 10,
description: "Maximum number of skills to attach (default 3).",
},
},
required: ["query"],
additionalProperties: false,
},
previewBudget: MCP_PREVIEW_BUDGET,
handler: (ctx, args) => toolSkillsAttach(ctx, args),
},
];