### Example: read and paginate Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/vault.md Shows how to resolve a note, read its text, and get the etag for revision guarding. ```typescript const fs = runtime.forVault("work").fs; const entry = await fs.resolveExisting("Projects/Plan.md"); const { text, etag } = await fs.readText(entry); console.log(etag); // 64-hex SHA-256 revision guard ``` -------------------------------- ### Example: using assertIfMatch Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/utility-helpers.md Example usage of assertIfMatch. Shows how to catch a REVISION_CONFLICT ToolFailure and re-read the note to retry. ```ts import { assertIfMatch } from "./validation.js"; try { assertIfMatch(ifMatch, currentEtag); // guard from obsidian_read_note } catch (error) { if (error instanceof ToolFailure && error.code === "REVISION_CONFLICT") { // re-read the note and retry } } ``` -------------------------------- ### run method example Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/transaction.md Example of using the run method to execute a transaction with a write and mkdir change. The transaction ID is returned. ```typescript const tm = runtime.forVault("work").transactions; const txId = await tm.run([ { kind: "write", path: "/vault/Notes/A.md", data: Buffer.from("# A"), requireMissing: true }, { kind: "mkdir", path: "/vault/Notes/NewDir", mode: 0o755 } ]); ``` -------------------------------- ### Install globally Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/README.md Install the package globally, then use "command": "obsidian-mcp" with the same arguments beginning at "serve". ```bash npm install -g obsidian-mcp@2 ``` -------------------------------- ### Move example with planLinkUpdates Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/links.md Example of calling planLinkUpdates in move mode and folding the resulting changes into a transaction with the move's write and delete operations. ```ts const links = await planLinkUpdates(fs, "Drafts/Plan.md", "Projects/Plan.md", "move"); const txId = await transactions.run([ { kind: "write", path: to, data: bytes, requireMissing: true }, { kind: "delete", path: from, expectedEtag: etag }, ...links.changes ]); ``` -------------------------------- ### Serve two vaults with runCli Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/cli.md Example of starting the MCP server with two vaults using the --vault flag. ```ts import { runCli } from "./cli.js"; // serve two vaults await runCli(["serve", "--vault", "work=/Users/me/Documents/WorkVault", "--vault", "personal=/Users/me/Documents/PersonalVault"]); ``` -------------------------------- ### Read note example: createReadNoteTool execute Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/tools-notes.md Example of creating the read tool and executing it with a vault, path, and max_chars. The returned page1.etag is used for edit/move/delete if_match. ```typescript const def = createReadNoteTool(runtime); const page1 = await def.execute( { vault: "work", path: "Projects/Plan.md", max_chars: 5000 }, { signal: abortSignal } ); // page1.etag → pass to edit/move/delete if_match ``` -------------------------------- ### Serve the fixture vault Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/evaluations/README.md Starts the server with the fixture vault mounted. The path must be an absolute path to the evaluations/fixture-vault directory. ```bash node dist/main.js serve --vault fixture-vault=/absolute/path/to/evaluations/fixture-vault ``` -------------------------------- ### Registry usage example for registerTool Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/tool-factory.md Example of registering a read-note tool in the registry. Shows how to pass the server and a tool factory function that returns a ToolDefinition. ```typescript registerTool(server, createReadNoteTool(runtime)); ``` -------------------------------- ### Mark broken example with planLinkUpdates Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/links.md Example of calling planLinkUpdates in mark_broken mode, with a comment noting that ambiguous links are reported but changes are still applied. ```ts const links = await planLinkUpdates(fs, "Drafts/Plan.md", undefined, "mark_broken"); // links.ambiguousLinks > 0 → report to the client; links.changes still applied ``` -------------------------------- ### Example: initialize a Runtime Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/runtime.md Constructs a `Runtime` with a recovery policy of 30 days and 1 GiB max bytes, then calls `initialize()` to prepare per-vault transaction managers. ```ts const runtime = new Runtime(registry, { recoveryDays: 30, recoveryMaxBytes: 1 << 30 }, logger); await runtime.initialize(); // per-vault TransactionManager is ready ``` -------------------------------- ### Error-handling example Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/vault.md Shows how to catch NOTE_NOT_FOUND when resolving a missing note and handle it. ```typescript let entry; try { entry = await fs.resolveExisting("Missing.md"); } catch (error) { if (error instanceof ToolFailure && error.code === "NOTE_NOT_FOUND") { // create it instead… } else { throw error; } } ``` -------------------------------- ### run method error handling example Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/transaction.md Example of error handling for the run method, checking for retryable errors and revision conflicts. ```typescript try { await tm.run([{ kind: "delete", path: "/vault/Notes/A.md", expectedEtag: oldEtag }]); } catch (error) { if (error instanceof ToolFailure && error.code === "REVISION_CONFLICT") { // re-read the note, retry with the fresh etag } else if (error instanceof ToolFailure && error.retryable) { // (LOCK_TIMEOUT, TRANSACTION_FAILED…) wait briefly and retry } } ``` -------------------------------- ### Embedding createToolDefinitions example Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/tools-registry.md Example of embedding tool definitions programmatically, used by tests and programmatic hosts. Shows destructuring the tuple and executing a tool with an AbortSignal. ```ts import { createToolDefinitions } from "./tools/index.js"; const definitions = createToolDefinitions(runtime); const [list, read] = definitions; // obsidian_list_vaults, obsidian_read_note await read.execute({ vault: "work", path: "Plan.md", max_chars: 5000 }, { signal: new AbortController().signal }); ``` -------------------------------- ### parseArguments example Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/cli.md Example usage of parseArguments with a serve command, a vault definition, and legacy mode. The comments show the expected parsed values. ```ts const parsed = parseArguments(["serve", "--vault", "notes=/vaults/Notes", "--legacy", "reject"]); // parsed.command === "serve" // parsed.vaults === [{ id: "notes", root: "/vaults/Notes" }] // parsed.legacy === "reject" ``` -------------------------------- ### Example: forVault to resolve and write Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/runtime.md Retrieves the services for the vault ID `work`, then resolves an existing file and runs a write transaction that requires the target to be missing. ```ts const { fs, transactions } = runtime.forVault("work"); const entry = await fs.resolveExisting("Projects/Plan.md"); const txId = await transactions.run([{ kind: "write", path: entry.absolutePath, data: Buffer.from("# New"), requireMissing: true }]); ``` -------------------------------- ### Example: executing add tags tool Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/tools-tags.md Shows how to execute the add-tags tool with a vault, paths, tags, and location. The result includes unchanged_count for paths that already had the tag. ```typescript const def = createAddTagsTool(runtime); const result = await def.execute( { vault: "work", paths: ["Projects/Orchid.md", "Projects/Relay.md"], tags: ["project/active"], location: "frontmatter" }, ctx ); // result.unchanged_count — paths that already had the tag ``` -------------------------------- ### wildcardMatch usage example Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/tags.md Example calls to wildcardMatch showing true for 'project/*' matching 'project/active' and 'project/active/sub', and false for 'other/active'. ```TypeScript wildcardMatch("project/*", "project/active"); // true wildcardMatch("project/*", "project/active/sub"); // true wildcardMatch("project/*", "other/active"); // false ``` -------------------------------- ### MIGRATION_GUIDE_URL constant Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/diagnostics.md Exports the migration guide URL constant. Appended with '#' in every formatted diagnostic. ```typescript export const MIGRATION_GUIDE_URL = "https://github.com/StevenStavrakis/obsidian-mcp/blob/v2-next/MIGRATING.md"; ``` -------------------------------- ### Check Node.js version Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/README.md Check that Node.js 22 or newer is installed before running the server. ```bash node --version # v22 or newer ``` -------------------------------- ### Read with revision protection - initial read Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/docs/tool-examples.md Example input for reading a note with revision protection. Returns an etag to use when editing. ```json { "vault": "work", "path": "Projects/Plan.md" } ``` -------------------------------- ### Start MCP server with custom recovery retention Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/README.md Start the MCP server with custom recovery retention settings. Overrides the default 30-day retention and 1 GiB prune threshold for completed transactions. ```bash obsidian-mcp serve --vault work=/path \ --recovery-days 14 \ --recovery-max-bytes 536870912 ``` -------------------------------- ### Run with npx Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/README.md Run the server with npx without installing globally. Pinning the major version receives compatible 2.x updates without crossing a future major version. ```bash npx -y obsidian-mcp@2 serve --vault notes=/absolute/path/to/vault ``` -------------------------------- ### Logger usage example Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/utility-helpers.md Example usage of the Logger with debug level. Logs an info event with fields; the comment shows the stderr output format. ```ts const logger = new Logger("debug"); logger.log("info", "transaction_committed", { transaction_id: id, vault: "work" }); // stderr: {"timestamp":"2026-…","level":"info","event":"transaction_committed","transaction_id":"…","vault":"work"} ``` -------------------------------- ### writeDiagnostic example Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/diagnostics.md Example call to writeDiagnostic with a warning diagnostic for a legacy MCP protocol. ```typescript writeDiagnostic("warning", { code: "LEGACY_MCP_PROTOCOL", problem: "The connected MCP client uses the 2025-era protocol.", detected: "A legacy initialize handshake was received.", fix: ["Upgrade the MCP client or host to one that negotiates MCP 2026-07-28."], verify: "Restart the MCP client and confirm the server appears and lists tools.", helpAnchor: "legacy-mcp-clients" }); ``` -------------------------------- ### Create note example (obsidian_create_note) Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/tools-notes.md Shows how to create a new note using the createCreateNoteTool factory. The execute call writes a new note at the given path, returning the etag and transaction_id. The note is never overwritten; if it exists, an ALREADY_EXISTS error is thrown. ```typescript const def = createCreateNoteTool(runtime); const { etag, transaction_id } = await def.execute( { vault: "work", path: "Inbox/Never.md", content: "# First", create_parents: true }, ctx ); ``` -------------------------------- ### Content search with continuation Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/tools-misc.md Example of a content search with continuation. It executes the tool with a query and limit, then if has_more is true, executes again with the next_cursor to fetch the next page. ```ts const def = createSearchVaultTool(runtime); const page = await def.execute( { vault: "work", query: "Obsidian", mode: "content", limit: 50, case_sensitive: false }, ctx ); const more = page.has_more ? await def.execute({ vault: "work", query: "Obsidian", mode: "content", limit: 50, cursor: page.next_cursor }, ctx) : undefined; ``` -------------------------------- ### Paginated search - initial call Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/docs/tool-examples.md Example input for paginated search. Repeat the same call with cursor set to next_cursor until has_more is false. ```json { "vault": "work", "query": "project/active", "mode": "tag", "limit": 50 } ``` -------------------------------- ### Development commands for obsidian-mcp Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/README.md Run the standard development workflow for the obsidian-mcp server: install dependencies, typecheck, test, build, and run the full CI suite. Requires Node.js and npm. ```bash npm ci npm run typecheck npm test npm run build npm run ci ``` -------------------------------- ### createListVaultsTool factory, execute, and usage example Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/tools-misc.md Factory signature for the read-only obsidian_list_vaults tool. The execute function returns the sorted vault ids from VaultRegistry.ids() and their count, never exposing host paths. The example shows invocation with an empty input object and an abort signal. ```typescript export function createListVaultsTool( runtime: Runtime ): ToolDefinition ``` ```typescript execute: () => { const vaults = runtime.registry.ids(); return Promise.resolve({ vaults, count: vaults.length }); } ``` ```typescript const def = createListVaultsTool(runtime); const { vaults, count } = await def.execute({}, { signal: abortSignal }); // vaults: e.g. ["personal", "work"] ``` -------------------------------- ### searchVault usage example with pagination Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/search.md Shows how to call searchVault for tag mode with pagination. The first call uses no cursor; if hasMore is true, a second call passes the opaque nextCursor to fetch the next page. ```typescript import { searchVault } from "./search.js"; const page1 = await searchVault(runtime.forVault("work").fs, { query: "project/active", mode: "tag", caseSensitive: false, limit: 50 }); if (page1.hasMore) { const page2 = await searchVault(fs, { query: "project/active", mode: "tag", caseSensitive: false, limit: 50, cursor: page1.nextCursor // opaque; bound to the query signature }); } ``` -------------------------------- ### Throw UserFacingError example Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/diagnostics.md Example of throwing a UserFacingError with a diagnostic for an unknown CLI option. Uses exit code 2 for usage errors. ```typescript throw new UserFacingError( { code: "CLI_UNKNOWN_OPTION", problem: "The command contains an unknown option.", detected: "--vaults", fix: ["Did you mean '--vault'?", "Run 'obsidian-mcp --help' to list supported options."], helpAnchor: "diagnostic-reference" }, 2 ); ``` -------------------------------- ### createCreateDirectoryTool factory, recursive usage, and ALREADY_EXISTS error handling Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/tools-misc.md Factory signature for the create obsidian_create_directory tool. The recursive example creates a nested directory path in one transaction. The error-handling example shows catching a ToolFailure with code ALREADY_EXISTS when the directory already exists. ```typescript export function createCreateDirectoryTool( runtime: Runtime ): ToolDefinition ``` ```typescript const def = createCreateDirectoryTool(runtime); const { path, transaction_id } = await def.execute( { vault: "work", path: "Projects/Orchid/Notes", recursive: true }, ctx ); ``` ```typescript try { await def.execute({ vault: "work", path: "Projects/Orchid", recursive: true }, ctx); } catch (error) { if (error instanceof ToolFailure && error.code === "ALREADY_EXISTS") { // the directory already exists — treat as no-op or different tool } } ``` -------------------------------- ### Create note error handling example (obsidian_create_note) Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/tools-notes.md Shows how to catch a ToolFailure with code ALREADY_EXISTS when creating a note that already exists. The comment suggests using obsidian_edit_note instead in that case. ```typescript try { await def.execute({ vault: "work", path: "Inbox/Never.md", content: "x" }, ctx); } catch (error) { if (error instanceof ToolFailure && error.code === "ALREADY_EXISTS") { // the note exists — use obsidian_edit_note instead } } ``` -------------------------------- ### sha256 usage example Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/utility-helpers.md Example usage of sha256 to compute an etag from a string. The result is a 64-character hex digest used as a revision guard. ```ts import { sha256 } from "./hash.js"; const etag = sha256(Buffer.from("# Hello")); // 64-hex revision guard ``` -------------------------------- ### Edit note example (obsidian_edit_note) Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/tools-notes.md Shows how to append content to an existing note using the createEditNoteTool factory. The if_match parameter must match the current etag to avoid a REVISION_CONFLICT. ```typescript const def = createEditNoteTool(runtime); const { etag } = await def.execute( { vault: "work", path: "Projects/Plan.md", operation: "append", content: "\n- next step\n", if_match: readEtag }, ctx ); ``` -------------------------------- ### searchVault error handling example Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/search.md Shows how to catch a ToolFailure with code INVALID_CURSOR when a stale or malformed cursor is passed. The comment indicates restarting the search without a cursor. ```typescript try { const page = await searchVault(fs, { query: "x", mode: "content", caseSensitive: false, limit: 50, cursor: staleCursor }); } catch (error) { if (error instanceof ToolFailure && error.code === "INVALID_CURSOR") { // restart the search without a cursor } } ``` -------------------------------- ### Creating a VaultRegistry with one vault Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/vault.md Example of creating a VaultRegistry with a single vault definition and logging the sorted IDs. The root path must be absolute and the vault must be initialized. ```typescript const registry = await VaultRegistry.create([ { id: "work", root: "/Users/me/Documents/WorkVault" } ]); console.log(registry.ids()); // ["work"] ``` -------------------------------- ### Unified add → remove example for createManageTagsTool Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/tools-tags.md Shows how to execute both add and remove operations using the same tool definition. The result of the remove operation has transaction_id equal to null when the file has no matching tag. ```ts const def = createManageTagsTool(runtime); await def.execute({ operation: "add", vault: "work", paths: ["A.md"], tags: ["x"], location: "both" }, ctx); const result = await def.execute({ operation: "remove", vault: "work", paths: ["A.md"], tags: ["x"] }, ctx); // result.transaction_id === null when "A.md" had no matching tag ``` -------------------------------- ### Example: calling restoreRecovery and handling REVISION_CONFLICT Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/transaction.md Example usage of restoreRecovery in a try-catch block. It calls the method with a transaction ID and catches a ToolFailure error with code REVISION_CONFLICT, indicating that the content changed since commit and the restore refuses to overwrite. ```typescript try { const newId = await tm.restoreRecovery("3f2f1e5a-…"); } catch (error) { if (error instanceof ToolFailure && error.code === "REVISION_CONFLICT") { // content changed since commit — restore refuses to overwrite } } ``` -------------------------------- ### Handle UserFacingError from runCli Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/cli.md Example of catching UserFacingError from runCli and writing the diagnostic code and problem to stderr. ```ts import { runCli } from "./cli.js"; import { UserFacingError } from "./utils/diagnostics.js"; try { await runCli(["serve", "--vault", "notes=/absolute/path"]); } catch (error) { if (error instanceof UserFacingError) { // error.diagnostic.code is e.g. "CLI_UNKNOWN_OPTION"; exitCode is 1 or 2 process.stderr.write(`${error.diagnostic.code}: ${error.diagnostic.problem}\n`); } } ``` -------------------------------- ### Error handling example for add tags Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/tools-tags.md Demonstrates catching a ToolFailure with code INVALID_ARGUMENT when a tag contains a space. Tags are validated at execution time. ```typescript try { await def.execute({ vault: "work", paths: ["Projects/Orchid.md"], tags: ["bad tag"] }, ctx); } catch (error) { if (error instanceof ToolFailure && error.code === "INVALID_ARGUMENT") { // tag contains a space — tags are validated at execution } } ``` -------------------------------- ### Migrate obsidian MCP configuration from v1 to v2 Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/MIGRATING.md Shows the old v1 configuration and the new v2 configuration for the obsidian MCP server. The v2 configuration replaces the positional vault path with the `serve --vault id=/absolute/path` arguments. For a global install, use `"command": "obsidian-mcp"` and begin `args` with `"serve"`. For multiple vaults, repeat `"--vault", "id=/absolute/path"`. ```json { "mcpServers": { "obsidian": { "command": "npx", "args": ["-y", "obsidian-mcp", "/absolute/path/to/vault"] } } } ``` ```json { "mcpServers": { "obsidian": { "command": "npx", "args": ["-y", "obsidian-mcp", "serve", "--vault", "notes=/absolute/path/to/vault"] } } } ``` -------------------------------- ### Embedding buildServer in a custom application Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/server.md Example of embedding buildServer in a custom application. It creates a VaultRegistry, initializes a Runtime with recovery settings and a logger, then calls buildServer to obtain an McpServer with tools and resources registered. ```ts import { buildServer } from "./server.js"; import { Runtime } from "./runtime.js"; import { VaultRegistry } from "./utils/vault.js"; import { Logger } from "./utils/logger.js"; const registry = await VaultRegistry.create([{ id: "notes", root: "/absolute/path/to/vault" }]); const runtime = new Runtime( registry, { recoveryDays: 30, recoveryMaxBytes: 1024 * 1024 * 1024 }, new Logger("info") ); await runtime.initialize(); const server = buildServer(runtime); // McpServer, tools + resource registered ``` -------------------------------- ### restoreRecovery(id) Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/transaction.md Documentation for the restoreRecovery method, including its signature, parameters, behavior, return type, example usage, and error conditions. ```APIDOC ## restoreRecovery(id) ### Description Restores a transaction from a recovery snapshot by building a reverse `PlannedChange` list and committing it as a new transaction. Validates that the recovery entry is committed and available, and that the current filesystem state matches the recorded snapshots before applying changes. ### Method async function ### Signature `async restoreRecovery(id: string): Promise` ### Parameters - `id` (string) - Required - Transaction UUID, validated by `/^[0-9a-f-]{36}$/u`. ### Behavior - Builds a reverse `PlannedChange` list from the recovery snapshots. - For each snapshot (reversed), targets are re-checked: - `mkdir` directories must still be directories. - `rmdir` destinations must still be absent. - Files must match the recorded `committedEtag` (or be absent when `committedEtag` is undefined). - If a check fails, rejects with `ToolFailure("REVISION_CONFLICT", …)` with messages: - "A recovered file has changed since the transaction completed." - "A recovery destination now exists; refusing to overwrite it." - If a snapshot is missing for a previously-existing file, rejects with `TRANSACTION_FAILED` ("Recovery snapshot is missing."). - If the change list is empty, rejects with `INVALID_ARGUMENT` ("Recovery entry has no restorable changes."). - If the id is not committed or unknown, rejects with `INVALID_ARGUMENT` ("Recovery entry is unavailable or incomplete."). ### Returns `Promise` - The new (recovery) transaction id, committing via `this.run(changes)`. ### Example ```ts try { const newId = await tm.restoreRecovery("3f2f1e5a-…"); } catch (error) { if (error instanceof ToolFailure && error.code === "REVISION_CONFLICT") { // content changed since commit — restore refuses to overwrite } } ``` ### Throws/Rejects - `ToolFailure` with codes: `INVALID_ARGUMENT`, `REVISION_CONFLICT`, `TRANSACTION_FAILED`. - All codes from `run` (e.g., `LOCK_TIMEOUT`). ``` -------------------------------- ### Error handling example for remove operation Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/tools-tags.md Demonstrates a try-catch block for the remove operation when both tags and patterns are empty. The schema refine throws an error requiring tags or patterns. ```ts try { await def.execute({ operation: "remove", vault: "work", paths: ["A.md"], tags: [], patterns: [] }, ctx); } catch (error) { // operation "remove" requires tags or patterns (schema refine) } ``` -------------------------------- ### Move note with link update using createMoveNoteTool Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/tools-notes.md Example of moving a note from 'Drafts/Plan.md' to 'Projects/Plan.md' with update_links set to true. The result includes ambiguous_links, which are links left unchanged. Requires a runtime and context (ctx) with a valid vault. ```typescript const def = createMoveNoteTool(runtime); const result = await def.execute( { vault: "work", source: "Drafts/Plan.md", destination: "Projects/Plan.md", update_links: true, if_match: readEtag }, ctx ); console.log(result.ambiguous_links); // links left unchanged ``` -------------------------------- ### Example: run doctor and print recovery entries Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/runtime.md Runs the doctor check and logs each vault's recovery entry count. The report includes `readable` and `writable` booleans that are always `true` after a successful access check. ```ts const report = await runtime.doctor(); for (const entry of report) console.log(`${entry.vault}: ${entry.recovery_entries} recovery entries`); ``` -------------------------------- ### Read vault resource with MCP client Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/tools-misc.md Example of reading the vault resource using the MCP client. It parses the response text and iterates over the vaults to log their id and capabilities. ```ts const response = await client.readResource({ uri: "obsidian-mcp://vaults" }); const vaults = JSON.parse(response.contents[0].text as string).vaults; for (const v of vaults) console.log(v.id, v.capabilities); ``` -------------------------------- ### Catch and convert tool errors with asToolFailure Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/errors.md Example of catching errors in consumer code for internal tool authors. It imports ToolFailure and asToolFailure from "./errors.js", calls asToolFailure with a context message, checks the failure code for NOTE_NOT_FOUND to surface a corrective message, and rethrows the failure. ```ts import { ToolFailure, asToolFailure } from "./errors.js"; try { await service.fs.readText(entry); } catch (error) { const failure = asToolFailure(error, "read the note"); if (failure.code === "NOTE_NOT_FOUND") { // path does not exist — surface a corrective message } throw failure; } ``` -------------------------------- ### Remove tags error handling Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/tools-tags.md Example of error handling when no tags or patterns are provided. The schema refine error is reported by the SDK before the handler runs. ```typescript try { await def.execute({ vault: "work", paths: ["Projects/Orchid.md"], tags: [], patterns: [] }, ctx); } catch (error) { // schema refine error: "At least one tag or pattern is required for a remove operation." // — reported by the SDK before the handler runs } ``` -------------------------------- ### mutateTags add to frontmatter example Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/tags.md Example of using mutateTags to add a tag to the frontmatter of a note. It imports the function, calls it with the note text and options for adding 'project/active' to the frontmatter, and destructures the result to get the modified text and changed tags. ```TypeScript import { mutateTags } from "./tags.js"; const { text, changed } = mutateTags(note, { operation: "add", tags: ["project/active"], location: "frontmatter", normalization: "preserve" }); ``` -------------------------------- ### Delete note with trash mode and backlink marking Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/tools-notes.md Example of using createDeleteNoteTool to delete a note in trash mode with backlink_action set to mark_broken. The result includes a trash_id for recovery, and trash bytes are stored under .obsidian-mcp/trash. ```typescript const def = createDeleteNoteTool(runtime); const result = await def.execute( { vault: "work", path: "Drafts/Old.md", mode: "trash", backlink_action: "mark_broken", reason: "superseded" }, ctx ); // result.trash_id — recover via 'recovery' only for transactions; trash bytes live under .obsidian-mcp/trash ``` -------------------------------- ### Edit note error handling example (obsidian_edit_note) Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/tools-notes.md Shows how to catch a REVISION_CONFLICT error when the etag is stale. The comment indicates the operation is retryable: re-read the note and retry with the fresh etag. ```typescript try { await def.execute({ vault: "work", path: "Plan.md", operation: "replace", content: "x", if_match: stale }, ctx); } catch (error) { if (error instanceof ToolFailure && error.code === "REVISION_CONFLICT") { // re-read and retry with the fresh etag (retryable: true) } } ``` -------------------------------- ### Calling a tool and handling error path Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/tool-factory.md Full handling example showing how to call a tool and process an error result. When result.isError is true, structuredContent contains { ok: false, error: { code: "REVISION_CONFLICT", … } } and you can access error.code and error.retryable. ```typescript const result = await client.callTool({ name: "obsidian_edit_note", arguments: { vault: "work", path: "Plan.md", operation: "append", content: "\nx", if_match: "wrong-etag…" } }); if (result.isError) { const wrapped = result.structuredContent; // { ok: false, error: { code: "REVISION_CONFLICT", … } } console.error(wrapped.error.code, wrapped.error.retryable); } ``` -------------------------------- ### MCP client configuration Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/README.md Configure an MCP client to launch the same command over stdio. ```json { "mcpServers": { "obsidian": { "command": "npx", "args": ["-y", "obsidian-mcp@2", "serve", "--vault", "notes=/absolute/path/to/vault"] } } } ``` -------------------------------- ### mutateTags error handling example Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/tags.md Example of error handling when calling mutateTags with an invalid tag containing a space. It wraps the call in a try-catch block and checks for a ToolFailure error with code 'INVALID_ARGUMENT'. ```TypeScript try { mutateTags(note, { operation: "remove", tags: ["bad tag"], location: "both", normalization: "preserve" }); } catch (error) { if (error instanceof ToolFailure && error.code === "INVALID_ARGUMENT") { // tag contains a space } } ``` -------------------------------- ### Module Graph (dist/main.js to Internals) Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/README.md Shows the module dependency graph from the CLI bootstrap to internal modules, including the server, tools, and resources. Use to understand the code structure and dependencies. ```text dist/main.js (CLI bootstrap, src/main.ts) └─ cli.ts: runCli / parseArguments ├─ constants.ts ├─ utils/diagnostics.ts (UserFacingError, writeDiagnostic) ├─ utils/logger.ts (Logger) ├─ utils/vault.ts (VaultRegistry.create) ├─ runtime.ts (Runtime) ─┬─ utils/vault.ts (VaultFs) │ └─ utils/transaction.ts (TransactionManager) ├─ server.ts (buildServer) │ ├─ tools/index.ts (registerTools) ─┬─ 12 × tools//index.ts (factory) │ │ │ ├─ utils/schemas.ts, utils/errors.ts │ │ │ ├─ utils/tool-factory.ts (registerTool) │ │ │ ├─ utils/validation.ts │ │ │ ├─ utils/tags.ts / utils/search.ts / utils/links.ts │ │ │ ├─ utils/transaction.ts (PlannedChange) │ │ │ └─ tools/shared/tag-mutation.ts │ └─ resources/index.ts (registerVaultResource, "obsidian-mcp://vaults") └─ @modelcontextprotocol/server/stdio (StdioServerTransport, serveStdio) ``` -------------------------------- ### listRecovery Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/transaction.md Lists transaction-root directories, reads each manifest, and returns entries with file counts, sorted newest-first by creation time. ```APIDOC ## listRecovery ### Description Lists transaction-root directories, reads each manifest, and returns entries with file counts, sorted newest-first by creation time. ### Method listRecovery ### Signature `async listRecovery(): Promise<{ id: string; state: Manifest["state"]; created_at: string; completed_at?: string; files: number; }[]>` ### Returns `Promise>` - Array of transaction recovery entries, sorted newest-first by `created_at` localeCompare. `state` ∈ `"preparing" | "committing" | "committed" | "rolled_back"`. ``` -------------------------------- ### helpText output for obsidian-mcp --help Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/cli.md Canonical usage text printed for --help. Lists serve, doctor, and recovery subcommands, deprecated v1 positional syntax, and all options with defaults (recovery-days 30, recovery-max-bytes 1073741824, legacy serve). ```text obsidian-mcp Usage: obsidian-mcp serve --vault = [--vault ...] [--legacy serve|reject] obsidian-mcp doctor --vault = [--vault ...] obsidian-mcp recovery list --vault = [--vault ...] obsidian-mcp recovery restore --vault = --id Compatibility: obsidian-mcp [vault-path ...] Deprecated v1 syntax; prints replacement args Options: --vault = Configure one vault (required, repeatable, maximum 10) --recovery-days Completed journal retention (default: 30) --recovery-max-bytes Recovery storage limit (default: 1073741824) --log-level error, warn, info, or debug --legacy 2025-era client handling: serve (default) or reject --help Show help --version Show version ``` -------------------------------- ### TransactionManager.initialize method Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/transaction.md Initializes the transaction manager by creating required directories, acquiring the write lock, running recovery and pruning, then releasing the lock. ```typescript async initialize(): Promise ``` -------------------------------- ### Rename tag error handling Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/tools-tags.md Example of error handling when the new tag contains invalid characters. The error is caught and checked for INVALID_ARGUMENT. ```typescript try { await def.execute({ vault: "work", old_tag: "project/orchid", new_tag: "x//y" }, ctx); } catch (error) { if (error instanceof ToolFailure && error.code === "INVALID_ARGUMENT") { // "//" is rejected by validateTag } } ``` -------------------------------- ### Entry point error handling with UserFacingError Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/main.md Error handling in the entry point: catches exceptions from runCli, writes a UserFacingError diagnostic or a STARTUP_FAILED diagnostic, and sets the process exit code. Appends the stack trace only when the literal "debug" is present in process.argv. ```ts const { runCli } = await import("./cli.js"); try { await runCli(); } catch (error: unknown) { const { UserFacingError, writeDiagnostic } = await import("./utils/diagnostics.js"); if (error instanceof UserFacingError) { writeDiagnostic("error", error.diagnostic); process.exitCode = error.exitCode; } else { const message = error instanceof Error ? error.message : String(error); writeDiagnostic("error", { code: "STARTUP_FAILED", problem: "Obsidian MCP could not start.", detected: message, fix: [ "Review the detected error and correct the configured vault or command.", "Run the same vault configuration with 'doctor' to validate it outside the MCP client." ], helpAnchor: "diagnostic-reference" }); if (process.argv.includes("debug") && error instanceof Error && error.stack !== undefined) { process.stderr.write(`${error.stack}\n`); } process.exitCode = 1; } } ``` -------------------------------- ### Read note error handling: INVALID_CURSOR Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/tools-notes.md Example of handling a ToolFailure with code INVALID_CURSOR when the cursor is stale or malformed. Re-read without a cursor is suggested. ```typescript try { await def.execute({ vault: "work", path: "Plan.md", cursor: staleCursor, max_chars: 5000 }, ctx); } catch (error) { if (error instanceof ToolFailure && error.code === "INVALID_CURSOR") { // note changed or cursor malformed — re-read without a cursor } } ``` -------------------------------- ### Rename tag with children Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/tools-tags.md Example of using createRenameTagTool to rename a tag across the vault, including children. The result contains the updated notes with per-note replacement counts. ```typescript const def = createRenameTagTool(runtime); const result = await def.execute( { vault: "work", old_tag: "project/orchid", new_tag: "product/release", include_children: true }, ctx ); // result.updated — every note touched, with per-note replacement counts ``` -------------------------------- ### buildServer(runtime: Runtime): McpServer Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/server.md Builds and returns an McpServer instance with identity, instructions, cache hints, and registered tools and resources. This function is called per connection to ensure protocol-era isolation. ```APIDOC ## buildServer(runtime: Runtime): McpServer ### Description Constructs an McpServer instance with the provided runtime, setting identity, instructions, cache hints, and registering all tools and the vaults resource. ### Method buildServer ### Endpoint src/server.ts:8 ### Parameters #### Parameters - **runtime** (Runtime) - Required - Fully initialized runtime created by runCli after VaultRegistry.create and Runtime.initialize. ### Returns - **McpServer** - An instance from @modelcontextprotocol/server with identity, instructions, cache hints, and registered tools and resources. ### Registration Steps 1. registerTools(server, runtime) - registers all 12 tools 2. registerResources(server, runtime) - registers the obsidian-mcp://vaults resource ### Usage Example ```ts import { buildServer } from "./server.js"; import { Runtime } from "./runtime.js"; import { VaultRegistry } from "./utils/vault.js"; import { Logger } from "./utils/logger.js"; const registry = await VaultRegistry.create([{ id: "notes", root: "/absolute/path/to/vault" }]); const runtime = new Runtime( registry, { recoveryDays: 30, recoveryMaxBytes: 1024 * 1024 * 1024 }, new Logger("info") ); await runtime.initialize(); const server = buildServer(runtime); // McpServer, tools + resource registered ``` ### Error Handling Never throws directly; per-connection construction happens inside the serveStdio callback in src/cli.ts, and tool/resource handler failures are converted into MCP error results by registerTool. ### Architecture Note buildServer is called per connection (the serveStdio callback in src/cli.ts), guaranteeing protocol-era isolation: a 2025-era and a 2026-07-28 client each get their own registered McpServer over the same Runtime. ``` -------------------------------- ### searchVault Source: https://github.com/stevenstavrakis/obsidian-mcp/blob/main/_autodocs/api-reference/search.md Performs a deterministic, bounded, cursor-paginated search over note filenames, content, and tags. Returns a page of matches along with a cursor for fetching subsequent pages. ```APIDOC ## searchVault ### Description Performs a deterministic, bounded, cursor-paginated search over note filenames, content, and tags. Returns a page of matches along with a cursor for fetching subsequent pages. ### Method async function ### Signature ```ts export async function searchVault( vaultFs: VaultFs, input: { query: string; scope?: string; mode: SearchMode; caseSensitive: boolean; limit: number; cursor?: string; signal?: AbortSignal; } ): Promise<{ matches: SearchMatch[]; hasMore: boolean; nextCursor?: string; warnings: string[] }> ``` ### Parameters #### vaultFs (VaultFs) - **vaultFs** (VaultFs) - Required - Filesystem facade #### input.query (string) - **query** (string) - Required - Substring to find (or tag equality / `tag/…` prefix in `tag` mode) #### input.scope (string) - **scope** (string) - Optional - Directory limiting the scan. Default: `undefined` (whole vault) #### input.mode (SearchMode) - **mode** (SearchMode) - Required - `"content"` | `"filename"` | `"both"` | `"tag"` #### input.caseSensitive (boolean) - **caseSensitive** (boolean) - Required - Exact-case matching #### input.limit (number) - **limit** (number) - Required - Maximum matches per page #### input.cursor (string) - **cursor** (string) - Optional - Opaque `next_cursor` from a previous call. Default: `undefined` #### input.signal (AbortSignal) - **signal** (AbortSignal) - Optional - Cancellation: aborted searches throw retryable `FILESYSTEM_ERROR` ("Search was cancelled."). Default: `undefined` ### Returns - **matches** (SearchMatch[]) - This page, file order then line order - **hasMore** (boolean) - `next !== undefined` - **nextCursor** (string) - base64url cursor — present iff `hasMore` - **warnings** (string[]) - Skipped-note messages ### Algorithm 1. Computes `signature = cursorSignature(input)` — base64url of `JSON.stringify([query, scope ?? "", mode, caseSensitive])`. 2. New searches start from `{ version: 1, signature, file: 0, match: 0 }`; continuations decode the cursor (`decodeCursor`, private). A signature mismatch → `ToolFailure("INVALID_CURSOR", "Search cursor does not match this query.")`; malformed payloads → `"Search cursor is invalid or malformed."` (with cause). 3. `vaultFs.listMarkdown(scope)` lists candidates (already sorted, `.md` only, dot/symlink-filtered). 4. Per file (`matchesForFile`, private): `resolveExisting` + `readText`; matches produced per mode: - `filename`/`both` — path includes query (case per option) → `{ kind: "filename", line: 0, snippet: relativePath }`; - `content`/`both` — line includes query → `{ kind: "content", line: index + 1, snippet: clip(line.trim(), 300) }`; - `tag` — tag equals query or starts with `query + "/"` (case per option) → `{ kind: "tag", line: occurrence.line ?? 0, snippet: "#" }`. 5. Unreadable files (any exception from read) are skipped and reported in `warnings` as `"Skipped unreadable note: "`. 6. Pagination stops a page when adding the next match would exceed `limit` **or** when the JSON-serialized candidate page would exceed `MAX_RESPONSE_CHARACTERS - 2_000` (25 000 - 2 000 = 23 000); the stop point is encoded into `next`. ### Request Example ```ts import { searchVault } from "./search.js"; const page1 = await searchVault(runtime.forVault("work").fs, { query: "project/active", mode: "tag", caseSensitive: false, limit: 50 }); if (page1.hasMore) { const page2 = await searchVault(fs, { query: "project/active", mode: "tag", caseSensitive: false, limit: 50, cursor: page1.nextCursor // opaque; bound to the query signature }); } ``` ### Error Handling Example ```ts try { const page = await searchVault(fs, { query: "x", mode: "content", caseSensitive: false, limit: 50, cursor: staleCursor }); } catch (error) { if (error instanceof ToolFailure && error.code === "INVALID_CURSOR") { // restart the search without a cursor } } ``` ### Throws/Rejects - `ToolFailure` `INVALID_CURSOR` (mismatched/malformed cursor) - `FILESYSTEM_ERROR` (aborted — retryable) - `PATH_REJECTED`/`SYMLINK_NOT_ALLOWED`/`NOTE_NOT_FOUND`/`INVALID_ENCODING` from the underlying `resolveExisting`/`readText` when they escape the per-file catch (scope resolution and other top-level calls). ```