Skip to content

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

feat: agent capability CLI integration - runtime MCP capabilities, inherited JSON, completions (#50)

Sol Aitken3a5d5c3cfb59
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index a4c29558..1e02d946 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.22.0",
+ "version": "0.23.0",
"description": "Plugin-first second brain package for AI agents and humans.",
"author": {
"name": "Open Second Brain contributors"
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index 57140308..8de71fe1 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.22.0",
+ "version": "0.23.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"skills": "./skills",
"hooks": "./hooks/hooks.json",
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e7a2a7bb..d53d9d80 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,41 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [0.23.0] - 2026-05-30
+
+Agent capability and CLI integration. MCP servers can now narrow the advertised
+tool surface at runtime without changing the static registry, while the CLI gains
+a shared command manifest, shell completions, and inherited JSON fallback for
+commands that did not previously have a machine-readable output mode.
+
+### Added
+
+- Runtime MCP capability window (`src/mcp/capabilities.ts`) with repeatable
+ `o2b mcp --allow-tool`, `--disable-tool`, and `--max-tools` flags. The
+ evaluator runs after static scope filtering, so it can narrow the full server
+ but cannot expose full-server tools through the writer-only scope.
+- Full-scope diagnostic MCP tool `second_brain_capabilities`, returning the
+ available tool list and stable withheld-tool reasons for the current server
+ process. `o2b mcp --probe --json` emits the same report for install checks and
+ operator diagnostics.
+- Shared CLI command manifest (`o2b help --json`) and generated shell completion
+ scripts via `o2b completions --shell bash|zsh|fish|elvish|nushell|powershell`.
+- Inherited `--json` parsing for CLI commands plus a redacted fallback envelope
+ for commands without an existing semantic JSON contract.
+
+### Changed
+
+- Existing semantic JSON commands keep their native payloads instead of being
+ wrapped by the fallback envelope, including nested Brain/Search/Vault/Pay
+ Memory command groups and `o2b install --json`.
+
+### Notes
+
+- New full-server MCP tool count: 46 -> 47. Writer scope remains the same five
+ always-loaded tools (`brain_feedback`, `brain_apply_evidence`, `brain_note`,
+ `brain_context`, `brain_pinned_context`).
+- Full suite green on merge: 2842 tests passing.
+
## [0.22.0] - 2026-05-29
Vault portability + session economy. A new `portability/` subsystem makes
@@ -39,13 +74,13 @@ install stays byte-identical.
routed through the resolver. Inspect with `o2b vault map`.
- Named multi-vault profiles (`portability/profiles.ts`). A registry in
`profiles.json` beside the config with `o2b vault profile list / create
- / switch` and a `brain_switch_vault` MCP tool; activation is a pointer
+/ switch` and a `brain_switch_vault` MCP tool; activation is a pointer
(no symlinks). `resolveVault` consults the active profile before the
bare config `vault` key; with no registry, resolution is unchanged.
- Vault graph export/import (`portability/graph.ts`). `o2b brain
- graph-export` serialises the user's pages (wikilinks + typed relations)
+graph-export` serialises the user's pages (wikilinks + typed relations)
to a stable, byte-identical `graph.json`; `o2b brain graph-import
- --mode skip|overwrite|merge` reconstructs page stubs, every write
+--mode skip|overwrite|merge` reconstructs page stubs, every write
guarded by `ensureInsideVault`.
### Notes
@@ -2097,7 +2132,7 @@ with `source_type: inline`, the source-file wikilink in `source`,
and a `dedup_hash`over the normalised payload. After capture
the source line is annotated`@osbβœ“ [[sig-...]]`(inline form)
or the info-string flips to`osb-checked`with a`<!-- @osbβœ“
- [[sig-...]] -->`comment line (block form), making re-runs
+ [[sig-...]] -->`comment line (block form), making re-runs
idempotent. Default ignore set covers`Brain/`, `.git`,
`node_modules`, `.obsidian`, `.trash`, `.stversions`,
`.open-second-brain`; additional excludes via `--exclude`,
diff --git a/README.md b/README.md
index e76f75ac..c3aa28a7 100644
--- a/README.md
+++ b/README.md
@@ -133,6 +133,9 @@ o2b vault profile switch work # Activate a named multi-vault profile
o2b brain agent-query --agent claude --json # Source-agent provenance query
o2b brain agent-diff --mode diff --agent claude --agent codex
o2b search "<query>" # FTS5 over the vault
+o2b help --json # Machine-readable command/flag manifest
+o2b completions --shell zsh # Completion script for bash/zsh/fish/elvish/nushell/powershell
+o2b mcp --probe --json --disable-tool second_brain_query # Capability-aware MCP probe
o2b update # Update across detected runtimes
```
@@ -142,6 +145,7 @@ Full list (~50 verbs across `o2b`, `o2b brain`, `o2b vault`, `o2b discipline`, P
- Plain Markdown on your filesystem. No daemon, no background writes.
- The MCP server is a stdio subprocess that exits with the parent runtime.
+- MCP runtime capability flags (`--allow-tool`, `--disable-tool`, `--max-tools`) can narrow the advertised tool surface per process without widening the writer-only scope.
- Secrets are not supposed to live in the vault. Daily logs and config exports go through a best-effort redactor for common secret-name patterns.
- Brain mutations (`dream`, `merge`, `upgrade`) take a pre-run snapshot with a SHA-256 sidecar; `o2b brain rollback` aborts on drift unless `--force-rollback`.
- Lifecycle review commands (`intent-review`, `retention`, `monthly`) are read-only. Retention emits recommendations only; it never deletes, moves, or edits Brain artifacts.
diff --git a/docs/brainstorm/agent-capability-cli-integration/README.md b/docs/brainstorm/agent-capability-cli-integration/README.md
new file mode 100644
index 00000000..26849163
--- /dev/null
+++ b/docs/brainstorm/agent-capability-cli-integration/README.md
@@ -0,0 +1,16 @@
+# Agent capability + CLI integration
+
+Phase 0 artifacts for the multi-task feature-release scope covering:
+
+- `t_4acb2c72` - runtime MCP capability verification
+- `t_01810c33` - inherited CLI `--json`
+- `t_93bd0cc1` - shell completions
+
+Primary artifacts:
+
+- `design.md`
+- `plan.md`
+- `variants.md`
+- `adr.md`
+- `cli-output/prompt.md`
+- `cli-output/claude.md`
diff --git a/docs/brainstorm/agent-capability-cli-integration/adr.md b/docs/brainstorm/agent-capability-cli-integration/adr.md
new file mode 100644
index 00000000..bdc6d89e
--- /dev/null
+++ b/docs/brainstorm/agent-capability-cli-integration/adr.md
@@ -0,0 +1,23 @@
+# ADR: Agent capability + CLI integration foundation
+
+## Status
+
+Accepted for implementation in this feature branch.
+
+## Context
+
+The board comments for `t_4acb2c72` note that runtime tool capability verification needs an ADR before implementation because Open Second Brain currently has only static MCP `ToolScope` filtering. The same PR also includes two CLI integration tasks: inherited `--json` output and shell completions.
+
+## Decision
+
+Add two separate foundations:
+
+- MCP runtime capabilities remain a small layer above static `ToolScope`. They can withhold tools only after static scope has already selected the candidate set, and every withheld tool must appear in a diagnostic report with a reason.
+- CLI discovery/completions use a CLI-only command manifest. This manifest does not own command dispatch; it owns machine-readable metadata for help JSON, fallback JSON, and shell completion generation.
+
+## Consequences
+
+- Static writer scope remains the access-control baseline.
+- Agents can ask why a tool is unavailable instead of inferring from a missing tool list.
+- CLI completions and discovery share metadata without a new CLI framework dependency.
+- The project keeps two intentionally small registries rather than one large cross-surface registry.
diff --git a/docs/brainstorm/agent-capability-cli-integration/cli-output/claude.md b/docs/brainstorm/agent-capability-cli-integration/cli-output/claude.md
new file mode 100644
index 00000000..baa973bc
--- /dev/null
+++ b/docs/brainstorm/agent-capability-cli-integration/cli-output/claude.md
@@ -0,0 +1,39 @@
+### Variant 1: Independent additive layers
+
+- **Approach**: Implement each of the three tasks in its own seam with no shared abstraction. The runtime capability check becomes a thin predicate wrapper around `buildToolTable` in `server.ts`; the `--json` work adds an inheritable `FlagSpec` plus a new `src/cli/json-helpers.ts`; completions ship as a generator that walks each command's existing `FlagsSchema`. Nothing is unified - three small, independently revertible additions.
+- **Trade-offs**:
+ - Pro: smallest blast radius; each piece is independently testable and revertible.
+ - Pro: respects the "small, dependency-free CLI grammar" convention with minimal disruption.
+ - Pro: capability layer stays additive on top of static scope, easy to keep transparent.
+ - Con: three sources of truth - the completion generator must re-walk command schemas and can drift from real flags unless carefully wired (tension with the anti-drift constraint).
+ - Con: no synergy; the `--json` discovery contract and completions duplicate command-metadata traversal.
+- **Complexity**: medium
+- **Risk**: low
+
+### Variant 2: Single declarative manifest spine
+
+- **Approach**: Introduce one declarative registry describing both MCP tools (scope plus runtime capability predicates) and CLI commands (flags, including an inherited `--json`). The runtime capability filter, the shell-completion generator, and the JSON-envelope contract all derive from this single manifest, so `help --json`, `completions`, and tool exposure share one source of truth.
+- **Trade-offs**:
+ - Pro: anti-drift by construction - completions and help cannot diverge from declared flags (directly satisfies the registry/manifest constraint).
+ - Pro: agent-discoverable surface (`help --json` enumerates every command/flag) and a coherent capability model across CLI and MCP.
+ - Con: large refactor touching `argparse`, every CLI verb, `tools.ts`, and `server.ts`; high chance of brushing against public-API backward-compat constraints.
+ - Con: over-engineers two priority-1 ergonomic tasks by coupling them to the design-heavy capability system that the board says needs an ADR first.
+ - Con: a single registry change has wide blast radius and harder review.
+- **Complexity**: large
+- **Risk**: high
+
+### Variant 3: Phased - shared CLI registry now, ADR-gated capability layer
+
+- **Approach**: Ship the two priority-1 ergonomic tasks together this PR behind a shared _CLI command manifest_ (used both by the inheritable `--json` flag + `json-helpers.ts` and by the completion generator, so they cannot drift), scoped to the CLI only. Land the runtime capability verification as a separate, transparent layer that wraps static `ToolScope` with a capability predicate plus a probe/diagnostic path, designed ADR-first and kept minimal in this scope.
+- **Trade-offs**:
+ - Pro: matches the actual priorities (1/1/3) and the board's "needs an ADR before build" note for the capability system.
+ - Pro: one shared CLI manifest covers `--json` and completions without dragging MCP into the refactor, satisfying the anti-drift constraint where it matters.
+ - Pro: capability filtering stays additive on top of static scope with an explicit probe (satisfies "no silent hiding of tools").
+ - Con: two registries (CLI command manifest + MCP capability predicates) rather than one unified spine.
+ - Con: the capability piece may land partially or as a thin first cut, deferring full dynamism.
+- **Complexity**: medium
+- **Risk**: low
+
+### Recommended: Variant 3
+
+**Rationale**: It honors the triage reality - two ergonomic priority-1 tasks that are cheap and a priority-3 capability system the board explicitly says needs an ADR before build - instead of forcing them into one coupled abstraction as Variant 2 does. The shared CLI manifest captures the real synergy (completions + `--json` from one source of truth, satisfying the anti-drift constraint) that Variant 1 misses, while keeping the capability layer additive, transparent via a probe path, and on top of static scope as the constraints require. This sequencing keeps the core deterministic and dependency-light while letting the design-heavy piece mature behind an ADR rather than blocking the easy wins.
diff --git a/docs/brainstorm/agent-capability-cli-integration/cli-output/prompt.md b/docs/brainstorm/agent-capability-cli-integration/cli-output/prompt.md
new file mode 100644
index 00000000..99190379
--- /dev/null
+++ b/docs/brainstorm/agent-capability-cli-integration/cli-output/prompt.md
@@ -0,0 +1,169 @@
+You are brainstorming architectural variants for the following task. Do not write code. Do not write a final design. Only produce variants and a recommendation.
+
+# Task
+
+This is a multi-task PR scope selected from the open-second-brain Hermes triage board.
+
+## Task t_4acb2c72 - [upstream:core] Agent runtime capability verification and constraint window
+
+**Source**: https://github.com/RedPlanetHQ/core/releases/tag/0.7.12
+**Repo**: RedPlanetHQ/core (1600 stars)
+**Released**: 0.7.12 (2026-05-19T06:23:06Z)
+
+### What
+
+CORE introduced a runtime window and capability check system that verifies what actions and integrations are available at runtime before attempting execution. The gateway checks runtime constraints and capability availability dynamically rather than relying on static configuration.
+
+### Why useful for OSB
+
+OSB MCP tool exposure uses a static ToolScope (full or writer) to filter which tools are available to agents. A dynamic runtime capability check would allow OSB to adapt tool availability based on current context, resource constraints, and agent identity. This would improve the safety and relevance of tool exposure in multi-agent scenarios.
+
+### Status in OSB
+
+- **Verdict**: present_weaker
+- **Codegraph hints**: src/mcp/tools.ts:193 (ToolScope type), src/mcp/tools.ts:57 (ToolDefinition interface), src/mcp/server.ts:56 (tools property on MCPServer), src/mcp/tools.ts:207 (buildToolTable with scope parameter). OSB has static tool scoping but no dynamic runtime capability verification.
+
+### Notes
+
+The upstream system checks capabilities at runtime versus OSB static scope. Could complement OSB existing ToolScope by adding a runtime check layer on top of the static tool table.
+
+### Board comments
+
+- osb-triage-validator @ 2026-05-27T11:28Z: sanity clean; no cluster; priority set to 2 from 4. present_weaker, but dynamic capability model is design-heavy on top of static ToolScope; needs an ADR before build.
+- osb-triage-validator @ 2026-05-29T07:07Z: sanity clean; no cluster; priority set to 3 from 2. present_weaker with concrete hints; dynamic capability verification is clear scope, about one week.
+
+## Task t_01810c33 - [upstream:mem0] Uniform --json flag across all o2b CLI commands for machine-readable output
+
+**Source**: https://github.com/mem0ai/mem0/releases/tag/openclaw-v1.0.8
+**Repo**: mem0ai/mem0 (56777 stars)
+**Released**: openclaw-v1.0.8 (2026-04-22T11:46:36Z) - "Mem0 OpenClaw Plugin v1.0.8"
+
+### What
+
+mem0's OpenClaw plugin v1.0.8 added a uniform `--json` flag to all 16 CLI commands for machine-readable output, plus a `cli/json-helpers.ts` module providing `jsonOut`, `jsonErr`, and `redactSecrets` utilities for consistent structured output. Quote from release notes: "Agents can call `openclaw mem0 help --json` to discover every command and flag". The flag standardizes envelope shape (data + errors) across the surface so agents can parse outputs without per-command exception handling.
+
+### Why useful for OSB
+
+The `o2b` CLI is invoked by agents (Claude Code router, Hermes profiles) as much as by humans. Agents currently consume stdout text and either rely on per-command parsing or fall back to MCP for structured output. A uniform `--json` flag on all o2b subcommands (brain doctor/note/feedback/query/scan-inline/import-session/digest/dream, payment ..., snapshot, etc.) would let any agent script the CLI reliably without needing the MCP surface for read-only ops. The OSB-side helper module would centralize secret-redaction (Brain crypt passwords, etc.) so each command doesn't reimplement it.
+
+### Status in OSB
+
+- **Verdict**: not_in_osb_useful
+- **Codegraph hints**: src/cli/argparse.ts:19 (FlagSpec interface), src/cli/argparse.ts:38 (parseFlags - parses argv against per-command schemas). Each subcommand declares its own FlagsSchema; no global helper. Some commands surface JSON output by hardcoded format flag; uniform contract is absent.
+
+### Notes
+
+Two-part implementation: (1) add `json` as an inheritable FlagSpec mixed into every CLI subcommand's schema at parse time; (2) add `src/cli/json-helpers.ts` with `jsonOut(data)`, `jsonErr(error)`, `redactSecrets(obj)` (strips known secret-shaped strings like crypt passwords, API keys). Every command short-circuits to the JSON branch when `--json` is set. Existing tests for individual commands need a `--json` round-trip check.
+
+### Board comments
+
+- osb-triage-validator @ 2026-05-26T17:30Z: sanity clean; no cluster; priority set to 1: ergonomic-only, value depends on agent/operator usage of o2b CLI; most traffic via MCP.
+
+## Task t_93bd0cc1 - [upstream:iwe] Shell completions for o2b CLI
+
+**Source**: https://github.com/iwe-org/iwe/releases/tag/iwe-v0.1.4
+**Repo**: iwe-org/iwe (1086 stars)
+**Released**: iwe-v0.1.4 (2026-05-15T11:36:55Z)
+
+### What
+
+iwe added `iwe completions <SHELL>` subcommand that prints a shell-completion script to stdout for `bash`, `elvish`, `fish`, `nushell`, `powershell`, or `zsh`. Generated via clap's bundled completion generator (standard pattern in Rust CLIs).
+
+### Why useful for OSB
+
+The `o2b` CLI exposes long subcommand trees (`brain doctor`, `brain note`, `brain feedback`, `brain query`, `brain scan-inline`, `brain import-session`, `payment ...`) that humans occasionally invoke. Tab-completion would lower the friction of remembering subcommands and option flags during manual operator work. Low priority - most o2b traffic flows through MCP, not interactive shells.
+
+### Status in OSB
+
+- **Verdict**: not_in_osb_useful
+- **Codegraph hints**: no shell-completion subcommand exists. CLI verbs live under src/cli/.
+
+### Notes
+
+Whichever JS CLI framework `o2b` uses has a built-in completion generator. Simplest pattern: `o2b completions <bash|zsh|fish>` prints the script to stdout; user pipes to their shell's completions dir. Pure ergonomic add - no behavior change to existing commands.
+
+### Board comments
+
+- osb-triage-validator @ 2026-05-26T17:30Z: sanity clean; no cluster; priority set to 1: ergonomic-only, value depends on whether operators use o2b CLI manually; MCP-first usage means low impact.
+
+# Project context
+
+Project: Open Second Brain, TypeScript on Bun, package version 0.22.0. It is an Obsidian-native memory layer for AI agents. The core is deterministic and no-LLM; MCP is optional; CLI remains the supported baseline. Package dependencies are intentionally small: runtime dependency proper-lockfile, optional sqlite-vec, TypeScript/Bun tooling.
+
+Recent commits:
+
+- a085bfa (HEAD -> main, tag: v0.22.0, origin/main, origin/HEAD) feat: vault portability + session economy - codec, sources dashboard, vault-map tokens, multi-vault profiles, graph export/import (#49)
+- 73e4a28 (tag: v0.21.0) feat: brain lifecycle suite - mutation audit, multi-phase dream, reconcile domains, morning brief, temporal extraction, heal enrichment (#48)
+- bd49cd5 (tag: v0.20.0) feat: recall and ranking quality - Weibull recency, query intent, synonym expansion, recall budgets, query cache, pre-compress pack (#47)
+- cbbe18f (tag: v0.19.0) feat: typed graph semantics - typed relations, visibility scoping, MCP landscape (#46)
+- 5fa7eb0 (tag: v0.18.0) feat: MCP context economy - preview budget, artifact fetch, recall hint (#45)
+- 2bd3f48 (tag: v0.17.0) v0.17.0 - Brain Lifecycle Review Suite: intent review, retention, monthly synthesis, complexity warning (#44)
+- 9b87838 (tag: v0.16.0) v0.16.0 - Agent boundary control surfaces: pinned context, Markdown links, MCP output contracts (#43)
+- 66980b2 ci: drop bun version floor, track latest only (#42)
+- feca6a7 (tag: v0.15.0) v0.15.0 - Cross-agent query foundation: source-agent provenance retrieval and comparison (#41)
+- ffde4ac (tag: v0.14.1) chore(release): v0.14.1 (#40)
+- bc97b38 refactor: add validation toolchain and normalize project formatting (#39)
+- b76199a (tag: v0.14.0) v0.14.0 - Semantic Brain Health and Self-Maintenance: contradiction detection, concept gaps, stale claims, edit-history, remediation (#38)
+- 2147640 (tag: v0.13.0) v0.13.0 - Hybrid Search and Recall Quality: explainable recall, MMR, link traversal, entity boost, header anchoring (#37)
+- 84886d1 (tag: v0.12.0) v0.12.0 - Brain Integrity Suite: typed collision detection, content-hash drift, durable dream workruns (#36)
+- c002268 (tag: v0.11.0) v0.11.0 - Brain-centric vault layout: one agent-owned root, opt-in user notes (#35)
+- a8d4803 (tag: v0.10.18) v0.10.18 - temporal axis: timeline, belief evolution, stale watch, daily brief, weekly synthesis (#34)
+- d0598af (tag: v0.10.17) v0.10.17 - link graph surfaces (aliases, anchors, mentions, synthesis, MOC audit, property filter, vault instruction) (#33)
+- 3b7dfe9 (tag: v0.10.16) v0.10.16: trust and operator surfaces - verification, verdict, dashboard (#32)
+- d045ea1 (tag: v0.10.15) chore: bump version to 0.10.15 (#31)
+- 5755200 v0.10.15: vault care bundle - metadata, dedup, lint, context-pack, actions (#30)
+
+Related files:
+
+- src/mcp/tools.ts: ToolDefinition, ServerContext, ToolScope = "full" | "writer", WRITER_TOOL_NAMES, buildToolTable(scope), findTool(). Today filtering is static: full returns all, writer returns selected names.
+- src/mcp/server.ts: MCPServer constructor stores scope and tools = buildToolTable(this.scope). tools/list returns this static array. tools/call uses findTool(this.tools, name).
+- src/cli/argparse.ts: small dependency-free parser. parseFlags(argv, schema) rejects unknown flags, applies defaults, checks required fields. No global/inheritable flags.
+- src/cli/main.ts: root CLI dispatcher. Some root commands have hardcoded `json` flags, some do not. `mcp --probe` reports static tool count. `tool-call` always prints JSON. HELP is a static string.
+- src/cli/brain.ts and src/cli/brain/helpers.ts: brain verb dispatcher and parse wrapper used by brain verbs. This is a likely seam for adding shared flags to brain verbs without sweeping every implementation.
+- src/cli/search.ts, src/cli/vault/_, src/cli/pay-memory/_, src/cli/update.ts: existing scattered JSON branches.
+- src/cli/output.ts: existing okJson/writeJson/failWith helpers but no uniform JSON envelope/redactor module.
+- tests/helpers/run-cli.ts: subprocess helper for CLI tests.
+- tests/mcp/output-contract.test.ts and other tests/mcp/\*: existing MCPServer tests.
+- docs/mcp.md: documents optional MCP server and static writer split; full server currently advertises 46 tools.
+- docs/cli-reference.md: documents that JSON is available via `--json` on read verbs and most write verbs, not yet uniform.
+- README.md and CHANGELOG.md: release convention is capability-first, bundled features, deterministic defaults/no-op default behavior.
+
+Conventions:
+
+- Keep core deterministic and dependency-light; avoid new runtime dependencies unless strongly justified.
+- MCP server is optional; CLI remains the supported baseline.
+- Default install should remain no-op/byte-identical when a feature is not configured.
+- Secrets must be redacted in config/output surfaces; never print token or secret values.
+- CLI grammar is intentionally small and dependency-free; no commander/yargs unless the benefit is overwhelming.
+- Mutating Brain commands generally snapshot before writes and expose dry-run where meaningful.
+- Public docs use full project name, not abbreviations, in release artifacts.
+- Tests run with Bun; validation commands include `bun test`, `bun run typecheck`, `bun run lint`, `bun run sync-version:check`.
+
+Constraints:
+
+- Do not change existing public APIs unless backward-compatible.
+- Do not add a new CLI framework dependency just for completions.
+- Avoid hardcoding natural-language phrases for specific languages; keep language handling abstract.
+- Do not make dynamic MCP capability checks silently hide tools without a transparent diagnostic/probe path.
+- Respect the existing writer scope behavior; runtime capability filtering should layer on top of static scope, not replace it.
+- Keep shell completions generated from a registry or manifest so help/completions do not drift.
+- User requested version bump before GitHub push, overriding the universal playbook default that usually bumps during release.
+
+# Required output format
+
+Produce exactly 3 distinct architectural variants. For each variant:
+
+### Variant N: <short name>
+
+- **Approach**: 2-3 sentences describing the variant.
+- **Trade-offs**: bullet list of pros and cons.
+- **Complexity**: small | medium | large
+- **Risk**: low | medium | high
+
+After the three variants, add exactly one recommendation:
+
+### Recommended: Variant N
+
+**Rationale**: 2-3 sentences explaining why this variant over the others, considering the project context and constraints above.
+
+Output nothing outside of these sections.
diff --git a/docs/brainstorm/agent-capability-cli-integration/context.md b/docs/brainstorm/agent-capability-cli-integration/context.md
new file mode 100644
index 00000000..66f10c83
--- /dev/null
+++ b/docs/brainstorm/agent-capability-cli-integration/context.md
@@ -0,0 +1,24 @@
+# Context summary
+
+## Repository
+
+- Language/runtime: TypeScript on Bun.
+- Version at start: `0.22.0`.
+- Current branch at start: `main`, synced to `origin/main`.
+- Feature branch: `feat/agent-capability-cli-integration`.
+
+## Relevant surfaces
+
+- `src/mcp/tools.ts` owns `ToolDefinition`, `ServerContext`, static `ToolScope`, and `buildToolTable(scope)`.
+- `src/mcp/server.ts` builds a fixed tool list at construction and serves it through `tools/list` and `tools/call`.
+- `src/cli/argparse.ts` owns the dependency-free parser and rejects unknown flags per-command.
+- `src/cli/main.ts` dispatches root commands and contains existing `mcp --probe`, `tool-call`, and static help.
+- `src/cli/brain/helpers.ts` provides the parse facade used by brain verbs.
+- `src/cli/output.ts` already has `okJson`, `writeJson`, and `failWith`, but no uniform JSON envelope or redactor.
+
+## Constraints
+
+- MCP is optional; CLI remains supported baseline.
+- Default behavior should stay unchanged unless a user opts into a new flag or runtime constraint.
+- No new CLI framework dependency.
+- Runtime capability filtering must not silently hide tools without a diagnostic path.
diff --git a/docs/brainstorm/agent-capability-cli-integration/design.md b/docs/brainstorm/agent-capability-cli-integration/design.md
new file mode 100644
index 00000000..c2dc2211
--- /dev/null
+++ b/docs/brainstorm/agent-capability-cli-integration/design.md
@@ -0,0 +1,71 @@
+# Agent capability + CLI integration - runtime-aware tools and scriptable CLI
+
+**Status:** draft
+**Author:** GitHub Copilot (via feature-release-playbook)
+**Audience:** implementation
+
+## Problem statement
+
+Open Second Brain currently exposes MCP tools through a static `ToolScope` (`full` or `writer`) and has no runtime capability report that explains which tools are available under the current process constraints. The CLI has many useful JSON branches, but `--json` is not globally accepted and command discovery/completions do not come from a shared command manifest. Agents therefore need per-command parsing knowledge, and operators get no completion support for the long `o2b` command tree.
+
+## Scope
+
+- Add a runtime capability layer for MCP tools that evaluates after static `ToolScope`.
+- Expose capability diagnostics through an always-available MCP diagnostic tool and `o2b mcp --probe --json`.
+- Add a dependency-free CLI command manifest for root commands and major nested command groups.
+- Make `--json` an inherited CLI flag so unsupported commands can still return a structured fallback envelope instead of rejecting the flag.
+- Add `o2b help --json` and `o2b completions <shell>` backed by the same CLI manifest.
+- Support shell completion output for `bash`, `zsh`, `fish`, `elvish`, `nushell`, and `powershell` without a new CLI framework dependency.
+
+## Out of scope
+
+- Replacing the handwritten CLI parser with commander/yargs or another framework.
+- A single unified registry for both MCP tools and CLI commands.
+- Provider-specific LLM capability probing, token-cost accounting, or subagent orchestration.
+- Changing existing successful human-readable CLI output.
+- Moving selected Hermes tasks out of `triage` before release closure.
+
+## Chosen approach
+
+Use the consultant's Variant 3. The CLI gets one manifest that drives machine-readable discovery and completions, while MCP runtime capability checks remain a small independent layer over `buildToolTable(scope)`. Default behavior remains backward-compatible: without runtime constraints, the full/writer tool lists stay equivalent except for the new diagnostic tool, and existing commands with semantic JSON keep their existing JSON payloads.
+
+## Design decisions
+
+- Keep static scope as the first filter. Runtime checks never widen a static writer scope into full access.
+- Add an explicit capability report instead of silent filtering. The report includes advertised and withheld tools with reasons.
+- Keep the capability model deterministic and local. The first implementation supports explicit allow/deny constraints and resource-window limits from runtime options/CLI flags; no network calls or provider SDKs.
+- Prefer fallback JSON over a mass rewrite of every command renderer. Existing commands that already implement semantic `--json` keep that shape; commands without semantic JSON can return `{ ok, command, code, stdout, stderr }` from a global wrapper.
+- Redact secret-shaped fields in fallback envelopes using a shared helper before writing JSON.
+- Generate completions from the manifest, not from duplicated hand-written scripts.
+
+## File changes
+
+Expected new files:
+
+- `src/mcp/capabilities.ts`
+- `src/cli/command-manifest.ts`
+- `src/cli/completions.ts`
+- `src/cli/json-helpers.ts`
+- `tests/mcp/runtime-capabilities.test.ts`
+- `tests/cli/cli-json-contract.test.ts`
+- `tests/cli/completions.test.ts`
+
+Expected modified files:
+
+- `src/mcp/tools.ts`
+- `src/mcp/server.ts`
+- `src/cli/argparse.ts`
+- `src/cli/main.ts`
+- `src/cli/brain/helpers.ts`
+- `docs/mcp.md`
+- `docs/cli-reference.md`
+- `README.md`
+- `CHANGELOG.md`
+- version-bearing package/plugin files during the pre-push docs/version phase
+
+## Risks and open questions
+
+- Some existing tests may assert raw text for commands that will now accept `--json`; fallback JSON must be opt-in and must not change default output.
+- Wrapping stdout/stderr for fallback JSON needs careful implementation so commands with existing semantic JSON are not double-wrapped.
+- Completion scripts should be useful without pretending to model every dynamic positional argument perfectly.
+- Tool count docs must be updated after the diagnostic MCP tool is added.
diff --git a/docs/brainstorm/agent-capability-cli-integration/implementation-notes.md b/docs/brainstorm/agent-capability-cli-integration/implementation-notes.md
new file mode 100644
index 00000000..f33ca82d
--- /dev/null
+++ b/docs/brainstorm/agent-capability-cli-integration/implementation-notes.md
@@ -0,0 +1,7 @@
+# Implementation notes
+
+- Prefer small pure helpers for capability evaluation and completion generation.
+- Keep manifest metadata descriptive, not dispatch-owning.
+- Avoid a full command-registry refactor in this PR.
+- Existing semantic JSON branches should not be double-wrapped.
+- Fallback JSON should capture command stdout/stderr only when the command has no semantic JSON contract.
diff --git a/docs/brainstorm/agent-capability-cli-integration/notes.md b/docs/brainstorm/agent-capability-cli-integration/notes.md
new file mode 100644
index 00000000..29313d8c
--- /dev/null
+++ b/docs/brainstorm/agent-capability-cli-integration/notes.md
@@ -0,0 +1,13 @@
+# Agent capability + CLI integration - task notes
+
+Selected Hermes triage tasks:
+
+- `t_4acb2c72` - Agent runtime capability verification and constraint window (priority 3)
+- `t_01810c33` - Uniform `--json` flag across all `o2b` CLI commands (priority 1)
+- `t_93bd0cc1` - Shell completions for `o2b` CLI (priority 1)
+
+Operational notes:
+
+- Leave selected tasks in `triage` until the final release/tracker closure step.
+- User override: bump project version before GitHub push.
+- Self-review must compare all changes against `main`.
diff --git a/docs/brainstorm/agent-capability-cli-integration/phase-log.md b/docs/brainstorm/agent-capability-cli-integration/phase-log.md
new file mode 100644
index 00000000..949f21fa
--- /dev/null
+++ b/docs/brainstorm/agent-capability-cli-integration/phase-log.md
@@ -0,0 +1,10 @@
+# Phase log
+
+## Phase 0 - Brainstorm
+
+- Exported triage snapshot with `.ai-notes/export_triage_snapshot.py`: 18 tasks written to `.ai-notes/tasks.json`.
+- Operator selected scope A via `ask_report`.
+- Created branch `feat/agent-capability-cli-integration`.
+- Wrote consultant prompt and ran primary consultant `claude -p`.
+- Consultant returned 3 variants and recommended Variant 3.
+- Orchestrator chose Variant 3.
diff --git a/docs/brainstorm/agent-capability-cli-integration/plan.md b/docs/brainstorm/agent-capability-cli-integration/plan.md
new file mode 100644
index 00000000..3623212a
--- /dev/null
+++ b/docs/brainstorm/agent-capability-cli-integration/plan.md
@@ -0,0 +1,27 @@
+# Agent capability + CLI integration - implementation plan
+
+## Tasks
+
+### Task 1: Runtime MCP capability report
+
+- **Files**: `src/mcp/capabilities.ts`, `src/mcp/tools.ts`, `src/mcp/server.ts`, `src/cli/main.ts`, `tests/mcp/runtime-capabilities.test.ts`
+- **Acceptance**: focused MCP tests show static scope is still enforced, runtime deny/allow constraints withhold tools deterministically, `second_brain_capabilities` reports reasons, and `o2b mcp --probe --json` emits the same report shape.
+- **Depends on**: none
+
+### Task 2: Inherited CLI JSON contract
+
+- **Files**: `src/cli/argparse.ts`, `src/cli/json-helpers.ts`, `src/cli/main.ts`, `src/cli/brain/helpers.ts`, `tests/cli/cli-json-contract.test.ts`
+- **Acceptance**: focused CLI tests show a command without bespoke JSON accepts `--json` and returns a fallback envelope, an existing semantic JSON command keeps its legacy JSON shape, and secret-shaped values are redacted in fallback output.
+- **Depends on**: none
+
+### Task 3: Manifest-backed CLI discovery and completions
+
+- **Files**: `src/cli/command-manifest.ts`, `src/cli/completions.ts`, `src/cli/main.ts`, `docs/cli-reference.md`, `tests/cli/completions.test.ts`
+- **Acceptance**: focused CLI tests show `o2b help --json` lists root/nested commands and flags from the manifest, and `o2b completions bash|zsh|fish|elvish|nushell|powershell` emits non-empty scripts containing the `o2b` command tree.
+- **Depends on**: Task 2
+
+### Task 4: Documentation, version, and release prep
+
+- **Files**: `README.md`, `docs/mcp.md`, `docs/cli-reference.md`, `CHANGELOG.md`, `package.json`, synced version files if required by `sync-version`
+- **Acceptance**: docs describe the capability diagnostic, inherited JSON fallback, completions, and the version bump requested before push; `bun run sync-version:check` passes.
+- **Depends on**: Tasks 1-3
diff --git a/docs/brainstorm/agent-capability-cli-integration/pr-notes.md b/docs/brainstorm/agent-capability-cli-integration/pr-notes.md
new file mode 100644
index 00000000..5a043498
--- /dev/null
+++ b/docs/brainstorm/agent-capability-cli-integration/pr-notes.md
@@ -0,0 +1,11 @@
+# PR notes draft
+
+Capability-first summary:
+
+Open Second Brain gains a transparent runtime capability report for MCP tools and a more scriptable CLI surface: inherited JSON fallback, manifest-backed command discovery, and shell completions.
+
+Task IDs:
+
+- `t_4acb2c72`
+- `t_01810c33`
+- `t_93bd0cc1`
diff --git a/docs/brainstorm/agent-capability-cli-integration/scope.md b/docs/brainstorm/agent-capability-cli-integration/scope.md
new file mode 100644
index 00000000..b92c3255
--- /dev/null
+++ b/docs/brainstorm/agent-capability-cli-integration/scope.md
@@ -0,0 +1,17 @@
+# Scope boundary
+
+## In
+
+- Runtime MCP capability constraints and diagnostics.
+- `o2b mcp --probe --json` capability report.
+- `second_brain_capabilities` diagnostic MCP tool.
+- Inherited `--json` acceptance and fallback envelopes.
+- `o2b help --json` command manifest discovery.
+- `o2b completions <shell>` for common shells.
+
+## Out
+
+- Provider SDK checks.
+- Subagent orchestration.
+- Replacing CLI parser.
+- Moving Hermes triage tasks before release closure.
diff --git a/docs/brainstorm/agent-capability-cli-integration/task-body.md b/docs/brainstorm/agent-capability-cli-integration/task-body.md
new file mode 100644
index 00000000..2909378f
--- /dev/null
+++ b/docs/brainstorm/agent-capability-cli-integration/task-body.md
@@ -0,0 +1,7 @@
+# Selected task bodies
+
+The full exported triage snapshot is in `.ai-notes/tasks.json`. This file records the selected task IDs for the feature-release audit trail.
+
+- `t_4acb2c72` - `[upstream:core] Agent runtime capability verification and constraint window`
+- `t_01810c33` - `[upstream:mem0] Uniform --json flag across all o2b CLI commands for machine-readable output`
+- `t_93bd0cc1` - `[upstream:iwe] Shell completions for o2b CLI`
diff --git a/docs/brainstorm/agent-capability-cli-integration/test-matrix.md b/docs/brainstorm/agent-capability-cli-integration/test-matrix.md
new file mode 100644
index 00000000..2b42d22b
--- /dev/null
+++ b/docs/brainstorm/agent-capability-cli-integration/test-matrix.md
@@ -0,0 +1,22 @@
+# Test matrix
+
+## MCP capability layer
+
+- Full scope with no constraints advertises the default candidate set plus capability diagnostics.
+- Writer scope remains narrower than full scope.
+- Runtime deny hides a named tool and reports reason.
+- Runtime allow cannot widen writer scope.
+- Probe JSON returns report fields: `scope`, `available`, `withheld`, `tool_count`.
+
+## CLI JSON layer
+
+- Existing semantic JSON command keeps its existing shape.
+- Text-only command with `--json` returns fallback envelope.
+- CLI usage errors can be represented as JSON when `--json` is present.
+- Secret-shaped output is redacted in fallback JSON.
+
+## Completions
+
+- Supported shells: `bash`, `zsh`, `fish`, `elvish`, `nushell`, `powershell`.
+- Output includes root commands, `brain` verbs, and common flags.
+- Unsupported shell returns usage error.
diff --git a/docs/brainstorm/agent-capability-cli-integration/variants.md b/docs/brainstorm/agent-capability-cli-integration/variants.md
new file mode 100644
index 00000000..c94e0afc
--- /dev/null
+++ b/docs/brainstorm/agent-capability-cli-integration/variants.md
@@ -0,0 +1,37 @@
+# Agent capability + CLI integration - variants
+
+## Consultant output
+
+See `cli-output/claude.md` for the primary consultant output.
+
+## Parsed variants
+
+### Variant 1: Independent additive layers
+
+Implement the capability filter, inherited `--json`, and shell completions as three independent additions.
+
+- **Complexity**: medium
+- **Risk**: low
+- **Trade-off**: low blast radius, but completions and JSON discovery can drift because they duplicate command metadata.
+
+### Variant 2: Single declarative manifest spine
+
+Introduce one registry that drives MCP tool capability predicates, CLI flags, help JSON, and completions.
+
+- **Complexity**: large
+- **Risk**: high
+- **Trade-off**: best anti-drift property, but too much refactor and too much coupling for this scope.
+
+### Variant 3: Phased - shared CLI registry now, ADR-gated capability layer
+
+Use a CLI-only manifest for JSON discovery and completions, then add a separate transparent MCP capability filter layered on top of static scope.
+
+- **Complexity**: medium
+- **Risk**: low
+- **Trade-off**: two registries instead of one, but each owns a smaller and clearer boundary.
+
+## Orchestrator decision
+
+Chosen: **Variant 3**.
+
+The CLI tasks have a real shared abstraction: command/flag metadata. A manifest lets `help --json`, fallback JSON handling, and shell completions use the same source of truth without forcing the MCP tool registry through a broad refactor. The runtime capability check stays separate, additive, and transparent: it filters after static `ToolScope` and exposes a report through the MCP surface and probe path so tools are never hidden without a way to inspect why.
diff --git a/docs/brainstorm/agent-capability-cli-integration/verification.md b/docs/brainstorm/agent-capability-cli-integration/verification.md
new file mode 100644
index 00000000..a8c86bd1
--- /dev/null
+++ b/docs/brainstorm/agent-capability-cli-integration/verification.md
@@ -0,0 +1,15 @@
+# Verification plan
+
+Focused checks during implementation:
+
+- `bun test tests/mcp/runtime-capabilities.test.ts`
+- `bun test tests/cli/cli-json-contract.test.ts`
+- `bun test tests/cli/completions.test.ts`
+
+QA checks before pre-push gate:
+
+- `bun run typecheck`
+- `bun run lint`
+- `bun run test`
+- `bun run sync-version:check`
+- `code_checker`
diff --git a/docs/cli-reference.md b/docs/cli-reference.md
index 7f4de232..46f0061c 100644
--- a/docs/cli-reference.md
+++ b/docs/cli-reference.md
@@ -2,7 +2,7 @@
The full set of `o2b` verbs. After `o2b install-cli` they are on PATH; the local checkout can also be used without installing the symlinks by running commands through `scripts/o2b` and `scripts/vault-log`.
-Most verbs accept `--vault <path>` and `--config <path>`; the values default to the active profile from `o2b init`. JSON output is available via `--json` on every read verb.
+Most verbs accept `--vault <path>` and `--config <path>`; the values default to the active profile from `o2b init`. JSON output is available via `--json` on every read verb. Commands that do not own a semantic JSON contract return a redacted fallback envelope when `--json` is passed.
## Core
@@ -14,8 +14,10 @@ o2b install-cli Symlink o2b and o2b-hook into ~/.local/bin
o2b doctor Run vault + adapter checks
o2b index Rebuild the Markdown page index
o2b export-config Write a redacted config snapshot
-o2b mcp Run the MCP tool server (stdio)
+o2b mcp Run the MCP tool server (stdio); --scope full|writer, --probe, --allow-tool, --disable-tool, --max-tools
o2b tool-call Invoke an MCP tool handler from the CLI
+o2b help --json Print the command/flag manifest as JSON
+o2b completions --shell zsh Print completions for bash|zsh|fish|elvish|nushell|powershell
o2b uninstall Print uninstall plan; --apply-local cleans config; --remove-cli removes symlinks
o2b update Update Open Second Brain across all detected runtimes; --target <name> / --dry-run / --force / --json
```
@@ -150,16 +152,16 @@ layer config-tunable and bounded:
Recall and ranking quality (v0.20.0), each tunable and bounded:
-| Config key | Env var | Default | Effect |
-| ------------------------------ | ------------------------------------------------ | ------- | ----------------------------------------------------------------- |
-| `search_recency_shape` | `OPEN_SECOND_BRAIN_SEARCH_RECENCY_SHAPE` | `0.8` | Weibull recency curve shape (k) |
-| `search_recency_scale` | `OPEN_SECOND_BRAIN_SEARCH_RECENCY_SCALE` | `30` | Weibull characteristic lifetime in days |
-| `search_recency_amplitude` | `OPEN_SECOND_BRAIN_SEARCH_RECENCY_AMPLITUDE` | `0.05` | Max recency boost at age 0; `0` disables the recency layer |
-| `search_intent_enabled` | `OPEN_SECOND_BRAIN_SEARCH_INTENT_ENABLED` | `true` | Re-weight ranking by structural query intent; `false` is neutral |
-| `search_synonym_enabled` | `OPEN_SECOND_BRAIN_SEARCH_SYNONYM_ENABLED` | `false` | Opt-in co-occurrence query expansion (language-agnostic) |
-| `search_synonym_max_terms` | `OPEN_SECOND_BRAIN_SEARCH_SYNONYM_MAX_TERMS` | `3` | Cap on expansion terms OR'd onto the query |
-| `search_cache_enabled` | `OPEN_SECOND_BRAIN_SEARCH_CACHE_ENABLED` | `false` | Opt-in persistent query cache, gated by corpus generation |
-| `search_cache_ttl_seconds` | `OPEN_SECOND_BRAIN_SEARCH_CACHE_TTL` | `300` | Cache row time-to-live in seconds |
+| Config key | Env var | Default | Effect |
+| -------------------------- | -------------------------------------------- | ------- | ---------------------------------------------------------------- |
+| `search_recency_shape` | `OPEN_SECOND_BRAIN_SEARCH_RECENCY_SHAPE` | `0.8` | Weibull recency curve shape (k) |
+| `search_recency_scale` | `OPEN_SECOND_BRAIN_SEARCH_RECENCY_SCALE` | `30` | Weibull characteristic lifetime in days |
+| `search_recency_amplitude` | `OPEN_SECOND_BRAIN_SEARCH_RECENCY_AMPLITUDE` | `0.05` | Max recency boost at age 0; `0` disables the recency layer |
+| `search_intent_enabled` | `OPEN_SECOND_BRAIN_SEARCH_INTENT_ENABLED` | `true` | Re-weight ranking by structural query intent; `false` is neutral |
+| `search_synonym_enabled` | `OPEN_SECOND_BRAIN_SEARCH_SYNONYM_ENABLED` | `false` | Opt-in co-occurrence query expansion (language-agnostic) |
+| `search_synonym_max_terms` | `OPEN_SECOND_BRAIN_SEARCH_SYNONYM_MAX_TERMS` | `3` | Cap on expansion terms OR'd onto the query |
+| `search_cache_enabled` | `OPEN_SECOND_BRAIN_SEARCH_CACHE_ENABLED` | `false` | Opt-in persistent query cache, gated by corpus generation |
+| `search_cache_ttl_seconds` | `OPEN_SECOND_BRAIN_SEARCH_CACHE_TTL` | `300` | Cache row time-to-live in seconds |
`brain_context_pack` also accepts `max_chars_per_memory` and
`max_total_chars` (code-point caps), and the read-only
@@ -182,6 +184,7 @@ vault-log Shell mirror of brain_note (one-liner narrative mi
- Every CLI mutation that touches Brain takes a pre-run snapshot under `Brain/.snapshots/` with a SHA-256 sidecar manifest. `o2b brain rollback` aborts on drift unless `--force-rollback`.
- `o2b ... --json` exists on every read verb and most write verbs (the JSON payload mirrors the MCP tool's response shape).
+- Root-level `--json` is inherited by every command parser; existing semantic JSON commands keep their native payloads, while other commands emit a redacted fallback envelope.
- MCP-only `brain_pinned_context` manages `Brain/pinned.md`, a transient current-task scratchpad loaded by `brain_context`; it is intentionally not a learned preference CLI verb.
- `--dry-run` is supported by every mutating verb that touches more than a single file (`brain merge`, `brain rollback`, `brain upgrade`, `brain import-claude-memory`, `update`, ...).
- `--vault` always overrides the profile path; useful for multi-vault hosts where the config-resolved default is not the right target.
diff --git a/docs/mcp.md b/docs/mcp.md
index 9a4f85c6..f0610d5e 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -18,34 +18,36 @@ in Open Second Brain depends on the MCP server being running.
## Tool Highlights
-The full server currently advertises 46 tools. The table below highlights the
+The full server currently advertises 47 tools. The table below highlights the
operator-facing core, agent-source, health, and Pay Memory tools; the full
surface also includes Brain writer, review, query, temporal, link-graph, and
search tools. In Claude Code, that full schema can push MCP definitions beyond
10% of the context window, causing `MCPSearch` tool-search deferral; use the
-writer split below for the always-loaded writer subset.
-
-| Tool | Purpose | Required arguments |
-| -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------- |
-| `second_brain_status` | Report config and vault status, with secrets redacted. | β€” |
-| `second_brain_query` | List vault pages with an optional case-insensitive title substring. | β€” |
-| `vault_health` | Run vault, config, and plugin manifest health checks. | β€” |
-| `brain_health` | Run semantic Brain Health checks and return the health verdict/domains. | β€” |
-| `brain_mcp_landscape` | List the MCP servers configured across the vault: name, source config file, packages, and required env-var names. Env values never read. | β€” |
-| `brain_agent_query` | Read-only source-agent retrieval over Brain provenance. Filters by agents, topic, free-text query, contribution kind, and limit. | β€” |
-| `brain_agent_diff` | Read-only comparison between source agents using browse/search/diff/map modes over the same provenance foundation. | β€” |
-| `brain_audit` | Read-only per-preference mutation trail (create / promote / update / retire / merge) with agent, reason, revision + content-hash before/after. | `pref_id` |
-| `brain_morning_brief` | Read-only session-start summary: top confirmed preferences, recent reconcile open questions, recent notes; character-budgeted. | β€” |
-| `brain_sources` | Read-only dashboard of signals grouped by (agent, source_type) with active/processed and distinct-topic counts. | β€” |
-| `brain_switch_vault` | Activate a named vault profile; the change takes effect on the next server launch. | `name` |
-| `payment_memory_init` | Bootstrap `Brain/payments/{policies,assets,drafts,reports}/ (+ dated YYYY-MM-DD receipt subdirs)` and write the spending policy template. | β€” |
-| `payment_receipt_append` | Save a Markdown receipt for one paid API call. `raw_output` is redacted before persisting. | `service`, `status`, `reason` |
-| `asset_capture` | Save a Markdown note for an asset produced by a paid call, linked to its receipt. | `title`, `service`, `result_url` |
-| `payment_report_generate` | Aggregate a date's receipts into a Markdown report under `Brain/payments/reports/`. | `date` |
-| `payment_policy_check` | Evaluate a prospective paid call against `policies/spending.json` (allowed / approval_required / denied). | `service` |
-| `payment_request_approval` | Create a pending-payment-request the user must approve before the agent runs `pay`. | `service`, `reason` |
-| `payment_request_status` | Look up a pending request by id; agent uses this to poll for approval. | `id` |
-| `payment_request_consume` | Mark an `approved` request as `consumed` and link the resulting receipt. | `id`, `receipt` |
+writer split below for the always-loaded writer subset, or the runtime
+capability flags for a narrower per-process full server.
+
+| Tool | Purpose | Required arguments |
+| --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------- |
+| `second_brain_capabilities` | Report the tools available to this MCP process and the withheld-tool reasons after runtime capability filtering. | β€” |
+| `second_brain_status` | Report config and vault status, with secrets redacted. | β€” |
+| `second_brain_query` | List vault pages with an optional case-insensitive title substring. | β€” |
+| `vault_health` | Run vault, config, and plugin manifest health checks. | β€” |
+| `brain_health` | Run semantic Brain Health checks and return the health verdict/domains. | β€” |
+| `brain_mcp_landscape` | List the MCP servers configured across the vault: name, source config file, packages, and required env-var names. Env values never read. | β€” |
+| `brain_agent_query` | Read-only source-agent retrieval over Brain provenance. Filters by agents, topic, free-text query, contribution kind, and limit. | β€” |
+| `brain_agent_diff` | Read-only comparison between source agents using browse/search/diff/map modes over the same provenance foundation. | β€” |
+| `brain_audit` | Read-only per-preference mutation trail (create / promote / update / retire / merge) with agent, reason, revision + content-hash before/after. | `pref_id` |
+| `brain_morning_brief` | Read-only session-start summary: top confirmed preferences, recent reconcile open questions, recent notes; character-budgeted. | β€” |
+| `brain_sources` | Read-only dashboard of signals grouped by (agent, source_type) with active/processed and distinct-topic counts. | β€” |
+| `brain_switch_vault` | Activate a named vault profile; the change takes effect on the next server launch. | `name` |
+| `payment_memory_init` | Bootstrap `Brain/payments/{policies,assets,drafts,reports}/ (+ dated YYYY-MM-DD receipt subdirs)` and write the spending policy template. | β€” |
+| `payment_receipt_append` | Save a Markdown receipt for one paid API call. `raw_output` is redacted before persisting. | `service`, `status`, `reason` |
+| `asset_capture` | Save a Markdown note for an asset produced by a paid call, linked to its receipt. | `title`, `service`, `result_url` |
+| `payment_report_generate` | Aggregate a date's receipts into a Markdown report under `Brain/payments/reports/`. | `date` |
+| `payment_policy_check` | Evaluate a prospective paid call against `policies/spending.json` (allowed / approval_required / denied). | `service` |
+| `payment_request_approval` | Create a pending-payment-request the user must approve before the agent runs `pay`. | `service`, `reason` |
+| `payment_request_status` | Look up a pending request by id; agent uses this to poll for approval. | `id` |
+| `payment_request_consume` | Mark an `approved` request as `consumed` and link the resulting receipt. | `id`, `receipt` |
`second_brain_query` accepts `pattern` (string) and `limit` (1–500, default 50).
`vault_health` accepts `repo` (string) for plugin manifest validation.
@@ -138,10 +140,38 @@ Optional flags:
- `--config PATH` β€” override the Open Second Brain config file location.
- `--repo PATH` β€” repository root used for plugin manifest checks.
+- `--scope full|writer` β€” choose the full server or the always-loaded writer subset.
+- `--writer-only` β€” alias for `--scope writer`.
+- `--probe` β€” start an in-process handshake and print whether the server can advertise tools, then exit.
+- `--json` β€” with `--probe`, print a machine-readable capability report.
+- `--allow-tool NAME` β€” expose only named tools from the static scope. Repeatable.
+- `--disable-tool NAME` β€” withhold named tools from the static scope. Repeatable.
+- `--max-tools N` β€” expose only the first N non-diagnostic tools from the static scope.
The server logs its banner to `stderr` and only writes JSON-RPC frames to
`stdout`, so it is safe to use as a subprocess in any MCP client.
+## Runtime capability window
+
+Runtime capability flags are evaluated after the static scope. They can narrow
+the tool list a process advertises, but they cannot widen `--scope writer` into
+full-server tools. The full server always keeps `second_brain_capabilities`
+available so clients and operators can inspect which tools were available or
+withheld and why.
+
+Examples:
+
+```bash
+o2b mcp --vault /path/to/vault --probe --json --disable-tool second_brain_query
+o2b mcp --vault /path/to/vault --allow-tool brain_context --allow-tool brain_feedback
+o2b mcp --vault /path/to/vault --max-tools 12
+```
+
+`second_brain_capabilities` returns `scope`, `server_name`, static and available
+tool counts, an `available[]` list, and a `withheld[]` list. Withheld reasons
+are stable strings such as `disabled by runtime capability window`, `not allowed
+by runtime capability window`, and `outside runtime capability max tool window`.
+
## Hermes integration
Hermes discovers MCP servers from `~/.hermes/config.yaml` under the
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index e3f865b0..65683fbf 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -2,7 +2,7 @@
"id": "open-second-brain",
"name": "Open Second Brain",
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults.",
- "version": "0.22.0",
+ "version": "0.23.0",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/package.json b/package.json
index 91600f50..ad20c2cd 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.22.0",
+ "version": "0.23.0",
"private": false,
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.",
"keywords": [
diff --git a/plugin.yaml b/plugin.yaml
index 88c9fbf8..beb7b181 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.22.0"
+version: "0.23.0"
description: "Hermes plugin entrypoint for OpenSecondBrain vault health checks and the optional MCP tool server."
author: "OpenSecondBrain contributors"
kind: standalone
diff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.json
index 17800ca5..49cc02aa 100644
--- a/plugins/codex/.codex-plugin/plugin.json
+++ b/plugins/codex/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "0.22.0",
+ "version": "0.23.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"author": {
"name": "Open Second Brain contributors",
diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yaml
index 734fb296..46d475f0 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "0.22.0"
+version: "0.23.0"
description: "Hermes adapter for OpenSecondBrain vault health checks and optional MCP tool server."
author: "OpenSecondBrain contributors"
kind: standalone
diff --git a/pyproject.toml b/pyproject.toml
index 0b68ed28..c4ead1e8 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -10,7 +10,7 @@ build-backend = "setuptools.build_meta"
# CLI entry points (those moved to `package.json` `bin`).
[project]
name = "open-second-brain"
-version = "0.22.0"
+version = "0.23.0"
description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."
readme = "README.md"
requires-python = ">=3.11"
diff --git a/src/cli/argparse.ts b/src/cli/argparse.ts
index cc7da744..73affffb 100644
--- a/src/cli/argparse.ts
+++ b/src/cli/argparse.ts
@@ -35,7 +35,14 @@ export interface ParsedArgs {
* Parse argv-tail for one subcommand. `argv` should be everything AFTER the
* subcommand name. Unknown flags raise `CliError`.
*/
-export function parseFlags(argv: ReadonlyArray<string>, schema: FlagsSchema): ParsedArgs {
+export function parseFlags(
+ argv: ReadonlyArray<string>,
+ schema: FlagsSchema,
+): ParsedArgs {
+ const effectiveSchema: FlagsSchema =
+ schema["json"] !== undefined
+ ? schema
+ : { ...schema, json: { type: "boolean" } };
const flags: Record<string, string | boolean | string[] | undefined> = {};
const positional: string[] = [];
@@ -49,7 +56,7 @@ export function parseFlags(argv: ReadonlyArray<string>, schema: FlagsSchema): Pa
const eqIdx = tok.indexOf("=");
const name = eqIdx === -1 ? tok.slice(2) : tok.slice(2, eqIdx);
const inlineVal = eqIdx === -1 ? null : tok.slice(eqIdx + 1);
- const spec = schema[name];
+ const spec = effectiveSchema[name];
if (!spec) {
throw new CliError(`unknown flag: --${name}`);
}
@@ -65,7 +72,8 @@ export function parseFlags(argv: ReadonlyArray<string>, schema: FlagsSchema): Pa
value = inlineVal;
} else {
const next = argv[++i];
- if (next === undefined) throw new CliError(`flag --${name} requires a value`);
+ if (next === undefined)
+ throw new CliError(`flag --${name} requires a value`);
value = next;
}
if (spec.type === "string") {
@@ -81,7 +89,7 @@ export function parseFlags(argv: ReadonlyArray<string>, schema: FlagsSchema): Pa
}
// Apply defaults and check required flags.
- for (const [name, spec] of Object.entries(schema)) {
+ for (const [name, spec] of Object.entries(effectiveSchema)) {
if (flags[name] === undefined) {
if (spec.type === "string" && spec.default !== undefined) {
flags[name] = spec.default;
diff --git a/src/cli/command-manifest.ts b/src/cli/command-manifest.ts
new file mode 100644
index 00000000..8bdeba05
--- /dev/null
+++ b/src/cli/command-manifest.ts
@@ -0,0 +1,256 @@
+export interface CliFlagManifest {
+ readonly name: string;
+ readonly type: "boolean" | "string" | "string-array";
+ readonly inherited?: boolean;
+}
+
+export interface CliCommandManifest {
+ readonly name: string;
+ readonly summary: string;
+ readonly flags?: ReadonlyArray<CliFlagManifest>;
+ readonly commands?: ReadonlyArray<CliCommandManifest>;
+}
+
+export interface CliRootManifest {
+ readonly command: "o2b";
+ readonly flags: ReadonlyArray<CliFlagManifest>;
+ readonly commands: ReadonlyArray<CliCommandManifest>;
+}
+
+export const INHERITED_JSON_FLAG: CliFlagManifest = Object.freeze({
+ name: "json",
+ type: "boolean",
+ inherited: true,
+});
+
+export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({
+ command: "o2b",
+ flags: [INHERITED_JSON_FLAG],
+ commands: [
+ command("status", "Show Open Second Brain configuration status", [
+ flag("config", "string"),
+ flag("vault", "string"),
+ ]),
+ command("init", "Initialize a vault profile", [
+ flag("vault", "string"),
+ flag("name", "string"),
+ flag("agent-name", "string"),
+ flag("timezone", "string"),
+ flag("force", "boolean"),
+ flag("interactive", "boolean"),
+ ]),
+ command("doctor", "Run health checks on vault, config, and plugins", [
+ flag("vault", "string"),
+ flag("config", "string"),
+ flag("repo", "string"),
+ ]),
+ command("export-config", "Write a redacted config snapshot", [
+ flag("config", "string"),
+ flag("output", "string"),
+ ]),
+ command("index", "Regenerate the vault index from discovered pages", [
+ flag("vault", "string"),
+ ]),
+ command("mcp", "Run the optional MCP tool server", [
+ flag("vault", "string"),
+ flag("config", "string"),
+ flag("repo", "string"),
+ flag("scope", "string"),
+ flag("writer-only", "boolean"),
+ flag("probe", "boolean"),
+ flag("allow-tool", "string-array"),
+ flag("disable-tool", "string-array"),
+ flag("max-tools", "string"),
+ ]),
+ command("help", "Print command help or the command manifest"),
+ command("completions", "Print shell completion script for o2b", [
+ flag("shell", "string"),
+ ]),
+ command("install-cli", "Create symlinks for o2b and vault-log"),
+ command("install", "Multi-runtime install orchestrator"),
+ command("update", "Update Open Second Brain across detected runtimes", [
+ flag("target", "string"),
+ flag("dry-run", "boolean"),
+ flag("force", "boolean"),
+ ]),
+ command("uninstall", "Print or apply an uninstall plan", [
+ flag("config", "string"),
+ flag("apply-local", "boolean"),
+ flag("remove-cli", "boolean"),
+ flag("target", "string"),
+ ]),
+ command("tool-call", "Invoke an MCP tool handler from the CLI", [
+ flag("vault", "string"),
+ flag("tool-arg", "string-array"),
+ ]),
+ command(
+ "brain",
+ "Brain memory verbs",
+ [],
+ [
+ command("init", "Bootstrap Brain skeleton"),
+ command("feedback", "Record a taste signal"),
+ command("dream", "Run deterministic consolidation"),
+ command("apply-evidence", "Record preference evidence"),
+ command("note", "Append a narrative milestone"),
+ command("digest", "Render recent Brain transitions"),
+ command("intent-review", "Review signal clusters before dream"),
+ command("retention", "Review retired preference retention"),
+ command("monthly", "Render month-level Brain synthesis"),
+ command("query", "Read preferences, topics, and logs"),
+ command("agent-query", "Read source-agent provenance"),
+ command("agent-diff", "Compare source-agent coverage"),
+ command("reject", "Retire a preference"),
+ command("merge", "Merge duplicate preferences"),
+ command("pin", "Pin a preference"),
+ command("unpin", "Unpin a preference"),
+ command("set-primary", "Set primary Brain agent"),
+ command("protect", "Emit runtime deny rules for Brain"),
+ command("unprotect", "Remove managed runtime deny rules"),
+ command("snapshot", "Inspect Brain snapshots"),
+ command("rollback", "Restore Brain from a snapshot"),
+ command("upgrade", "Migrate release-owned Brain files"),
+ command("export", "Export active preferences"),
+ command("explorer", "Open or export Brain graph explorer"),
+ command("doctor", "Check Brain invariants"),
+ command("health", "Render semantic Brain health"),
+ command("history", "Render preference edit history"),
+ command("audit", "Render mutation audit trail"),
+ command("morning-brief", "Render session-start summary"),
+ command("codec", "Compress or expand session prose"),
+ command("sources", "Show signal source dashboard"),
+ command("graph-export", "Export vault graph"),
+ command("graph-import", "Import vault graph stubs"),
+ command("backlinks", "List inbound Brain references"),
+ command(
+ "mcp-landscape",
+ "List MCP servers configured across the vault",
+ ),
+ command("scan-inline", "Capture inline @osb markers"),
+ command("import-session", "Replay registered agent sessions"),
+ command("import-claude-memory", "Import Claude memory feedback"),
+ ],
+ ),
+ command(
+ "search",
+ "Search the vault index",
+ [],
+ [
+ command("query", "Search the vault index"),
+ command("index", "Incrementally update the search index"),
+ command("reindex", "Rebuild the search index"),
+ command("status", "Print search index status"),
+ command("check", "Run search pre-flight diagnostics"),
+ ],
+ ),
+ command(
+ "vault",
+ "Vault scope and profile verbs",
+ [],
+ [
+ command("status", "Show vault policy walk summary"),
+ command("inspect", "Inspect one vault-relative path"),
+ command("profile", "Manage named vault profiles"),
+ command("map", "Print vault-map role tokens"),
+ ],
+ ),
+ command(
+ "discipline",
+ "Daily logging discipline verbs",
+ [],
+ [
+ command("report", "Render discipline report"),
+ command("install", "Install discipline cron"),
+ command("uninstall", "Remove discipline cron"),
+ ],
+ ),
+ command("init-pay-memory", "Bootstrap Pay Memory folders"),
+ command("append-payment-receipt", "Save a payment receipt"),
+ command("capture-asset", "Save an asset note"),
+ command("payment-report", "Aggregate payment receipts"),
+ command("check-payment-policy", "Evaluate paid-call policy"),
+ command("request-payment-approval", "Create payment approval request"),
+ command("approve-payment-request", "Approve payment request"),
+ command("reject-payment-request", "Reject payment request"),
+ command("consume-payment-request", "Consume approved payment request"),
+ command("list-pending-payments", "List payment requests"),
+ command("payment-digest", "Render payment digest"),
+ ],
+});
+
+export function manifestForJson(): CliRootManifest {
+ return addInheritedFlags(CLI_COMMAND_MANIFEST);
+}
+
+export function commandNames(
+ manifest: CliRootManifest = CLI_COMMAND_MANIFEST,
+): string[] {
+ return manifest.commands.map((item) => item.name);
+}
+
+export function nestedCommandNames(parent: string): string[] {
+ const node = CLI_COMMAND_MANIFEST.commands.find(
+ (item) => item.name === parent,
+ );
+ return node?.commands?.map((item) => item.name) ?? [];
+}
+
+export function allFlagNames(
+ manifest: CliRootManifest = manifestForJson(),
+): string[] {
+ const names = new Set<string>();
+ for (const flagSpec of manifest.flags) names.add(flagSpec.name);
+ const visit = (items: ReadonlyArray<CliCommandManifest>): void => {
+ for (const item of items) {
+ for (const flagSpec of item.flags ?? []) names.add(flagSpec.name);
+ if (item.commands) visit(item.commands);
+ }
+ };
+ visit(manifest.commands);
+ return [...names].toSorted();
+}
+
+function command(
+ name: string,
+ summary: string,
+ flags: ReadonlyArray<CliFlagManifest> = [],
+ commands: ReadonlyArray<CliCommandManifest> = [],
+): CliCommandManifest {
+ return Object.freeze({
+ name,
+ summary,
+ ...(flags.length > 0 ? { flags } : {}),
+ ...(commands.length > 0 ? { commands } : {}),
+ });
+}
+
+function flag(name: string, type: CliFlagManifest["type"]): CliFlagManifest {
+ return Object.freeze({ name, type });
+}
+
+function addInheritedFlags(root: CliRootManifest): CliRootManifest {
+ return {
+ ...root,
+ commands: root.commands.map((item) => addInheritedFlagsToCommand(item)),
+ };
+}
+
+function addInheritedFlagsToCommand(
+ commandSpec: CliCommandManifest,
+): CliCommandManifest {
+ const ownFlags = commandSpec.flags ?? [];
+ const hasJson = ownFlags.some(
+ (item) => item.name === INHERITED_JSON_FLAG.name,
+ );
+ return {
+ ...commandSpec,
+ flags: hasJson ? ownFlags : [...ownFlags, INHERITED_JSON_FLAG],
+ ...(commandSpec.commands
+ ? {
+ commands: commandSpec.commands.map((item) =>
+ addInheritedFlagsToCommand(item),
+ ),
+ }
+ : {}),
+ };
+}
diff --git a/src/cli/completions.ts b/src/cli/completions.ts
new file mode 100644
index 00000000..84018557
--- /dev/null
+++ b/src/cli/completions.ts
@@ -0,0 +1,96 @@
+import {
+ allFlagNames,
+ commandNames,
+ nestedCommandNames,
+ type CliRootManifest,
+} from "./command-manifest.ts";
+
+export const COMPLETION_SHELLS = [
+ "bash",
+ "zsh",
+ "fish",
+ "elvish",
+ "nushell",
+ "powershell",
+] as const;
+
+export type CompletionShell = (typeof COMPLETION_SHELLS)[number];
+
+export function isCompletionShell(value: string): value is CompletionShell {
+ return (COMPLETION_SHELLS as ReadonlyArray<string>).includes(value);
+}
+
+export function renderCompletions(
+ shell: CompletionShell,
+ manifest: CliRootManifest,
+): string {
+ const roots = commandNames(manifest);
+ const brain = nestedCommandNames("brain");
+ const search = nestedCommandNames("search");
+ const vault = nestedCommandNames("vault");
+ const flags = allFlagNames(manifest).map((flag) => `--${flag}`);
+ const words = [...roots, ...flags];
+ const header = `# o2b completions for ${shell}\n# commands: ${roots.join(" ")}\n# flags: ${flags.join(" ")}\n`;
+ switch (shell) {
+ case "bash":
+ return `${header}
+_o2b_completions() {
+ local cur prev
+ COMPREPLY=()
+ cur="\${COMP_WORDS[COMP_CWORD]}"
+ prev="\${COMP_WORDS[COMP_CWORD-1]}"
+ if [[ "$prev" == "brain" ]]; then
+ COMPREPLY=( $(compgen -W "${brain.join(" ")}" -- "$cur") )
+ return 0
+ fi
+ COMPREPLY=( $(compgen -W "${words.join(" ")}" -- "$cur") )
+}
+complete -F _o2b_completions o2b
+`;
+ case "zsh":
+ return `${header}
+#compdef o2b
+_arguments \\
+ '1:command:(${roots.join(" ")})' \\
+ '2:subcommand:(${[...brain, ...search, ...vault].join(" ")})' \\
+ '*:flags:(${flags.join(" ")})'
+`;
+ case "fish":
+ return `${header}${roots.map((root) => `complete -c o2b -f -a ${quoteFish(root)}`).join("\n")}
+${brain.map((verb) => `complete -c o2b -n '__fish_seen_subcommand_from brain' -f -a ${quoteFish(verb)}`).join("\n")}
+${flags.map((flag) => `complete -c o2b -l ${flag.slice(2)}`).join("\n")}
+`;
+ case "elvish":
+ return `${header}
+set edit:completion:arg-completer[o2b] = {|@words|
+ put ${words.map((word) => quoteElvish(word)).join(" ")}
+}
+`;
+ case "nushell":
+ return `${header}
+def "nu-complete o2b" [] { [${words.map((word) => quoteNu(word)).join(" ")}] }
+export extern "o2b" [command?: string@"nu-complete o2b", ...rest]
+`;
+ case "powershell":
+ return `${header}
+Register-ArgumentCompleter -Native -CommandName o2b -ScriptBlock {
+ param($wordToComplete)
+ ${JSON.stringify(words)} | Where-Object { $_ -like "$wordToComplete*" } | ForEach-Object {
+ [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)
+ }
+}
+`;
+ }
+}
+
+function quoteFish(value: string): string {
+ return `'${value.replace(/'/g, "\\'")}'`;
+}
+
+function quoteElvish(value: string): string {
+ return `"${value.replace(/"/g, '\\"')}"`;
+}
+
+function quoteNu(value: string): string {
+ return `"${value.replace(/"/g, '\\"')}"`;
+}
diff --git a/src/cli/json-helpers.ts b/src/cli/json-helpers.ts
new file mode 100644
index 00000000..9fcb6c3f
--- /dev/null
+++ b/src/cli/json-helpers.ts
@@ -0,0 +1,90 @@
+const SECRET_KEY_RE =
+ /(?:api[_-]?key|token|secret|password|crypt[_-]?password)/i;
+const SECRET_ASSIGNMENT_RE =
+ /((?:api[_-]?key|token|secret|password|crypt[_-]?password)\s*[=:]\s*)(?:"[^"]*"|'[^']*'|[^\s]+)/gi;
+
+export function wantsJsonFlag(argv: ReadonlyArray<string>): boolean {
+ return argv.some((arg) => arg === "--json" || arg.startsWith("--json="));
+}
+
+export function redactSecrets(value: unknown): unknown {
+ if (typeof value === "string") return redactSecretString(value);
+ if (Array.isArray(value)) return value.map((item) => redactSecrets(item));
+ if (value !== null && typeof value === "object") {
+ const entries = Object.entries(value as Record<string, unknown>).map(
+ ([key, raw]) => [
+ key,
+ SECRET_KEY_RE.test(key) ? "[REDACTED]" : redactSecrets(raw),
+ ],
+ );
+ return Object.fromEntries(entries);
+ }
+ return value;
+}
+
+export async function withJsonFallback(
+ command: string,
+ run: () => Promise<number>,
+): Promise<number> {
+ let stdout = "";
+ let stderr = "";
+ const stdoutWrite = process.stdout.write;
+ const stderrWrite = process.stderr.write;
+
+ process.stdout.write = ((
+ chunk: unknown,
+ encodingOrCallback?: unknown,
+ callback?: unknown,
+ ) => {
+ stdout += stringifyChunk(chunk);
+ invokeWriteCallback(encodingOrCallback, callback);
+ return true;
+ }) as typeof process.stdout.write;
+ process.stderr.write = ((
+ chunk: unknown,
+ encodingOrCallback?: unknown,
+ callback?: unknown,
+ ) => {
+ stderr += stringifyChunk(chunk);
+ invokeWriteCallback(encodingOrCallback, callback);
+ return true;
+ }) as typeof process.stderr.write;
+
+ let code: number;
+ try {
+ code = await run();
+ } finally {
+ process.stdout.write = stdoutWrite;
+ process.stderr.write = stderrWrite;
+ }
+
+ process.stdout.write(
+ JSON.stringify(
+ redactSecrets({ ok: code === 0, command, code, stdout, stderr }),
+ null,
+ 2,
+ ) + "\n",
+ );
+ return code;
+}
+
+function redactSecretString(value: string): string {
+ return value.replace(SECRET_ASSIGNMENT_RE, "$1[REDACTED]");
+}
+
+function stringifyChunk(chunk: unknown): string {
+ if (typeof chunk === "string") return chunk;
+ if (chunk instanceof Uint8Array) return Buffer.from(chunk).toString("utf8");
+ return String(chunk);
+}
+
+function invokeWriteCallback(
+ encodingOrCallback: unknown,
+ callback: unknown,
+): void {
+ if (typeof encodingOrCallback === "function") {
+ encodingOrCallback();
+ } else if (typeof callback === "function") {
+ callback();
+ }
+}
diff --git a/src/cli/main.ts b/src/cli/main.ts
index 22791752..9cad7dbc 100644
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -32,6 +32,7 @@ import {
resolveSemanticConfigState,
sortedReplacer,
} from "./helpers.ts";
+import { wantsJsonFlag, withJsonFallback } from "./json-helpers.ts";
import {
cmdInitPayMemory,
cmdAppendPaymentReceipt,
@@ -56,10 +57,20 @@ import { planUninstall, renderPlan } from "./uninstall.ts";
import { cmdInstall } from "./install/install.ts";
import { cmdUninstallTarget } from "./install/uninstall-target.ts";
import { cmdInitInteractive } from "./install/init-interactive.ts";
+import { CLI_COMMAND_MANIFEST, manifestForJson } from "./command-manifest.ts";
+import {
+ COMPLETION_SHELLS,
+ isCompletionShell,
+ renderCompletions,
+} from "./completions.ts";
import { MCPServer } from "../mcp/server.ts";
import { serveStdio } from "../mcp/stdio.ts";
import { SERVER_VERSION } from "../mcp/protocol.ts";
import { buildToolTable } from "../mcp/tools.ts";
+import {
+ evaluateToolCapabilities,
+ type RuntimeCapabilityWindow,
+} from "../mcp/capabilities.ts";
// ── Subcommands ─────────────────────────────────────────────────────────────
@@ -89,7 +100,9 @@ async function cmdStatus(argv: string[]): Promise<number> {
process.stdout.write(JSON.stringify(output, sortedReplacer, 2) + "\n");
} else {
process.stdout.write(`config_path: ${result.path}\n`);
- process.stdout.write(`config_exists: ${result.exists ? "true" : "false"}\n`);
+ process.stdout.write(
+ `config_exists: ${result.exists ? "true" : "false"}\n`,
+ );
if (Object.keys(result.data).length > 0) {
process.stdout.write("config_keys:\n");
for (const key of Object.keys(result.data).toSorted()) {
@@ -175,7 +188,9 @@ async function cmdInit(argv: string[]): Promise<number> {
*/
function writeSearchInitBlock(configPath: string): void {
process.stdout.write("\nSearch:\n");
- process.stdout.write(" next: o2b search index # build the vault search index\n");
+ process.stdout.write(
+ " next: o2b search index # build the vault search index\n",
+ );
const data = discoverConfig(configPath).data;
// v0.10.10 β€” share the truthy / key-present logic with `o2b status`
@@ -186,7 +201,11 @@ function writeSearchInitBlock(configPath: string): void {
// Skip the embedding-key prompt when search is explicitly disabled
// (no point onboarding semantic when the whole layer is off), the
// semantic flag is off, or the key is already present.
- if (semantic.search_disabled || !semantic.semantic_enabled || semantic.embedding_key_present) {
+ if (
+ semantic.search_disabled ||
+ !semantic.semantic_enabled ||
+ semantic.embedding_key_present
+ ) {
return;
}
@@ -233,7 +252,9 @@ async function cmdDoctor(argv: string[]): Promise<number> {
repoRoot: (flags["repo"] as string | undefined) ?? null,
});
} catch (exc) {
- process.stderr.write(`error: doctor failed: ${(exc as Error).message ?? exc}\n`);
+ process.stderr.write(
+ `error: doctor failed: ${(exc as Error).message ?? exc}\n`,
+ );
return 1;
}
let allOk = true;
@@ -258,9 +279,15 @@ async function cmdExportConfig(argv: string[]): Promise<number> {
const output = String(flags["output"]);
try {
mkdirSync(resolve(output, ".."), { recursive: true });
- writeFileSync(output, JSON.stringify(snapshot, sortedReplacer, 2) + "\n", "utf8");
+ writeFileSync(
+ output,
+ JSON.stringify(snapshot, sortedReplacer, 2) + "\n",
+ "utf8",
+ );
} catch (exc) {
- process.stderr.write(`error: failed to export config: ${(exc as Error).message ?? exc}\n`);
+ process.stderr.write(
+ `error: failed to export config: ${(exc as Error).message ?? exc}\n`,
+ );
return 1;
}
process.stdout.write(`exported: ${output}\n`);
@@ -269,12 +296,17 @@ async function cmdExportConfig(argv: string[]): Promise<number> {
async function cmdIndex(argv: string[]): Promise<number> {
const { flags } = parseFlags(argv, { vault: { type: "string" } });
- const vault = requireVault(flags["vault"] as string | undefined, defaultConfigPath());
+ const vault = requireVault(
+ flags["vault"] as string | undefined,
+ defaultConfigPath(),
+ );
let pages;
try {
pages = listVaultPages(vault);
} catch (exc) {
- process.stderr.write(`error: failed to list vault pages: ${(exc as Error).message ?? exc}\n`);
+ process.stderr.write(
+ `error: failed to list vault pages: ${(exc as Error).message ?? exc}\n`,
+ );
return 1;
}
if (pages.length === 0) {
@@ -288,17 +320,27 @@ async function cmdIndex(argv: string[]): Promise<number> {
"",
];
for (const p of pages) {
- const rel = p.path.startsWith(vault) ? p.path.slice(vault.length).replace(/^\/+/, "") : p.path;
+ const rel = p.path.startsWith(vault)
+ ? p.path.slice(vault.length).replace(/^\/+/, "")
+ : p.path;
lines.push(`- [[${p.title}]] \`${rel}\``);
}
const indexPath = resolve(vault, BRAIN_INDEX_REL);
try {
- writeFrontmatter(indexPath, { title: "Index", type: "index" }, lines.join("\n"));
+ writeFrontmatter(
+ indexPath,
+ { title: "Index", type: "index" },
+ lines.join("\n"),
+ );
} catch (exc) {
- process.stderr.write(`error: failed to write index: ${(exc as Error).message ?? exc}\n`);
+ process.stderr.write(
+ `error: failed to write index: ${(exc as Error).message ?? exc}\n`,
+ );
return 1;
}
- process.stdout.write(`index regenerated: ${indexPath} (${pages.length} pages)\n`);
+ process.stdout.write(
+ `index regenerated: ${indexPath} (${pages.length} pages)\n`,
+ );
return 0;
}
@@ -310,6 +352,10 @@ async function cmdMcp(argv: string[]): Promise<number> {
scope: { type: "string" },
"writer-only": { type: "boolean" },
probe: { type: "boolean" },
+ json: { type: "boolean" },
+ "allow-tool": { type: "string-array" },
+ "disable-tool": { type: "string-array" },
+ "max-tools": { type: "string" },
});
// `--writer-only` is an alias for `--scope writer`. The two flags
@@ -318,7 +364,8 @@ async function cmdMcp(argv: string[]): Promise<number> {
// contradictory pair (e.g. `--scope full --writer-only`) is
// rejected to avoid silent surprises.
const writerOnly = Boolean(flags["writer-only"]);
- const rawScope = (flags["scope"] as string | undefined) ?? (writerOnly ? "writer" : "full");
+ const rawScope =
+ (flags["scope"] as string | undefined) ?? (writerOnly ? "writer" : "full");
if (rawScope !== "full" && rawScope !== "writer") {
process.stderr.write(
`o2b mcp: invalid --scope value: ${rawScope}; expected one of: full, writer\n`,
@@ -326,11 +373,15 @@ async function cmdMcp(argv: string[]): Promise<number> {
return 2;
}
if (writerOnly && rawScope !== "writer") {
- process.stderr.write(`o2b mcp: --writer-only conflicts with --scope ${rawScope}\n`);
+ process.stderr.write(
+ `o2b mcp: --writer-only conflicts with --scope ${rawScope}\n`,
+ );
return 2;
}
const scope = rawScope;
- const serverName = scope === "writer" ? "open-second-brain-writer" : "open-second-brain";
+ const serverName =
+ scope === "writer" ? "open-second-brain-writer" : "open-second-brain";
+ const capabilityWindow = parseCapabilityWindow(flags);
const config = (flags["config"] as string | undefined) ?? defaultConfigPath();
@@ -340,6 +391,8 @@ async function cmdMcp(argv: string[]): Promise<number> {
config,
scope,
serverName,
+ json: Boolean(flags["json"]),
+ capabilityWindow,
});
}
@@ -349,7 +402,34 @@ async function cmdMcp(argv: string[]): Promise<number> {
process.stderr.write(
`[mcp] ${serverName} ${SERVER_VERSION} listening on stdio (vault=${vault})\n`,
);
- return await serveStdio({ vault, configPath: config, repoRoot }, {}, { scope, serverName });
+ return await serveStdio(
+ { vault, configPath: config, repoRoot },
+ {},
+ { scope, serverName, capabilityWindow },
+ );
+}
+
+function parseCapabilityWindow(
+ flags: Record<string, string | boolean | string[] | undefined>,
+): RuntimeCapabilityWindow | undefined {
+ const allowedTools = flags["allow-tool"] as string[] | undefined;
+ const disabledTools = flags["disable-tool"] as string[] | undefined;
+ const rawMaxTools = flags["max-tools"] as string | undefined;
+ let maxTools: number | undefined;
+ if (rawMaxTools !== undefined) {
+ const parsed = Number(rawMaxTools);
+ if (!Number.isInteger(parsed) || parsed < 1) {
+ throw new CliError("--max-tools must be a positive integer");
+ }
+ maxTools = parsed;
+ }
+ if (!allowedTools && !disabledTools && maxTools === undefined)
+ return undefined;
+ return {
+ ...(allowedTools ? { allowedTools } : {}),
+ ...(disabledTools ? { disabledTools } : {}),
+ ...(maxTools !== undefined ? { maxTools } : {}),
+ };
}
async function runMcpProbe(args: {
@@ -357,6 +437,8 @@ async function runMcpProbe(args: {
config: string;
scope: "full" | "writer";
serverName: string;
+ json: boolean;
+ capabilityWindow: RuntimeCapabilityWindow | undefined;
}): Promise<number> {
// The probe is an in-process MCP handshake: it counts the tools the
// server would advertise and exits. Used by `o2b install --check`
@@ -365,11 +447,33 @@ async function runMcpProbe(args: {
try {
vault = requireVault(args.vault, args.config);
} catch (e) {
- process.stdout.write(`mcp probe FAIL: vault not configured (${(e as Error).message})\n`);
+ process.stdout.write(
+ `mcp probe FAIL: vault not configured (${(e as Error).message})\n`,
+ );
return 1;
}
try {
- const tools = buildToolTable(args.scope);
+ const evaluated = evaluateToolCapabilities(buildToolTable(args.scope), {
+ scope: args.scope,
+ serverName: args.serverName,
+ window: args.capabilityWindow,
+ });
+ if (args.json) {
+ process.stdout.write(
+ JSON.stringify(
+ {
+ ok: true,
+ server_name: args.serverName,
+ vault,
+ capabilities: evaluated.report,
+ },
+ null,
+ 2,
+ ) + "\n",
+ );
+ return 0;
+ }
+ const tools = evaluated.tools;
process.stdout.write(
`mcp probe ok: ${args.serverName} (${tools.length} tools, vault=${vault})\n`,
);
@@ -434,7 +538,9 @@ async function cmdToolCall(argv: string[]): Promise<number> {
if (eq === -1) {
// Argument-shape error: align with the dispatcher convention
// (CliError β†’ exit 2). Tool execution failures keep using exit 1.
- process.stderr.write(`error: --tool-arg must be key=value, got: ${pair}\n`);
+ process.stderr.write(
+ `error: --tool-arg must be key=value, got: ${pair}\n`,
+ );
return 2;
}
const k = pair.slice(0, eq);
@@ -456,6 +562,39 @@ async function cmdToolCall(argv: string[]): Promise<number> {
}
}
+function cmdHelp(argv: ReadonlyArray<string>): number {
+ const { flags, positional } = parseFlags(argv, {});
+ if (positional.length > 0) {
+ process.stderr.write(
+ `error: help does not accept positional arguments: ${positional.join(" ")}\n`,
+ );
+ return 2;
+ }
+ if (flags["json"]) {
+ process.stdout.write(JSON.stringify(manifestForJson(), null, 2) + "\n");
+ } else {
+ process.stdout.write(HELP);
+ }
+ return 0;
+}
+
+function cmdCompletions(argv: ReadonlyArray<string>): number {
+ const { positional } = parseFlags(argv, {});
+ if (positional.length !== 1) {
+ process.stderr.write(
+ `error: completions requires one shell (${COMPLETION_SHELLS.join("|")})\n`,
+ );
+ return 2;
+ }
+ const shell = positional[0]!;
+ if (!isCompletionShell(shell)) {
+ process.stderr.write(`error: unsupported completion shell: ${shell}\n`);
+ return 2;
+ }
+ process.stdout.write(renderCompletions(shell, CLI_COMMAND_MANIFEST));
+ return 0;
+}
+
const HELP = `usage: o2b <command> [args...]
Commands:
@@ -470,6 +609,8 @@ Commands:
update Update OSB installation across all detected runtimes
uninstall Print an uninstall plan; --target X removes a per-runtime install
tool-call Invoke an MCP tool handler from the CLI and print JSON to stdout
+ help Print this help text; --json prints command metadata
+ completions Print shell completions for bash, zsh, fish, elvish, nushell, powershell
Pay Memory:
init-pay-memory Bootstrap policies/, payments/, assets/, drafts/, reports/
@@ -530,7 +671,9 @@ export async function main(argv: ReadonlyArray<string>): Promise<number> {
command !== "brain" &&
command !== "vault"
) {
- process.stdout.write(`${command}: see https://github.com/itechmeat/open-second-brain\n`);
+ process.stdout.write(
+ `${command}: see https://github.com/itechmeat/open-second-brain\n`,
+ );
if (command === "uninstall") {
process.stdout.write(
"Read-only by default. Prints the Hermes commands you must run yourself " +
@@ -544,6 +687,52 @@ export async function main(argv: ReadonlyArray<string>): Promise<number> {
return 0;
}
+ const run = () => dispatchCommand(command, rest);
+ if (wantsJsonFlag(rest) && !commandHasSemanticJson(command, rest)) {
+ return await withJsonFallback(command, run);
+ }
+ return await run();
+}
+
+function commandHasSemanticJson(
+ command: string,
+ rest: ReadonlyArray<string>,
+): boolean {
+ if (!wantsJsonFlag(rest)) return false;
+ if (COMMANDS_WITH_INTERNAL_JSON.has(command)) {
+ return true;
+ }
+ if (command === "mcp" && rest.includes("--probe")) return true;
+ if (command === "help") return true;
+ return false;
+}
+
+const COMMANDS_WITH_INTERNAL_JSON: ReadonlySet<string> = new Set([
+ "status",
+ "install",
+ "update",
+ "tool-call",
+ "brain",
+ "search",
+ "vault",
+ "discipline",
+ "init-pay-memory",
+ "append-payment-receipt",
+ "capture-asset",
+ "payment-report",
+ "check-payment-policy",
+ "request-payment-approval",
+ "approve-payment-request",
+ "reject-payment-request",
+ "consume-payment-request",
+ "list-pending-payments",
+ "payment-digest",
+]);
+
+async function dispatchCommand(
+ command: string,
+ rest: string[],
+): Promise<number> {
try {
switch (command) {
case "status":
@@ -568,6 +757,10 @@ export async function main(argv: ReadonlyArray<string>): Promise<number> {
return await cmdUninstall(rest);
case "tool-call":
return await cmdToolCall(rest);
+ case "help":
+ return cmdHelp(rest);
+ case "completions":
+ return cmdCompletions(rest);
case "init-pay-memory":
return await cmdInitPayMemory(rest);
case "append-payment-receipt":
diff --git a/src/mcp/capabilities.ts b/src/mcp/capabilities.ts
new file mode 100644
index 00000000..5f39d8ea
--- /dev/null
+++ b/src/mcp/capabilities.ts
@@ -0,0 +1,107 @@
+import type { ToolDefinition, ToolScope } from "./tools.ts";
+
+export interface RuntimeCapabilityWindow {
+ readonly allowedTools?: ReadonlyArray<string>;
+ readonly disabledTools?: ReadonlyArray<string>;
+ readonly maxTools?: number;
+}
+
+export interface RuntimeCapabilityContext {
+ readonly scope: ToolScope;
+ readonly serverName: string;
+ readonly window?: RuntimeCapabilityWindow;
+}
+
+export interface ToolCapabilityEntry {
+ readonly name: string;
+ readonly reason: string;
+}
+
+export interface ToolCapabilityReport {
+ readonly scope: ToolScope;
+ readonly server_name: string;
+ readonly static_tool_count: number;
+ readonly available_tool_count: number;
+ readonly available: ToolCapabilityEntry[];
+ readonly withheld: ToolCapabilityEntry[];
+}
+
+export interface ToolCapabilityEvaluation {
+ readonly tools: ToolDefinition[];
+ readonly report: ToolCapabilityReport;
+}
+
+export const CAPABILITY_DIAGNOSTIC_TOOL = "second_brain_capabilities";
+
+export function evaluateToolCapabilities(
+ candidates: ReadonlyArray<ToolDefinition>,
+ context: RuntimeCapabilityContext,
+): ToolCapabilityEvaluation {
+ const allowed = nonEmptySet(context.window?.allowedTools);
+ const disabled = new Set(context.window?.disabledTools ?? []);
+ const maxTools = context.window?.maxTools;
+ const tools: ToolDefinition[] = [];
+ const available: ToolCapabilityEntry[] = [];
+ const withheld: ToolCapabilityEntry[] = [];
+ let countedAvailable = 0;
+
+ for (const tool of candidates) {
+ if (tool.name === CAPABILITY_DIAGNOSTIC_TOOL) {
+ tools.push(tool);
+ available.push({
+ name: tool.name,
+ reason: "diagnostic tool is always available",
+ });
+ continue;
+ }
+ const deniedReason = deniedByWindow(
+ tool.name,
+ allowed,
+ disabled,
+ maxTools,
+ countedAvailable,
+ );
+ if (deniedReason) {
+ withheld.push({ name: tool.name, reason: deniedReason });
+ continue;
+ }
+ countedAvailable += 1;
+ tools.push(tool);
+ available.push({ name: tool.name, reason: "available" });
+ }
+
+ return {
+ tools,
+ report: {
+ scope: context.scope,
+ server_name: context.serverName,
+ static_tool_count: candidates.length,
+ available_tool_count: tools.length,
+ available,
+ withheld,
+ },
+ };
+}
+
+function nonEmptySet(
+ values: ReadonlyArray<string> | undefined,
+): ReadonlySet<string> | null {
+ if (!values || values.length === 0) return null;
+ return new Set(values);
+}
+
+function deniedByWindow(
+ name: string,
+ allowed: ReadonlySet<string> | null,
+ disabled: ReadonlySet<string>,
+ maxTools: number | undefined,
+ countedAvailable: number,
+): string | null {
+ if (disabled.has(name)) return "disabled by runtime capability window";
+ if (allowed !== null && !allowed.has(name))
+ return "not allowed by runtime capability window";
+ if (maxTools !== undefined && countedAvailable >= maxTools) {
+ return "outside runtime capability max tool window";
+ }
+ return null;
+}
diff --git a/src/mcp/index.ts b/src/mcp/index.ts
index f9f2dfc6..62e85b99 100644
--- a/src/mcp/index.ts
+++ b/src/mcp/index.ts
@@ -15,8 +15,21 @@ export {
INTERNAL_ERROR,
MCPError,
} from "./protocol.ts";
-export { MCPServer, errorResponse, type JsonRpcRequest, type JsonRpcResponse } from "./server.ts";
+export {
+ MCPServer,
+ errorResponse,
+ type JsonRpcRequest,
+ type JsonRpcResponse,
+} from "./server.ts";
export { serveStdio, serveStdioFromString } from "./stdio.ts";
-export { buildToolTable, PLACEHOLDER_AGENT_VALUES, type ToolDefinition } from "./tools.ts";
+export {
+ buildToolTable,
+ PLACEHOLDER_AGENT_VALUES,
+ type ToolDefinition,
+} from "./tools.ts";
+export {
+ evaluateToolCapabilities,
+ type RuntimeCapabilityWindow,
+} from "./capabilities.ts";
export { buildInstructions } from "./instructions.ts";
export { slugify } from "../core/vault.ts";
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index 49d12bf7..7de9dbdc 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -17,7 +17,11 @@ import {
SERVER_NAME,
SERVER_VERSION,
} from "./protocol.ts";
-import { listResources, listResourceTemplates, readResource } from "./resources.ts";
+import {
+ listResources,
+ listResourceTemplates,
+ readResource,
+} from "./resources.ts";
import {
buildToolTable,
findTool,
@@ -28,6 +32,11 @@ import {
import { assertOutputContract } from "./output-contract.ts";
import { ArtifactStore } from "./artifact-store.ts";
import { applyPreviewBudget } from "./preview-budget.ts";
+import {
+ evaluateToolCapabilities,
+ type RuntimeCapabilityWindow,
+ type ToolCapabilityReport,
+} from "./capabilities.ts";
/** TTL after which a prior process's artifact run directory is pruned. */
const ARTIFACT_TTL_MS = 24 * 60 * 60 * 1000;
@@ -41,6 +50,7 @@ export interface MCPServerOptions {
export interface MCPServerRuntimeOptions {
readonly serverName?: string;
readonly scope?: ToolScope;
+ readonly capabilityWindow?: RuntimeCapabilityWindow;
/**
* Run id grouping this process's preview artifacts under
* `Brain/.artifacts/<run-id>/`. Defaults to a per-process id;
@@ -71,16 +81,27 @@ export class MCPServer {
private readonly serverName: string;
private readonly scope: ToolScope;
private readonly artifactStore: ArtifactStore;
+ private readonly capabilityReport: ToolCapabilityReport;
- constructor(opts: MCPServerOptions, runtimeOpts: MCPServerRuntimeOptions = {}) {
+ constructor(
+ opts: MCPServerOptions,
+ runtimeOpts: MCPServerRuntimeOptions = {},
+ ) {
this.vault = opts.vault;
this.configPath = opts.configPath ?? null;
this.repoRoot = opts.repoRoot ?? null;
this.serverName = runtimeOpts.serverName ?? SERVER_NAME;
this.scope = runtimeOpts.scope ?? "full";
- this.tools = buildToolTable(this.scope);
+ const evaluated = evaluateToolCapabilities(buildToolTable(this.scope), {
+ scope: this.scope,
+ serverName: this.serverName,
+ window: runtimeOpts.capabilityWindow,
+ });
+ this.tools = evaluated.tools;
+ this.capabilityReport = evaluated.report;
const runId =
- runtimeOpts.artifactRunId ?? `run-${process.pid}-${Date.now().toString(36)}`;
+ runtimeOpts.artifactRunId ??
+ `run-${process.pid}-${Date.now().toString(36)}`;
this.artifactStore = new ArtifactStore({ vault: this.vault, runId });
// Best-effort housekeeping: clear prior processes' stale artifacts.
// Never fatal - a missing/unwritable vault just yields zero pruned.
@@ -96,31 +117,53 @@ export class MCPServer {
vault: this.vault,
configPath: this.configPath,
repoRoot: this.repoRoot,
+ capabilityReport: this.capabilityReport,
artifactStore: this.artifactStore,
};
}
/** Public method for CLI tool-call bridge β€” the legacy code reached into `_tools`. */
- async callTool(name: string, args: Record<string, unknown>): Promise<Record<string, unknown>> {
+ async callTool(
+ name: string,
+ args: Record<string, unknown>,
+ ): Promise<Record<string, unknown>> {
const tool = findTool(this.tools, name);
return toolResult(tool, await tool.handler(this.context, args));
}
/** Process one JSON-RPC request or notification. Returns null for notifications. */
- async handleRequest(request: JsonRpcRequest): Promise<JsonRpcResponse | null> {
+ async handleRequest(
+ request: JsonRpcRequest,
+ ): Promise<JsonRpcResponse | null> {
if (typeof request !== "object" || request === null) {
return errorResponse(null, INVALID_REQUEST, "request must be an object");
}
if (request.jsonrpc !== JSONRPC_VERSION) {
- return errorResponse(request.id ?? null, INVALID_REQUEST, "unsupported jsonrpc version");
+ return errorResponse(
+ request.id ?? null,
+ INVALID_REQUEST,
+ "unsupported jsonrpc version",
+ );
}
const method = request.method;
if (typeof method !== "string") {
- return errorResponse(request.id ?? null, INVALID_REQUEST, "method must be a string");
+ return errorResponse(
+ request.id ?? null,
+ INVALID_REQUEST,
+ "method must be a string",
+ );
}
const paramsRaw = request.params ?? {};
- if (typeof paramsRaw !== "object" || paramsRaw === null || Array.isArray(paramsRaw)) {
- return errorResponse(request.id ?? null, INVALID_PARAMS, "params must be an object");
+ if (
+ typeof paramsRaw !== "object" ||
+ paramsRaw === null ||
+ Array.isArray(paramsRaw)
+ ) {
+ return errorResponse(
+ request.id ?? null,
+ INVALID_PARAMS,
+ "params must be an object",
+ );
}
const params = paramsRaw as Record<string, unknown>;
// JSON-RPC 2.0 Β§4.1: `id` MUST be a string, number, or null. Anything
@@ -131,7 +174,11 @@ export class MCPServer {
if (!isNotification) {
const idType = typeof request.id;
if (idType !== "string" && idType !== "number" && request.id !== null) {
- return errorResponse(null, INVALID_REQUEST, "id must be string, number, or null");
+ return errorResponse(
+ null,
+ INVALID_REQUEST,
+ "id must be string, number, or null",
+ );
}
}
const requestId = request.id;
@@ -169,13 +216,20 @@ export class MCPServer {
return errorResponse(requestId, exc.code, exc.message, exc.data);
}
const message = (exc as Error).message ?? String(exc);
- return errorResponse(requestId, INTERNAL_ERROR, `internal error: ${message}`);
+ return errorResponse(
+ requestId,
+ INTERNAL_ERROR,
+ `internal error: ${message}`,
+ );
}
}
- private handleInitialize(params: Record<string, unknown>): Record<string, unknown> {
+ private handleInitialize(
+ params: Record<string, unknown>,
+ ): Record<string, unknown> {
const clientVersion = params["protocolVersion"];
- const negotiated = typeof clientVersion === "string" ? clientVersion : PROTOCOL_VERSION;
+ const negotiated =
+ typeof clientVersion === "string" ? clientVersion : PROTOCOL_VERSION;
const defaultAgent = resolveAgentName(this.configPath ?? undefined);
return {
protocolVersion: negotiated,
@@ -184,7 +238,10 @@ export class MCPServer {
resources: { listChanged: false, subscribe: false },
},
serverInfo: { name: this.serverName, version: SERVER_VERSION },
- instructions: buildInstructions({ agent: defaultAgent, scope: this.scope }),
+ instructions: buildInstructions({
+ agent: defaultAgent,
+ scope: this.scope,
+ }),
};
}
@@ -207,24 +264,38 @@ export class MCPServer {
return { resourceTemplates: listResourceTemplates() };
}
- private handleResourcesRead(params: Record<string, unknown>): Record<string, unknown> {
+ private handleResourcesRead(
+ params: Record<string, unknown>,
+ ): Record<string, unknown> {
const uri = params["uri"];
if (typeof uri !== "string") {
- throw new MCPError(INVALID_PARAMS, "resources/read requires a string `uri`");
+ throw new MCPError(
+ INVALID_PARAMS,
+ "resources/read requires a string `uri`",
+ );
}
const content = readResource({ vault: this.vault }, uri);
return { contents: [content] };
}
- private async handleToolsCall(params: Record<string, unknown>): Promise<Record<string, unknown>> {
+ private async handleToolsCall(
+ params: Record<string, unknown>,
+ ): Promise<Record<string, unknown>> {
const name = params["name"];
if (typeof name !== "string") {
throw new MCPError(INVALID_PARAMS, "tools/call requires a string name");
}
const tool = findTool(this.tools, name);
const argsRaw = params["arguments"] ?? {};
- if (typeof argsRaw !== "object" || argsRaw === null || Array.isArray(argsRaw)) {
- throw new MCPError(INVALID_PARAMS, "tools/call arguments must be an object");
+ if (
+ typeof argsRaw !== "object" ||
+ argsRaw === null ||
+ Array.isArray(argsRaw)
+ ) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ "tools/call arguments must be an object",
+ );
}
const args = argsRaw as Record<string, unknown>;
try {
@@ -241,7 +312,10 @@ export class MCPServer {
}
}
-function toolResult(tool: ToolDefinition, structured: unknown): Record<string, unknown> {
+function toolResult(
+ tool: ToolDefinition,
+ structured: unknown,
+): Record<string, unknown> {
assertOutputContract(tool.name, tool.outputSchema, structured);
const text = JSON.stringify(structured, sortedReplacer, 2);
return {
@@ -284,7 +358,9 @@ function toolError(message: string): Record<string, unknown> {
function sortedReplacer(_key: string, value: unknown): unknown {
if (value !== null && typeof value === "object" && !Array.isArray(value)) {
- const entries = Object.entries(value).toSorted(([a], [b]) => a.localeCompare(b));
+ const entries = Object.entries(value).toSorted(([a], [b]) =>
+ a.localeCompare(b),
+ );
return Object.fromEntries(entries);
}
return value;
@@ -296,7 +372,10 @@ export function errorResponse(
message: string,
data?: unknown,
): JsonRpcResponse {
- const error: { code: number; message: string; data?: unknown } = { code, message };
+ const error: { code: number; message: string; data?: unknown } = {
+ code,
+ message,
+ };
if (data !== undefined) error.data = data;
return { jsonrpc: JSONRPC_VERSION, id: requestId ?? null, error };
}
diff --git a/src/mcp/tools.ts b/src/mcp/tools.ts
index 66c47b5c..a38ea692 100644
--- a/src/mcp/tools.ts
+++ b/src/mcp/tools.ts
@@ -23,11 +23,17 @@ import { discoverConfig, redactMapping } from "../core/config.ts";
import { computeBrainStatus } from "../core/brain/status.ts";
import { doctor } from "../core/doctor.ts";
import { isDir } from "../core/fs-utils.ts";
-import { resolveVaultScope, walkVaultScope } from "../core/vault-scope/index.ts";
+import {
+ resolveVaultScope,
+ walkVaultScope,
+} from "../core/vault-scope/index.ts";
import { BRAIN_TOOLS } from "./brain-tools.ts";
import { SEARCH_TOOLS, buildSearchStatusBlock } from "./search-tools.ts";
import { PAY_MEMORY_TOOLS } from "./pay-memory-tools.ts";
-import { normalizeAgentArgument, PLACEHOLDER_AGENT_VALUES } from "../core/agent-identity.ts";
+import {
+ normalizeAgentArgument,
+ PLACEHOLDER_AGENT_VALUES,
+} from "../core/agent-identity.ts";
import { vaultRelative } from "../core/path-safety.ts";
import { listVaultPages } from "../core/vault.ts";
import { INVALID_PARAMS, METHOD_NOT_FOUND, MCPError } from "./protocol.ts";
@@ -35,11 +41,14 @@ import { coerceStr, coerceInt } from "./coerce.ts";
import type { OutputSchema } from "./output-contract.ts";
import type { ArtifactStore } from "./artifact-store.ts";
import { MCP_PREVIEW_BUDGET } from "./preview-budget.ts";
+import type { ToolCapabilityReport } from "./capabilities.ts";
+import { CAPABILITY_DIAGNOSTIC_TOOL } from "./capabilities.ts";
export interface ServerContext {
readonly vault: string;
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
@@ -90,7 +99,9 @@ function vaultRelpath(target: string, vault: string): string {
// ── Tool implementations ────────────────────────────────────────────────────
-async function toolStatus(ctx: ServerContext): Promise<Record<string, unknown>> {
+async function toolStatus(
+ ctx: ServerContext,
+): Promise<Record<string, unknown>> {
const discovery = discoverConfig(ctx.configPath ?? undefined);
const vaultExists = isDir(ctx.vault);
const configKeys = Object.keys(discovery.data).toSorted();
@@ -98,7 +109,8 @@ async function toolStatus(ctx: ServerContext): Promise<Record<string, unknown>>
// `present: false` with zero counts.
const brain = vaultExists ? computeBrainStatus(ctx.vault) : null;
const searchDisabled = discovery.data["search_enabled"] === "false";
- const search = vaultExists && !searchDisabled ? await buildSearchStatusBlock(ctx) : null;
+ const search =
+ vaultExists && !searchDisabled ? await buildSearchStatusBlock(ctx) : null;
// 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.
@@ -184,7 +196,11 @@ async function toolVaultHealth(
config: ctx.configPath,
repoRoot: repoRoot ?? null,
});
- const payload = results.map((r) => ({ name: r.name, ok: r.ok, message: r.message }));
+ const payload = results.map((r) => ({
+ name: r.name,
+ ok: r.ok,
+ message: r.message,
+ }));
return {
vault_path: ctx.vault,
config_path: ctx.configPath ? String(ctx.configPath) : null,
@@ -216,6 +232,13 @@ async function toolArtifactGet(
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"],
@@ -226,6 +249,40 @@ const ARTIFACT_GET_OUTPUT_SCHEMA: OutputSchema = {
},
};
+const CAPABILITIES_OUTPUT_SCHEMA: OutputSchema = {
+ type: "object",
+ required: [
+ "scope",
+ "server_name",
+ "static_tool_count",
+ "available_tool_count",
+ "available",
+ "withheld",
+ ],
+ properties: {
+ scope: { type: "string", enum: ["full", "writer"] },
+ server_name: { type: "string" },
+ static_tool_count: { type: "integer" },
+ available_tool_count: { type: "integer" },
+ 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" } },
+ },
+ },
+ },
+};
+
export type ToolScope = "full" | "writer";
// The set is named after the original payload (mutating writers). As
@@ -243,10 +300,26 @@ const WRITER_TOOL_NAMES: ReadonlySet<string> = new Set([
export function buildToolTable(scope: ToolScope = "full"): ToolDefinition[] {
const all: ToolDefinition[] = [
+ {
+ name: CAPABILITY_DIAGNOSTIC_TOOL,
+ 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",
description: "Report Open Second Brain configuration and vault status.",
- inputSchema: { type: "object", properties: {}, additionalProperties: false },
+ inputSchema: {
+ type: "object",
+ properties: {},
+ additionalProperties: false,
+ },
previewBudget: MCP_PREVIEW_BUDGET,
handler: toolStatus,
},
@@ -258,13 +331,15 @@ export function buildToolTable(scope: ToolScope = "full"): ToolDefinition[] {
properties: {
pattern: {
type: "string",
- description: "Optional case-insensitive substring matched against page titles.",
+ 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).",
+ description:
+ "Maximum number of matched pages to return (default 50).",
},
},
additionalProperties: false,
@@ -285,7 +360,8 @@ export function buildToolTable(scope: ToolScope = "full"): ToolDefinition[] {
properties: {
repo: {
type: "string",
- description: "Optional repository root to validate plugin manifests.",
+ description:
+ "Optional repository root to validate plugin manifests.",
},
},
additionalProperties: false,
@@ -301,7 +377,8 @@ export function buildToolTable(scope: ToolScope = "full"): ToolDefinition[] {
properties: {
artifact_id: {
type: "string",
- description: "The artifact_id returned in a preview-truncated tool result envelope.",
+ description:
+ "The artifact_id returned in a preview-truncated tool result envelope.",
},
},
required: ["artifact_id"],
@@ -316,7 +393,10 @@ export function buildToolTable(scope: ToolScope = "full"): ToolDefinition[] {
return all.filter((t) => WRITER_TOOL_NAMES.has(t.name));
}
-export function findTool(tools: ReadonlyArray<ToolDefinition>, name: string): ToolDefinition {
+export function findTool(
+ tools: ReadonlyArray<ToolDefinition>,
+ name: string,
+): ToolDefinition {
const tool = tools.find((t) => t.name === name);
if (!tool) throw new MCPError(METHOD_NOT_FOUND, `unknown tool: ${name}`);
return tool;
diff --git a/tests/cli/cli-json-contract.test.ts b/tests/cli/cli-json-contract.test.ts
new file mode 100644
index 00000000..b90c99d9
--- /dev/null
+++ b/tests/cli/cli-json-contract.test.ts
@@ -0,0 +1,77 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { runCli } from "../helpers/run-cli.ts";
+
+let tempDir: string;
+let vault: string;
+let configPath: string;
+
+beforeEach(() => {
+ tempDir = mkdtempSync(join(tmpdir(), "o2b-cli-json-"));
+ vault = join(tempDir, "vault");
+ configPath = join(tempDir, "config.yaml");
+ mkdirSync(vault, { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(tempDir, { recursive: true, force: true });
+});
+
+function env(): Record<string, string> {
+ return {
+ OPEN_SECOND_BRAIN_CONFIG: configPath,
+ VAULT_DIR: "",
+ VAULT_AGENT_NAME: "",
+ };
+}
+
+describe("inherited CLI --json contract", () => {
+ test("text-only commands accept --json and return a fallback envelope", async () => {
+ const result = await runCli(["doctor", "--vault", vault, "--json"], {
+ env: env(),
+ });
+
+ const parsed = JSON.parse(result.stdout);
+ expect(parsed.command).toBe("doctor");
+ expect(parsed.code).toBe(result.returncode);
+ expect(typeof parsed.ok).toBe("boolean");
+ expect(typeof parsed.stdout).toBe("string");
+ expect(parsed.stdout.length).toBeGreaterThan(0);
+ expect(result.stderr).toBe("");
+ });
+
+ test("commands with semantic JSON keep their existing payload shape", async () => {
+ const result = await runCli(["status", "--config", configPath, "--json"], {
+ env: env(),
+ });
+
+ expect(result.returncode).toBe(0);
+ const parsed = JSON.parse(result.stdout);
+ expect(parsed.config_path).toBe(configPath);
+ expect(parsed).not.toHaveProperty("command");
+ expect(parsed).not.toHaveProperty("stdout");
+ });
+
+ test("fallback JSON redacts secret-shaped output", async () => {
+ const result = await runCli(
+ [
+ "init",
+ "--vault",
+ vault,
+ "--agent-name",
+ "api_key=super-secret-value",
+ "--json",
+ ],
+ { env: env() },
+ );
+
+ expect(result.returncode).toBe(0);
+ const parsed = JSON.parse(result.stdout);
+ const serialized = JSON.stringify(parsed);
+ expect(serialized).not.toContain("super-secret-value");
+ expect(serialized).toContain("[REDACTED]");
+ });
+});
diff --git a/tests/cli/completions.test.ts b/tests/cli/completions.test.ts
new file mode 100644
index 00000000..ba605979
--- /dev/null
+++ b/tests/cli/completions.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, test } from "bun:test";
+
+import { runCli } from "../helpers/run-cli.ts";
+
+describe("CLI command manifest", () => {
+ test("help --json lists root commands, nested verbs, and inherited json flag", async () => {
+ const result = await runCli(["help", "--json"]);
+
+ expect(result.returncode).toBe(0);
+ expect(result.stderr).toBe("");
+ const parsed = JSON.parse(result.stdout);
+
+ expect(parsed.command).toBe("o2b");
+ const rootNames = parsed.commands.map((command: any) => command.name);
+ expect(rootNames).toContain("status");
+ expect(rootNames).toContain("mcp");
+ expect(rootNames).toContain("brain");
+ expect(rootNames).toContain("completions");
+
+ const status = parsed.commands.find(
+ (command: any) => command.name === "status",
+ );
+ expect(status.flags).toContainEqual({
+ name: "json",
+ type: "boolean",
+ inherited: true,
+ });
+
+ const brain = parsed.commands.find(
+ (command: any) => command.name === "brain",
+ );
+ const brainVerbs = brain.commands.map((command: any) => command.name);
+ expect(brainVerbs).toContain("doctor");
+ expect(brainVerbs).toContain("mcp-landscape");
+ });
+});
+
+describe("o2b completions", () => {
+ for (const shell of [
+ "bash",
+ "zsh",
+ "fish",
+ "elvish",
+ "nushell",
+ "powershell",
+ ]) {
+ test(`prints ${shell} completions from the manifest`, async () => {
+ const result = await runCli(["completions", shell]);
+
+ expect(result.returncode).toBe(0);
+ expect(result.stderr).toBe("");
+ expect(result.stdout).toContain("o2b");
+ expect(result.stdout).toContain("brain");
+ expect(result.stdout).toContain("mcp");
+ expect(result.stdout).toContain("--json");
+ });
+ }
+
+ test("rejects unsupported shells", async () => {
+ const result = await runCli(["completions", "xonsh"]);
+
+ expect(result.returncode).toBe(2);
+ expect(result.stderr).toContain("unsupported completion shell: xonsh");
+ });
+});
diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.ts
index 288d1090..88bd0785 100644
--- a/tests/mcp/mcp.test.ts
+++ b/tests/mcp/mcp.test.ts
@@ -173,6 +173,8 @@ describe("tool listing", () => {
.toSorted();
expect(names).toEqual(
[
+ // Runtime capability diagnostics (v0.23.0).
+ "second_brain_capabilities",
// Core read/health (writable legacy tools removed in v0.9.0).
"second_brain_status",
"second_brain_query",
@@ -478,7 +480,8 @@ describe("stdio loop", () => {
// + brain_audit (v0.21.0) = 43.
// + brain_morning_brief (v0.21.0) = 44.
// + brain_sources + brain_switch_vault (v0.22.0) = 46.
- expect(list.result.tools.length).toBe(46);
+ // + second_brain_capabilities (v0.23.0) = 47.
+ expect(list.result.tools.length).toBe(47);
});
test("returns parse error for invalid JSON", async () => {
diff --git a/tests/mcp/runtime-capabilities.test.ts b/tests/mcp/runtime-capabilities.test.ts
new file mode 100644
index 00000000..83c5eb99
--- /dev/null
+++ b/tests/mcp/runtime-capabilities.test.ts
@@ -0,0 +1,104 @@
+import { describe, expect, test } from "bun:test";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { JSONRPC_VERSION, MCPServer } from "../../src/mcp/index.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+describe("MCP runtime capability window", () => {
+ test("runtime deny withholds a tool and reports the reason", async () => {
+ const server = new MCPServer(
+ { vault: "/tmp/o2b-runtime-capability-test" },
+ { capabilityWindow: { disabledTools: ["second_brain_query"] } },
+ );
+
+ const listResponse = (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 1,
+ method: "tools/list",
+ })) as any;
+ const names = (listResponse.result.tools as Array<{ name: string }>).map(
+ (tool) => tool.name,
+ );
+
+ expect(names).toContain("second_brain_capabilities");
+ expect(names).not.toContain("second_brain_query");
+
+ const reportResponse = (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 2,
+ method: "tools/call",
+ params: { name: "second_brain_capabilities", arguments: {} },
+ })) as any;
+ const report = reportResponse.result.structuredContent;
+
+ expect(report.scope).toBe("full");
+ expect(
+ report.available.some((tool: any) => tool.name === "second_brain_status"),
+ ).toBe(true);
+ expect(report.withheld).toContainEqual({
+ name: "second_brain_query",
+ reason: "disabled by runtime capability window",
+ });
+ });
+
+ test("runtime allow list cannot widen writer scope", async () => {
+ const server = new MCPServer(
+ { vault: "/tmp/o2b-runtime-capability-test" },
+ {
+ scope: "writer",
+ capabilityWindow: {
+ allowedTools: ["second_brain_status", "brain_feedback"],
+ },
+ },
+ );
+
+ const response = (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 1,
+ method: "tools/list",
+ })) as any;
+ const names = (response.result.tools as Array<{ name: string }>).map(
+ (tool) => tool.name,
+ );
+
+ expect(names).toContain("brain_feedback");
+ expect(names).not.toContain("second_brain_status");
+ });
+
+ test("mcp probe json emits capability report", async () => {
+ const vault = mkdtempSync(join(tmpdir(), "o2b-runtime-capability-vault-"));
+ try {
+ const result = await runCli(
+ [
+ "mcp",
+ "--vault",
+ vault,
+ "--probe",
+ "--json",
+ "--disable-tool",
+ "second_brain_query",
+ ],
+ { env: { OPEN_SECOND_BRAIN_CONFIG: "" } },
+ );
+
+ expect(result.returncode).toBe(0);
+ expect(result.stderr).toBe("");
+ const parsed = JSON.parse(result.stdout);
+ expect(parsed.ok).toBe(true);
+ expect(parsed.server_name).toBe("open-second-brain");
+ expect(parsed.capabilities.withheld).toContainEqual({
+ name: "second_brain_query",
+ reason: "disabled by runtime capability window",
+ });
+ expect(
+ parsed.capabilities.available.some(
+ (tool: any) => tool.name === "second_brain_status",
+ ),
+ ).toBe(true);
+ } finally {
+ rmSync(vault, { recursive: true, force: true });
+ }
+ });
+});