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: add v1 MCP tool server

Sol Aitkenf053b9ff8124
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 548e85f8..c4129654 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,12 +1,12 @@
{
"name": "open-second-brain",
- "version": "0.0.1",
+ "version": "0.4.0",
"description": "Plugin-first second brain package for AI agents and humans.",
"author": "Open Second Brain contributors",
"license": "MIT",
"homepage": "https://github.com/itechmeat/open-second-brain",
"repository": "https://github.com/itechmeat/open-second-brain",
- "keywords": ["second-brain", "obsidian", "agents", "skills", "event-log"],
+ "keywords": ["second-brain", "obsidian", "agents", "skills", "event-log", "mcp"],
"commands": [
{
"name": "status",
@@ -44,6 +44,12 @@
"command": "scripts/o2b",
"args": ["export-config"]
},
+ {
+ "name": "mcp",
+ "description": "Run the optional MCP tool server over stdio (JSON-RPC 2.0).",
+ "command": "scripts/o2b",
+ "args": ["mcp"]
+ },
{
"name": "vault-log",
"description": "Compatibility wrapper for appending event log entries.",
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index 4fccc626..874d62ea 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "open-second-brain",
- "version": "0.0.1",
+ "version": "0.4.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, and other agent runtimes.",
"skills": "./skills",
- "keywords": ["second-brain", "obsidian", "agents", "skills", "event-log"]
+ "keywords": ["second-brain", "obsidian", "agents", "skills", "event-log", "mcp"]
}
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e384a1ef..3f08d74e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+## [0.4.0] - 2026-05-06
+
+### Added
+
+- Optional Model Context Protocol (MCP) tool server over stdio JSON-RPC 2.0 (`o2b mcp`, `o2b-mcp`).
+- Five MCP tools backed by the existing core: `second_brain_status`, `second_brain_query`, `second_brain_capture`, `event_log_append`, `vault_health`.
+- `docs/mcp.md` guide for Hermes `~/.hermes/config.yaml mcp_servers` registration, Claude Code, and Codex.
+- `mcp_server` metadata in the top-level Hermes plugin manifest and `plugins/hermes/plugin.yaml`.
+- `mcp` command entry in the Claude Code plugin manifest.
+- 20 dedicated MCP tests covering handshake, tools listing, every tool, stdio loop, and CLI integration.
+
+### Changed
+
+- Bumped package, plugin, and Claude/Codex manifest versions to 0.4.0.
+- Updated README and roadmap to mark v1 as implemented and link to the new MCP guide.
+
## [0.3.1] - 2026-05-06
### Added
@@ -32,6 +48,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Sandbox vault and plugin manifest fixtures for tests.
- GitHub release workflow for tag-based and manually dispatched releases.
-[unreleased]: https://github.com/itechmeat/open-second-brain/compare/v0.3.1...HEAD
+[unreleased]: https://github.com/itechmeat/open-second-brain/compare/v0.4.0...HEAD
+[0.4.0]: https://github.com/itechmeat/open-second-brain/compare/v0.3.1...v0.4.0
[0.3.1]: https://github.com/itechmeat/open-second-brain/compare/v0.3.0...v0.3.1
[0.3.0]: https://github.com/itechmeat/open-second-brain/releases/tag/v0.3.0
diff --git a/README.md b/README.md
index bdcd7a58..defadb37 100644
--- a/README.md
+++ b/README.md
@@ -75,11 +75,25 @@ o2b doctor Run vault and adapter checks
o2b append-event Append one daily event-log entry
o2b index Rebuild the Markdown page index
o2b export-config Write a redacted config snapshot
+o2b mcp Run the optional MCP tool server (stdio)
vault-log Compatibility wrapper around append-event
```
The local checkout can be used without installing the Python package. Run commands through `scripts/o2b` and `scripts/vault-log`, or set `PYTHONPATH=src` for module execution.
+## Optional MCP tool server
+
+OpenSecondBrain ships an optional Model Context Protocol server that exposes the same deterministic operations as MCP tools. Hermes Agent discovers it through `~/.hermes/config.yaml`:
+
+```yaml
+mcp_servers:
+ open-second-brain:
+ command: o2b
+ args: ["mcp", "--vault", "/path/to/vault"]
+```
+
+Tools: `second_brain_status`, `second_brain_query`, `second_brain_capture`, `event_log_append`, `vault_health`. See `docs/mcp.md` for full setup, tool schemas, and Claude Code/Codex notes. The CLI remains the supported baseline; the MCP server is opt-in.
+
## Safety model
- Your notes stay as plain Markdown.
diff --git a/docs/mcp.md b/docs/mcp.md
new file mode 100644
index 00000000..9ac92686
--- /dev/null
+++ b/docs/mcp.md
@@ -0,0 +1,107 @@
+# MCP tool server
+
+The optional Model Context Protocol (MCP) server exposes Open Second Brain's
+deterministic operations as tools that Hermes Agent (or any other MCP client)
+can route through its tool registry.
+
+The server is **optional**: the `o2b` CLI remains the supported baseline. Nothing
+in Open Second Brain depends on the MCP server being running.
+
+## Protocol
+
+- Transport: stdio (JSON-RPC 2.0, newline-delimited).
+- Protocol version: `2025-06-18`.
+- Capabilities advertised: `tools` only. No `resources`, `prompts`, or
+ `sampling`.
+- Standard MCP lifecycle: `initialize`, `notifications/initialized`,
+ `tools/list`, `tools/call`, optional `ping`.
+
+## Tools
+
+| 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. | β€” |
+| `second_brain_capture` | Write a Markdown note under `AI Wiki/notes/` with frontmatter. | `title`, `content` |
+| `event_log_append` | Append a single-line event to the daily Markdown event log. | `message` |
+| `vault_health` | Run vault, config, and plugin manifest health checks. | β€” |
+
+`second_brain_query` accepts `pattern` (string) and `limit` (1–500, default 50).
+`second_brain_capture` also accepts `tags` (array of strings) and `overwrite`
+(boolean). `event_log_append` accepts `agent`, `date` (YYYY.MM.DD), and `time`
+(HH:MM). `vault_health` accepts `repo` (string) for plugin manifest validation.
+
+All tool results contain both an unstructured `content` text block (a JSON
+serialization of the structured payload) and a `structuredContent` object so
+clients that prefer typed results can use it directly.
+
+## Run from the CLI
+
+```bash
+scripts/o2b mcp --vault /path/to/vault
+```
+
+Optional flags:
+
+- `--config PATH` β€” override the Open Second Brain config file location.
+- `--repo PATH` β€” repository root used for plugin manifest checks.
+
+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.
+
+## Hermes integration
+
+Hermes discovers MCP servers from `~/.hermes/config.yaml` under the
+`mcp_servers` key. After installing this plugin, register the MCP server on
+the same machine that hosts the vault:
+
+```yaml
+mcp_servers:
+ open-second-brain:
+ command: o2b
+ args: ["mcp", "--vault", "/path/to/vault"]
+ enabled: true
+ timeout: 30
+ tools:
+ include:
+ - second_brain_status
+ - second_brain_query
+ - second_brain_capture
+ - event_log_append
+ - vault_health
+```
+
+If you run Open Second Brain from a checkout instead of an installed package,
+point `command` at the absolute path of `scripts/o2b`:
+
+```yaml
+mcp_servers:
+ open-second-brain:
+ command: /srv/projects/open-second-brain/scripts/o2b
+ args: ["mcp", "--vault", "/path/to/vault"]
+```
+
+After editing the file, run `/reload-mcp` inside Hermes to pick up the new
+server.
+
+The Hermes plugin manifest (`plugin.yaml`) advertises this MCP entrypoint via
+the `mcp_server` field so future Hermes releases can auto-register the server,
+but the official Hermes config flow is the source of truth today.
+
+## Claude Code and Codex
+
+The Claude Code plugin manifest exposes `o2b mcp` as a regular command that
+Claude Code can invoke. Codex installs the same `scripts/o2b` script through
+its plugin manifest, so the MCP entrypoint is reachable from a Codex shell as
+well. There is no auto-registration into Codex's MCP discovery β€” add the
+server to your Codex MCP config the same way as Hermes.
+
+## Safety notes
+
+- The vault path is bound to the server instance at startup. Tools cannot
+ escape it.
+- `second_brain_capture` writes only under `<vault>/AI Wiki/notes/` and rejects
+ collisions unless `overwrite: true` is supplied.
+- `second_brain_status` reuses the same redaction logic as `o2b export-config`.
+- `event_log_append` appends below the `## Raw events` section using the same
+ locking strategy as the CLI.
diff --git a/docs/roadmap.md b/docs/roadmap.md
index 70896166..50b9fa03 100644
--- a/docs/roadmap.md
+++ b/docs/roadmap.md
@@ -69,17 +69,17 @@ Implemented:
- better install and runtime notes in README;
- test fixtures for sandbox vaults and plugin manifest repos.
-## v1: MCP tool server
+## v1: MCP tool server βœ…
-Optional MCP server over the same core operations:
+Implemented in v0.4.0 (`docs/mcp.md`):
-- `second_brain_status`;
-- `second_brain_query`;
-- `second_brain_capture`;
-- `event_log_append`;
-- `vault_health`.
+- stdio JSON-RPC 2.0 server on protocol version `2025-06-18`;
+- five tools: `second_brain_status`, `second_brain_query`, `second_brain_capture`, `event_log_append`, `vault_health`;
+- `o2b mcp` subcommand and `o2b-mcp` console script;
+- Hermes/Claude/Codex manifest metadata referencing the MCP entrypoint;
+- documentation for `~/.hermes/config.yaml mcp_servers` registration.
-The MCP server should be optional. CLI must remain the baseline.
+The MCP server is optional. The CLI remains the supported baseline.
## v2: richer automation
diff --git a/plugin.yaml b/plugin.yaml
index f6d5ea8c..a53e7c85 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,6 +1,11 @@
name: open-second-brain
-version: "0.3.1"
-description: "Hermes plugin entrypoint for OpenSecondBrain vault health checks."
+version: "0.4.0"
+description: "Hermes plugin entrypoint for OpenSecondBrain vault health checks and the optional MCP tool server."
author: "OpenSecondBrain contributors"
kind: standalone
provides_hooks: []
+mcp_server:
+ command: scripts/o2b
+ args: ["mcp"]
+ description: "Optional stdio MCP server. Add to ~/.hermes/config.yaml mcp_servers if MCP tool routing is desired."
+ protocol_version: "2025-06-18"
diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yaml
index f3f40ddb..5876479c 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,6 +1,11 @@
name: open-second-brain
-version: "0.3.1"
-description: "Hermes adapter for OpenSecondBrain vault health checks."
+version: "0.4.0"
+description: "Hermes adapter for OpenSecondBrain vault health checks and optional MCP tool server."
author: "OpenSecondBrain contributors"
kind: standalone
provides_hooks: []
+mcp_server:
+ command: scripts/o2b
+ args: ["mcp"]
+ description: "Optional stdio MCP server. Add to ~/.hermes/config.yaml mcp_servers if MCP tool routing is desired."
+ protocol_version: "2025-06-18"
diff --git a/pyproject.toml b/pyproject.toml
index be9505f9..500b12cb 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "open-second-brain"
-version = "0.3.1"
+version = "0.4.0"
description = "Hermes-first second brain package for Obsidian-compatible Markdown vaults."
readme = "README.md"
requires-python = ">=3.11"
@@ -16,6 +16,7 @@ dependencies = []
[project.scripts]
o2b = "open_second_brain.cli:main"
vault-log = "open_second_brain.vault_log:main"
+o2b-mcp = "open_second_brain.mcp:main"
[tool.setuptools.packages.find]
where = ["src"]
diff --git a/src/open_second_brain/__init__.py b/src/open_second_brain/__init__.py
index 2be37a4f..2c472b92 100644
--- a/src/open_second_brain/__init__.py
+++ b/src/open_second_brain/__init__.py
@@ -1,3 +1,3 @@
"""Open Second Brain core package."""
-__version__ = "0.0.1"
+__version__ = "0.4.0"
diff --git a/src/open_second_brain/cli.py b/src/open_second_brain/cli.py
index cc662da8..4fb8141f 100644
--- a/src/open_second_brain/cli.py
+++ b/src/open_second_brain/cli.py
@@ -10,6 +10,7 @@ from open_second_brain.config import default_config_path, discover_config, redac
from open_second_brain.doctor import doctor
from open_second_brain.event_log import append_event
from open_second_brain.init import bootstrap_vault
+from open_second_brain.mcp import run_cli_command as run_mcp_server
from open_second_brain.vault import list_vault_pages, write_frontmatter
@@ -44,6 +45,18 @@ def build_parser() -> argparse.ArgumentParser:
index_cmd = subcommands.add_parser("index", help="Regenerate the vault index from discovered pages")
index_cmd.add_argument("--vault", type=Path, default=None, help="Vault directory path")
+ mcp_cmd = subcommands.add_parser(
+ "mcp",
+ help="Run the optional MCP tool server (stdio JSON-RPC)",
+ description=(
+ "Start an MCP server over stdio that exposes Second Brain tools. "
+ "Pair with Hermes ~/.hermes/config.yaml mcp_servers."
+ ),
+ )
+ mcp_cmd.add_argument("--vault", type=Path, default=None, help="Vault directory path")
+ mcp_cmd.add_argument("--config", type=Path, default=None, help="Config file path")
+ mcp_cmd.add_argument("--repo", type=Path, default=None, help="Repository root for plugin checks")
+
return parser
@@ -156,6 +169,16 @@ def command_index(args: argparse.Namespace) -> int:
return 0
+def command_mcp(args: argparse.Namespace) -> int:
+ vault = args.vault or Path(os.environ.get("VAULT_DIR", "."))
+ config = args.config or default_config_path()
+ repo_root: Path | None = args.repo
+ try:
+ return run_mcp_server(vault=vault, config_path=config, repo_root=repo_root)
+ except KeyboardInterrupt:
+ return 0
+
+
def main(argv: list[str] | None = None) -> int:
parser = build_parser()
args = parser.parse_args(argv)
@@ -171,6 +194,8 @@ def main(argv: list[str] | None = None) -> int:
return command_export_config(args)
if args.command == "index":
return command_index(args)
+ if args.command == "mcp":
+ return command_mcp(args)
raise AssertionError(f"unhandled command: {args.command}")
diff --git a/src/open_second_brain/mcp.py b/src/open_second_brain/mcp.py
new file mode 100644
index 00000000..ca94fe09
--- /dev/null
+++ b/src/open_second_brain/mcp.py
@@ -0,0 +1,589 @@
+"""Optional Model Context Protocol (MCP) server for Open Second Brain.
+
+This module implements a stdio JSON-RPC 2.0 server that exposes deterministic
+Second Brain operations as MCP tools. It is dependency-free and uses the
+``2025-06-18`` MCP protocol version, which the current Hermes Agent runtime
+discovers and registers like any other ``mcp_servers`` entry in
+``~/.hermes/config.yaml`` (see ``docs/mcp.md``).
+
+The CLI is the baseline: every tool here delegates to the same core helpers
+(``config``, ``doctor``, ``event_log``, ``vault``) used by the ``o2b`` command,
+so behavior stays consistent across runtimes.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import re
+import sys
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Callable, IO
+
+from open_second_brain.config import default_config_path, discover_config, redact_mapping
+from open_second_brain.doctor import doctor
+from open_second_brain.event_log import append_event, validate_event_time
+from open_second_brain.vault import list_vault_pages, parse_frontmatter, write_frontmatter
+
+PROTOCOL_VERSION = "2025-06-18"
+SERVER_NAME = "open-second-brain"
+SERVER_VERSION = "0.4.0"
+JSONRPC_VERSION = "2.0"
+
+# JSON-RPC 2.0 error codes used by the MCP server.
+PARSE_ERROR = -32700
+INVALID_REQUEST = -32600
+METHOD_NOT_FOUND = -32601
+INVALID_PARAMS = -32602
+INTERNAL_ERROR = -32603
+
+_SLUG_INVALID = re.compile(r"[^a-z0-9]+")
+_SLUG_MAX_LEN = 64
+
+
+@dataclass(frozen=True)
+class ToolDefinition:
+ name: str
+ description: str
+ input_schema: dict[str, Any]
+ handler: Callable[["MCPServer", dict[str, Any]], dict[str, Any]]
+
+ def to_listing(self) -> dict[str, Any]:
+ return {
+ "name": self.name,
+ "description": self.description,
+ "inputSchema": self.input_schema,
+ }
+
+
+def slugify(value: str) -> str:
+ lowered = value.strip().lower()
+ slug = _SLUG_INVALID.sub("-", lowered).strip("-")
+ if not slug:
+ slug = "note"
+ return slug[:_SLUG_MAX_LEN].rstrip("-") or "note"
+
+
+def _vault_relpath(target: Path, vault: Path) -> str:
+ try:
+ return str(target.resolve().relative_to(vault.resolve()))
+ except ValueError:
+ return str(target)
+
+
+def _ensure_inside_vault(target: Path, vault: Path) -> Path:
+ resolved_target = target.resolve()
+ resolved_vault = vault.resolve()
+ try:
+ resolved_target.relative_to(resolved_vault)
+ except ValueError as exc:
+ raise ValueError(f"path escapes vault: {target}") from exc
+ return resolved_target
+
+
+class MCPError(Exception):
+ """Protocol-level error returned as a JSON-RPC error response."""
+
+ def __init__(self, code: int, message: str, data: Any | None = None):
+ super().__init__(message)
+ self.code = code
+ self.message = message
+ self.data = data
+
+
+class MCPServer:
+ """JSON-RPC 2.0 MCP server exposing Second Brain operations as tools."""
+
+ def __init__(
+ self,
+ *,
+ vault: Path,
+ config_path: Path | None = None,
+ repo_root: Path | None = None,
+ ) -> None:
+ self.vault = vault
+ self.config_path = config_path
+ self.repo_root = repo_root
+ self._initialized = False
+ self._tools: dict[str, ToolDefinition] = {tool.name: tool for tool in _build_tool_table()}
+
+ # ── JSON-RPC dispatch ────────────────────────────────────────────────
+
+ def handle_request(self, request: dict[str, Any]) -> dict[str, Any] | None:
+ """Process one JSON-RPC request or notification.
+
+ Returns a JSON-RPC response dict, or ``None`` for notifications.
+ """
+
+ if not isinstance(request, dict):
+ return self._error_response(None, INVALID_REQUEST, "request must be an object")
+ if request.get("jsonrpc") != JSONRPC_VERSION:
+ return self._error_response(request.get("id"), INVALID_REQUEST, "unsupported jsonrpc version")
+
+ method = request.get("method")
+ if not isinstance(method, str):
+ return self._error_response(request.get("id"), INVALID_REQUEST, "method must be a string")
+
+ params = request.get("params") or {}
+ request_id = request.get("id")
+ is_notification = "id" not in request
+
+ try:
+ if method == "initialize":
+ result = self._handle_initialize(params)
+ elif method == "notifications/initialized":
+ self._initialized = True
+ return None
+ elif method == "ping":
+ result = {}
+ elif method == "tools/list":
+ result = self._handle_tools_list()
+ elif method == "tools/call":
+ result = self._handle_tools_call(params)
+ elif method.startswith("notifications/"):
+ return None
+ else:
+ raise MCPError(METHOD_NOT_FOUND, f"unknown method: {method}")
+ except MCPError as exc:
+ if is_notification:
+ return None
+ return self._error_response(request_id, exc.code, exc.message, exc.data)
+ except Exception as exc: # noqa: BLE001 β€” last-resort safety net for stdio loop
+ if is_notification:
+ return None
+ return self._error_response(request_id, INTERNAL_ERROR, f"internal error: {exc}")
+
+ if is_notification:
+ return None
+ return {"jsonrpc": JSONRPC_VERSION, "id": request_id, "result": result}
+
+ # ── Method handlers ──────────────────────────────────────────────────
+
+ def _handle_initialize(self, params: dict[str, Any]) -> dict[str, Any]:
+ client_version = params.get("protocolVersion")
+ negotiated = client_version if isinstance(client_version, str) else PROTOCOL_VERSION
+ return {
+ "protocolVersion": negotiated,
+ "capabilities": {"tools": {"listChanged": False}},
+ "serverInfo": {"name": SERVER_NAME, "version": SERVER_VERSION},
+ "instructions": (
+ "Open Second Brain MCP server. Tools are deterministic wrappers around the o2b CLI. "
+ "Use second_brain_status before writes, vault_health to verify the vault, "
+ "second_brain_query to look up notes, second_brain_capture to add wiki pages, "
+ "and event_log_append for daily operational events."
+ ),
+ }
+
+ def _handle_tools_list(self) -> dict[str, Any]:
+ return {"tools": [tool.to_listing() for tool in self._tools.values()]}
+
+ def _handle_tools_call(self, params: dict[str, Any]) -> dict[str, Any]:
+ name = params.get("name")
+ if not isinstance(name, str):
+ raise MCPError(INVALID_PARAMS, "tools/call requires a string name")
+ tool = self._tools.get(name)
+ if tool is None:
+ raise MCPError(METHOD_NOT_FOUND, f"unknown tool: {name}")
+ arguments = params.get("arguments") or {}
+ if not isinstance(arguments, dict):
+ raise MCPError(INVALID_PARAMS, "tools/call arguments must be an object")
+ try:
+ structured = tool.handler(self, arguments)
+ except MCPError:
+ raise
+ except (ValueError, TypeError) as exc:
+ return _tool_error(str(exc))
+ except OSError as exc:
+ return _tool_error(f"filesystem error: {exc}")
+ return _tool_result(structured)
+
+ # ── Helpers ──────────────────────────────────────────────────────────
+
+ def _error_response(
+ self,
+ request_id: Any,
+ code: int,
+ message: str,
+ data: Any | None = None,
+ ) -> dict[str, Any]:
+ error: dict[str, Any] = {"code": code, "message": message}
+ if data is not None:
+ error["data"] = data
+ return {"jsonrpc": JSONRPC_VERSION, "id": request_id, "error": error}
+
+
+# ── Tool implementations ─────────────────────────────────────────────────
+
+
+def _tool_result(structured: dict[str, Any]) -> dict[str, Any]:
+ text = json.dumps(structured, ensure_ascii=False, sort_keys=True, indent=2)
+ return {
+ "content": [{"type": "text", "text": text}],
+ "structuredContent": structured,
+ "isError": False,
+ }
+
+
+def _tool_error(message: str) -> dict[str, Any]:
+ return {
+ "content": [{"type": "text", "text": message}],
+ "isError": True,
+ }
+
+
+def _coerce_str(arguments: dict[str, Any], key: str, *, required: bool = True, default: str | None = None) -> str | None:
+ value = arguments.get(key)
+ if value is None:
+ if required:
+ raise MCPError(INVALID_PARAMS, f"missing required argument: {key}")
+ return default
+ if not isinstance(value, str):
+ raise MCPError(INVALID_PARAMS, f"argument {key!r} must be a string")
+ return value
+
+
+def _coerce_str_list(arguments: dict[str, Any], key: str) -> list[str]:
+ value = arguments.get(key)
+ if value is None:
+ return []
+ if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
+ raise MCPError(INVALID_PARAMS, f"argument {key!r} must be a list of strings")
+ return value
+
+
+def _coerce_int(arguments: dict[str, Any], key: str, *, default: int, minimum: int, maximum: int) -> int:
+ value = arguments.get(key, default)
+ if isinstance(value, bool) or not isinstance(value, int):
+ raise MCPError(INVALID_PARAMS, f"argument {key!r} must be an integer")
+ if value < minimum or value > maximum:
+ raise MCPError(INVALID_PARAMS, f"argument {key!r} must be between {minimum} and {maximum}")
+ return value
+
+
+def _tool_second_brain_status(server: MCPServer, _arguments: dict[str, Any]) -> dict[str, Any]:
+ discovery = discover_config(server.config_path)
+ vault_exists = server.vault.is_dir()
+ config_keys = sorted(discovery.data.keys())
+ return {
+ "config_path": str(discovery.path),
+ "config_exists": discovery.exists,
+ "config_keys": config_keys,
+ "config": redact_mapping(discovery.data),
+ "vault_path": str(server.vault),
+ "vault_exists": vault_exists,
+ }
+
+
+def _tool_second_brain_query(server: MCPServer, arguments: dict[str, Any]) -> dict[str, Any]:
+ if not server.vault.is_dir():
+ raise MCPError(INVALID_PARAMS, f"vault directory missing: {server.vault}")
+
+ pattern = _coerce_str(arguments, "pattern", required=False)
+ limit = _coerce_int(arguments, "limit", default=50, minimum=1, maximum=500)
+
+ pages = list_vault_pages(server.vault)
+ needle = pattern.lower() if pattern else None
+ matched: list[dict[str, Any]] = []
+ for title, path, meta in pages:
+ if needle is not None and needle not in title.lower():
+ continue
+ matched.append(
+ {
+ "title": title,
+ "path": _vault_relpath(path, server.vault),
+ "metadata": meta,
+ }
+ )
+ if len(matched) >= limit:
+ break
+
+ return {
+ "vault_path": str(server.vault),
+ "total_pages": len(pages),
+ "returned": len(matched),
+ "limit": limit,
+ "pattern": pattern,
+ "pages": matched,
+ }
+
+
+def _tool_second_brain_capture(server: MCPServer, arguments: dict[str, Any]) -> dict[str, Any]:
+ if not server.vault.is_dir():
+ raise MCPError(INVALID_PARAMS, f"vault directory missing: {server.vault}")
+
+ title = _coerce_str(arguments, "title")
+ content = _coerce_str(arguments, "content")
+ tags = _coerce_str_list(arguments, "tags")
+ overwrite = bool(arguments.get("overwrite", False))
+ assert title is not None # required=True
+ assert content is not None # required=True
+
+ if not title.strip():
+ raise MCPError(INVALID_PARAMS, "title must not be empty")
+ if not content.strip():
+ raise MCPError(INVALID_PARAMS, "content must not be empty")
+
+ notes_dir = server.vault / "AI Wiki" / "notes"
+ notes_dir.mkdir(parents=True, exist_ok=True)
+
+ slug = slugify(title)
+ target = notes_dir / f"{slug}.md"
+ _ensure_inside_vault(target, server.vault)
+
+ note_existed = target.exists()
+ if note_existed and not overwrite:
+ raise ValueError(f"note already exists: {_vault_relpath(target, server.vault)}")
+
+ metadata: dict[str, Any] = {
+ "title": title,
+ "type": "note",
+ "created": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
+ }
+ if tags:
+ metadata["tags"] = list(tags)
+
+ write_frontmatter(target, metadata, content.strip())
+
+ return {
+ "path": _vault_relpath(target, server.vault),
+ "absolute_path": str(target.resolve()),
+ "slug": slug,
+ "overwritten": note_existed and overwrite,
+ }
+
+
+def _tool_event_log_append(server: MCPServer, arguments: dict[str, Any]) -> dict[str, Any]:
+ message = _coerce_str(arguments, "message")
+ agent = _coerce_str(
+ arguments,
+ "agent",
+ required=False,
+ default=os.environ.get("VAULT_AGENT_NAME", "agent"),
+ )
+ date = _coerce_str(arguments, "date", required=False)
+ time = _coerce_str(arguments, "time", required=False)
+ assert message is not None # required=True
+
+ if time is not None:
+ validate_event_time(time)
+
+ effective_agent = agent or "agent"
+ path = append_event(server.vault, effective_agent, message, date=date, time=time)
+
+ return {
+ "path": _vault_relpath(path, server.vault),
+ "absolute_path": str(path.resolve()),
+ "agent": effective_agent,
+ "date": date,
+ "time": time,
+ }
+
+
+def _tool_vault_health(server: MCPServer, arguments: dict[str, Any]) -> dict[str, Any]:
+ repo_arg = _coerce_str(arguments, "repo", required=False)
+ if repo_arg:
+ repo_root: Path | None = Path(repo_arg)
+ else:
+ repo_root = server.repo_root
+
+ results = doctor(vault=server.vault, config=server.config_path, repo_root=repo_root)
+ payload = [{"name": r.name, "ok": r.ok, "message": r.message} for r in results]
+ return {
+ "vault_path": str(server.vault),
+ "config_path": str(server.config_path) if server.config_path else None,
+ "repo_root": str(repo_root) if repo_root else None,
+ "ok": all(item["ok"] for item in payload),
+ "checks": payload,
+ }
+
+
+def _build_tool_table() -> list[ToolDefinition]:
+ return [
+ ToolDefinition(
+ name="second_brain_status",
+ description="Report Open Second Brain configuration and vault status.",
+ input_schema={"type": "object", "properties": {}, "additionalProperties": False},
+ handler=_tool_second_brain_status,
+ ),
+ ToolDefinition(
+ name="second_brain_query",
+ description="List vault pages with optional title substring filter.",
+ input_schema={
+ "type": "object",
+ "properties": {
+ "pattern": {
+ "type": "string",
+ "description": "Optional case-insensitive substring matched against page titles.",
+ },
+ "limit": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 500,
+ "description": "Maximum number of matched pages to return (default 50).",
+ },
+ },
+ "additionalProperties": False,
+ },
+ handler=_tool_second_brain_query,
+ ),
+ ToolDefinition(
+ name="second_brain_capture",
+ description="Write a new Markdown note to AI Wiki/notes/ with frontmatter.",
+ input_schema={
+ "type": "object",
+ "properties": {
+ "title": {"type": "string", "description": "Human-readable note title."},
+ "content": {"type": "string", "description": "Markdown body of the note."},
+ "tags": {
+ "type": "array",
+ "items": {"type": "string"},
+ "description": "Optional list of tag strings.",
+ },
+ "overwrite": {
+ "type": "boolean",
+ "description": "Allow overwriting an existing note with the same slug.",
+ },
+ },
+ "required": ["title", "content"],
+ "additionalProperties": False,
+ },
+ handler=_tool_second_brain_capture,
+ ),
+ ToolDefinition(
+ name="event_log_append",
+ description="Append a single-line event to the daily Markdown event log.",
+ input_schema={
+ "type": "object",
+ "properties": {
+ "message": {"type": "string", "description": "Single-line event message."},
+ "agent": {"type": "string", "description": "Agent name (default 'agent')."},
+ "date": {
+ "type": "string",
+ "description": "Optional event date in YYYY.MM.DD format.",
+ },
+ "time": {
+ "type": "string",
+ "description": "Optional event time in 24-hour HH:MM format.",
+ },
+ },
+ "required": ["message"],
+ "additionalProperties": False,
+ },
+ handler=_tool_event_log_append,
+ ),
+ ToolDefinition(
+ name="vault_health",
+ description="Run vault, config, and plugin manifest health checks.",
+ input_schema={
+ "type": "object",
+ "properties": {
+ "repo": {
+ "type": "string",
+ "description": "Optional repository root to validate plugin manifests.",
+ },
+ },
+ "additionalProperties": False,
+ },
+ handler=_tool_vault_health,
+ ),
+ ]
+
+
+# ── stdio loop ───────────────────────────────────────────────────────────
+
+
+def serve_stdio(
+ server: MCPServer,
+ *,
+ stdin: IO[str] | None = None,
+ stdout: IO[str] | None = None,
+ stderr: IO[str] | None = None,
+) -> int:
+ """Run the MCP server reading newline-delimited JSON from stdin.
+
+ The server only writes JSON-RPC frames to ``stdout``. Logs go to ``stderr``.
+ Returns 0 on normal EOF.
+ """
+
+ inp = stdin or sys.stdin
+ out = stdout or sys.stdout
+ err = stderr or sys.stderr
+
+ for raw_line in inp:
+ line = raw_line.strip()
+ if not line:
+ continue
+ try:
+ request = json.loads(line)
+ except json.JSONDecodeError as exc:
+ response = server._error_response( # noqa: SLF001 β€” controlled internal use
+ None, PARSE_ERROR, f"invalid JSON: {exc}"
+ )
+ _write_frame(out, response)
+ continue
+
+ if isinstance(request, list):
+ response = server._error_response( # noqa: SLF001 β€” controlled internal use
+ None,
+ INVALID_REQUEST,
+ "batch requests are not supported by the 2025-06-18 spec",
+ )
+ _write_frame(out, response)
+ continue
+
+ response = server.handle_request(request)
+ if response is not None:
+ _write_frame(out, response)
+ return 0
+
+
+def _write_frame(out: IO[str], response: dict[str, Any]) -> None:
+ line = json.dumps(response, ensure_ascii=False)
+ if "\n" in line:
+ line = line.replace("\n", " ")
+ out.write(line + "\n")
+ out.flush()
+
+
+def run_cli_command(
+ *,
+ vault: Path,
+ config_path: Path | None,
+ repo_root: Path | None,
+) -> int:
+ server = MCPServer(vault=vault, config_path=config_path, repo_root=repo_root)
+ sys.stderr.write(
+ f"[mcp] open-second-brain {SERVER_VERSION} listening on stdio (vault={vault})\n"
+ )
+ sys.stderr.flush()
+ return serve_stdio(server)
+
+
+def default_repo_root() -> Path:
+ return Path(__file__).resolve().parents[2]
+
+
+def main(argv: list[str] | None = None) -> int:
+ """Entry point for ``python -m open_second_brain.mcp``."""
+
+ import argparse
+
+ parser = argparse.ArgumentParser(
+ prog="open-second-brain-mcp",
+ description="Open Second Brain MCP server (stdio).",
+ )
+ parser.add_argument("--vault", type=Path, default=None, help="Vault directory")
+ parser.add_argument("--config", type=Path, default=None, help="Config file path")
+ parser.add_argument("--repo", type=Path, default=None, help="Repository root for plugin checks")
+ args = parser.parse_args(argv)
+
+ vault = args.vault or Path(os.environ.get("VAULT_DIR", "."))
+ config = args.config or default_config_path()
+ repo_root = args.repo
+ return run_cli_command(vault=vault, config_path=config, repo_root=repo_root)
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/src/open_second_brain/vault.py b/src/open_second_brain/vault.py
index 2b82faca..791dbd92 100644
--- a/src/open_second_brain/vault.py
+++ b/src/open_second_brain/vault.py
@@ -48,12 +48,44 @@ def parse_frontmatter(path: Path) -> tuple[dict[str, Any], str]:
return metadata, body
+_PLAIN_SCALAR_RE = re.compile(r"^[A-Za-z0-9_./-](?:[A-Za-z0-9_./ -]*[A-Za-z0-9_./-])?$")
+
+
+def _format_yaml_scalar(value: Any) -> str:
+ text = str(value)
+ if (
+ text
+ and _PLAIN_SCALAR_RE.match(text)
+ and ": " not in text
+ and " #" not in text
+ ):
+ return text
+ escaped = (
+ text.replace("\\", "\\\\")
+ .replace('"', '\\"')
+ .replace("\n", "\\n")
+ .replace("\r", "\\r")
+ .replace("\t", "\\t")
+ )
+ return f'"{escaped}"'
+
+
+def _format_yaml_value(value: Any) -> str:
+ if isinstance(value, list):
+ return "[" + ", ".join(_format_yaml_scalar(item) for item in value) + "]"
+ return _format_yaml_scalar(value)
+
+
def write_frontmatter(path: Path, metadata: dict[str, Any], body: str) -> None:
- """Write a Markdown file with YAML-like frontmatter and body text."""
+ """Write a Markdown file with YAML-like frontmatter and body text.
+
+ Lists are serialized as YAML inline arrays (``key: [a, b]``) so they round-trip
+ cleanly through Obsidian and the project's simple frontmatter parser.
+ """
path.parent.mkdir(parents=True, exist_ok=True)
lines = ["---"]
for key, value in metadata.items():
- lines.append(f"{key}: {value}")
+ lines.append(f"{key}: {_format_yaml_value(value)}")
lines.append("---")
if body:
lines.append("")
diff --git a/tests/test_mcp.py b/tests/test_mcp.py
new file mode 100644
index 00000000..c731d19e
--- /dev/null
+++ b/tests/test_mcp.py
@@ -0,0 +1,403 @@
+import io
+import json
+import os
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+ENV = {**os.environ, "PYTHONPATH": str(ROOT / "src")}
+
+sys.path.insert(0, str(ROOT / "src"))
+
+from open_second_brain.mcp import ( # noqa: E402
+ JSONRPC_VERSION,
+ MCPServer,
+ PROTOCOL_VERSION,
+ SERVER_NAME,
+ SERVER_VERSION,
+ serve_stdio,
+ slugify,
+)
+from tests.fixtures import create_plugin_repo, create_sandbox_vault # noqa: E402
+
+
+def _make_server(vault: Path, *, config: Path | None = None, repo: Path | None = None) -> MCPServer:
+ return MCPServer(vault=vault, config_path=config, repo_root=repo)
+
+
+def _initialize(server: MCPServer) -> dict:
+ response = server.handle_request(
+ {
+ "jsonrpc": JSONRPC_VERSION,
+ "id": 1,
+ "method": "initialize",
+ "params": {
+ "protocolVersion": PROTOCOL_VERSION,
+ "capabilities": {},
+ "clientInfo": {"name": "test-client", "version": "0"},
+ },
+ }
+ )
+ assert server.handle_request(
+ {"jsonrpc": JSONRPC_VERSION, "method": "notifications/initialized"}
+ ) is None
+ return response
+
+
+def _call_tool(server: MCPServer, name: str, arguments: dict | None = None, request_id: int = 99) -> dict:
+ return server.handle_request(
+ {
+ "jsonrpc": JSONRPC_VERSION,
+ "id": request_id,
+ "method": "tools/call",
+ "params": {"name": name, "arguments": arguments or {}},
+ }
+ )
+
+
+class SlugifyTests(unittest.TestCase):
+ def test_slugify_lowercases_and_replaces_punctuation(self):
+ self.assertEqual(slugify("Hello, World!"), "hello-world")
+
+ def test_slugify_handles_unicode_and_empty(self):
+ self.assertEqual(slugify(" "), "note")
+ self.assertEqual(slugify("---"), "note")
+ self.assertEqual(slugify("КСйс / ВСст"), "note")
+
+ def test_slugify_truncates_long_input(self):
+ long = "a" * 200
+ self.assertEqual(len(slugify(long)), 64)
+
+
+class HandshakeTests(unittest.TestCase):
+ def test_initialize_returns_server_info_and_tools_capability(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ server = _make_server(Path(tmp))
+ response = _initialize(server)
+ self.assertEqual(response["jsonrpc"], JSONRPC_VERSION)
+ self.assertEqual(response["id"], 1)
+ result = response["result"]
+ self.assertEqual(result["serverInfo"]["name"], SERVER_NAME)
+ self.assertEqual(result["serverInfo"]["version"], SERVER_VERSION)
+ self.assertIn("tools", result["capabilities"])
+ self.assertEqual(result["protocolVersion"], PROTOCOL_VERSION)
+
+ def test_initialize_negotiates_alternate_client_version(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ server = _make_server(Path(tmp))
+ response = server.handle_request(
+ {
+ "jsonrpc": JSONRPC_VERSION,
+ "id": 1,
+ "method": "initialize",
+ "params": {
+ "protocolVersion": "2024-11-05",
+ "capabilities": {},
+ "clientInfo": {"name": "old", "version": "0"},
+ },
+ }
+ )
+ self.assertEqual(response["result"]["protocolVersion"], "2024-11-05")
+
+ def test_initialized_notification_is_silent(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ server = _make_server(Path(tmp))
+ self.assertIsNone(
+ server.handle_request(
+ {"jsonrpc": JSONRPC_VERSION, "method": "notifications/initialized"}
+ )
+ )
+
+ def test_unknown_method_returns_method_not_found(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ server = _make_server(Path(tmp))
+ response = server.handle_request(
+ {"jsonrpc": JSONRPC_VERSION, "id": 7, "method": "does/not/exist"}
+ )
+ self.assertEqual(response["error"]["code"], -32601)
+
+
+class ToolListingTests(unittest.TestCase):
+ def test_tools_list_advertises_all_roadmap_tools(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ server = _make_server(Path(tmp))
+ _initialize(server)
+ response = server.handle_request(
+ {"jsonrpc": JSONRPC_VERSION, "id": 2, "method": "tools/list"}
+ )
+ names = {tool["name"] for tool in response["result"]["tools"]}
+ self.assertEqual(
+ names,
+ {
+ "second_brain_status",
+ "second_brain_query",
+ "second_brain_capture",
+ "event_log_append",
+ "vault_health",
+ },
+ )
+ for tool in response["result"]["tools"]:
+ self.assertIn("inputSchema", tool)
+ self.assertEqual(tool["inputSchema"]["type"], "object")
+
+
+class ToolCallTests(unittest.TestCase):
+ def test_second_brain_status_reports_vault_and_config(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ vault = Path(tmp) / "vault"
+ vault.mkdir()
+ config = Path(tmp) / "config.yaml"
+ config.write_text("vault_path: /tmp/vault\napi_key: secret\n", encoding="utf-8")
+ server = _make_server(vault, config=config)
+ _initialize(server)
+
+ response = _call_tool(server, "second_brain_status")
+ structured = response["result"]["structuredContent"]
+ self.assertEqual(structured["vault_path"], str(vault))
+ self.assertTrue(structured["vault_exists"])
+ self.assertEqual(structured["config"]["api_key"], "[REDACTED]")
+ self.assertIn("vault_path", structured["config_keys"])
+
+ def test_second_brain_query_filters_and_limits(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ vault = create_sandbox_vault(Path(tmp))
+ server = _make_server(vault)
+ _initialize(server)
+
+ response = _call_tool(
+ server,
+ "second_brain_query",
+ {"pattern": "Sandbox", "limit": 5},
+ )
+ structured = response["result"]["structuredContent"]
+ self.assertEqual(structured["limit"], 5)
+ self.assertGreaterEqual(structured["total_pages"], 1)
+ self.assertTrue(any("Sandbox" in p["title"] for p in structured["pages"]))
+
+ def test_second_brain_capture_writes_note_with_frontmatter(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ vault = Path(tmp) / "vault"
+ vault.mkdir()
+ server = _make_server(vault)
+ _initialize(server)
+
+ response = _call_tool(
+ server,
+ "second_brain_capture",
+ {
+ "title": "Hello World",
+ "content": "# Body\n\ntext",
+ "tags": ["draft", "demo"],
+ },
+ )
+ structured = response["result"]["structuredContent"]
+ note = vault / "AI Wiki" / "notes" / "hello-world.md"
+ self.assertTrue(note.is_file())
+ text = note.read_text(encoding="utf-8")
+ self.assertIn("title: Hello World", text)
+ self.assertIn("tags: [draft, demo]", text)
+ self.assertIn("# Body", text)
+ self.assertEqual(structured["slug"], "hello-world")
+
+ def test_second_brain_capture_rejects_existing_note_without_overwrite(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ vault = Path(tmp) / "vault"
+ vault.mkdir()
+ server = _make_server(vault)
+ _initialize(server)
+
+ args = {"title": "Same Title", "content": "first"}
+ response = _call_tool(server, "second_brain_capture", args)
+ self.assertFalse(response["result"]["isError"])
+
+ response = _call_tool(server, "second_brain_capture", args, request_id=100)
+ self.assertTrue(response["result"]["isError"])
+ self.assertIn("already exists", response["result"]["content"][0]["text"])
+
+ def test_second_brain_capture_rejects_empty_title(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ vault = Path(tmp) / "vault"
+ vault.mkdir()
+ server = _make_server(vault)
+ _initialize(server)
+
+ response = _call_tool(
+ server,
+ "second_brain_capture",
+ {"title": " ", "content": "body"},
+ )
+ self.assertEqual(response["error"]["code"], -32602)
+
+ def test_event_log_append_writes_daily_note(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ vault = Path(tmp)
+ server = _make_server(vault)
+ _initialize(server)
+
+ response = _call_tool(
+ server,
+ "event_log_append",
+ {
+ "message": "via mcp",
+ "agent": "mcp-test",
+ "date": "2026.05.06",
+ "time": "11:42",
+ },
+ )
+ self.assertFalse(response["result"]["isError"])
+ structured = response["result"]["structuredContent"]
+ self.assertEqual(structured["agent"], "mcp-test")
+ daily = vault / "Daily" / "2026.05.06.md"
+ self.assertIn("- 11:42 β€” @mcp-test β€” via mcp", daily.read_text(encoding="utf-8"))
+
+ def test_event_log_append_rejects_invalid_time(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ server = _make_server(Path(tmp))
+ _initialize(server)
+ response = _call_tool(
+ server,
+ "event_log_append",
+ {"message": "x", "time": "99:99"},
+ )
+ self.assertTrue(response["result"]["isError"])
+ self.assertIn("HH:MM", response["result"]["content"][0]["text"])
+
+ def test_vault_health_runs_doctor(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ vault = create_sandbox_vault(Path(tmp))
+ repo = create_plugin_repo(Path(tmp), valid=True)
+ server = _make_server(vault, repo=repo)
+ _initialize(server)
+
+ response = _call_tool(server, "vault_health", {})
+ structured = response["result"]["structuredContent"]
+ self.assertTrue(structured["ok"])
+ check_names = {check["name"] for check in structured["checks"]}
+ self.assertIn("vault_writeable", check_names)
+ self.assertIn("claude_manifest", check_names)
+ self.assertIn("hermes_manifest", check_names)
+
+ def test_unknown_tool_returns_method_not_found(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ server = _make_server(Path(tmp))
+ _initialize(server)
+ response = _call_tool(server, "not_a_tool")
+ self.assertEqual(response["error"]["code"], -32601)
+
+
+class StdioLoopTests(unittest.TestCase):
+ def test_serve_stdio_processes_initialize_and_tools_list(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ vault = Path(tmp)
+ server = MCPServer(vault=vault)
+ payload = "\n".join(
+ [
+ json.dumps(
+ {
+ "jsonrpc": JSONRPC_VERSION,
+ "id": 1,
+ "method": "initialize",
+ "params": {
+ "protocolVersion": PROTOCOL_VERSION,
+ "capabilities": {},
+ "clientInfo": {"name": "t", "version": "0"},
+ },
+ }
+ ),
+ json.dumps({"jsonrpc": JSONRPC_VERSION, "method": "notifications/initialized"}),
+ json.dumps({"jsonrpc": JSONRPC_VERSION, "id": 2, "method": "tools/list"}),
+ ]
+ ) + "\n"
+ stdin = io.StringIO(payload)
+ stdout = io.StringIO()
+ stderr = io.StringIO()
+ self.assertEqual(serve_stdio(server, stdin=stdin, stdout=stdout, stderr=stderr), 0)
+ lines = [line for line in stdout.getvalue().splitlines() if line]
+ self.assertEqual(len(lines), 2)
+ init_response = json.loads(lines[0])
+ list_response = json.loads(lines[1])
+ self.assertEqual(init_response["id"], 1)
+ self.assertEqual(list_response["id"], 2)
+ self.assertEqual(len(list_response["result"]["tools"]), 5)
+
+ def test_serve_stdio_returns_parse_error_for_invalid_json(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ server = MCPServer(vault=Path(tmp))
+ stdin = io.StringIO("{not json}\n")
+ stdout = io.StringIO()
+ self.assertEqual(serve_stdio(server, stdin=stdin, stdout=stdout, stderr=io.StringIO()), 0)
+ response = json.loads(stdout.getvalue().splitlines()[0])
+ self.assertEqual(response["error"]["code"], -32700)
+
+ def test_serve_stdio_returns_invalid_request_for_batch_request(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ server = MCPServer(vault=Path(tmp))
+ batch = json.dumps(
+ [
+ {"jsonrpc": JSONRPC_VERSION, "id": 1, "method": "ping"},
+ {"jsonrpc": JSONRPC_VERSION, "id": 2, "method": "ping"},
+ ]
+ )
+ stdin = io.StringIO(batch + "\n")
+ stdout = io.StringIO()
+ self.assertEqual(serve_stdio(server, stdin=stdin, stdout=stdout, stderr=io.StringIO()), 0)
+ response = json.loads(stdout.getvalue().splitlines()[0])
+ self.assertEqual(response["error"]["code"], -32600)
+ self.assertIn("batch", response["error"]["message"].lower())
+
+
+class CliIntegrationTests(unittest.TestCase):
+ def test_o2b_mcp_subcommand_serves_stdio(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ vault = Path(tmp) / "vault"
+ vault.mkdir()
+ payload = "\n".join(
+ [
+ json.dumps(
+ {
+ "jsonrpc": JSONRPC_VERSION,
+ "id": 1,
+ "method": "initialize",
+ "params": {
+ "protocolVersion": PROTOCOL_VERSION,
+ "capabilities": {},
+ "clientInfo": {"name": "t", "version": "0"},
+ },
+ }
+ ),
+ json.dumps({"jsonrpc": JSONRPC_VERSION, "method": "notifications/initialized"}),
+ json.dumps({"jsonrpc": JSONRPC_VERSION, "id": 2, "method": "tools/list"}),
+ ]
+ ) + "\n"
+ result = subprocess.run(
+ [
+ sys.executable,
+ "-m",
+ "open_second_brain.cli",
+ "mcp",
+ "--vault",
+ str(vault),
+ ],
+ cwd=ROOT,
+ input=payload,
+ env=ENV,
+ text=True,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ timeout=15,
+ )
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertIn("listening on stdio", result.stderr)
+ lines = [line for line in result.stdout.splitlines() if line]
+ self.assertEqual(len(lines), 2)
+ tools_response = json.loads(lines[1])
+ self.assertEqual(tools_response["id"], 2)
+ tool_names = {tool["name"] for tool in tools_response["result"]["tools"]}
+ self.assertIn("second_brain_status", tool_names)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_vault.py b/tests/test_vault.py
index c3c1dace..846f30e7 100644
--- a/tests/test_vault.py
+++ b/tests/test_vault.py
@@ -44,6 +44,42 @@ class VaultTests(unittest.TestCase):
self.assertEqual(meta["title"], "Roundtrip")
self.assertEqual(body, "The body.")
+ def test_write_frontmatter_serializes_list_values_as_inline_array(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ path = Path(tmp) / "note.md"
+ write_frontmatter(
+ path,
+ {"title": "Tagged", "tags": ["draft", "demo"]},
+ "Body.",
+ )
+ text = path.read_text(encoding="utf-8")
+ self.assertIn("tags: [draft, demo]", text)
+
+ def test_write_frontmatter_quotes_list_values_with_special_chars(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ path = Path(tmp) / "note.md"
+ write_frontmatter(
+ path,
+ {"tags": ["plain", "needs, comma"]},
+ "Body.",
+ )
+ text = path.read_text(encoding="utf-8")
+ self.assertIn('tags: [plain, "needs, comma"]', text)
+
+ def test_write_frontmatter_quotes_scalar_with_colon_space(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ path = Path(tmp) / "note.md"
+ write_frontmatter(path, {"title": "Hello: world"}, "Body.")
+ text = path.read_text(encoding="utf-8")
+ self.assertIn('title: "Hello: world"', text)
+
+ def test_write_frontmatter_escapes_control_characters(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ path = Path(tmp) / "note.md"
+ write_frontmatter(path, {"summary": "line one\nline two"}, "Body.")
+ text = path.read_text(encoding="utf-8")
+ self.assertIn(r'summary: "line one\nline two"', text)
+
def test_extract_wikilinks_simple(self):
content = "See [[Target]] and [[Other]] for details."
links = extract_wikilinks(content)