Skip to main content
Glama
jagoff

obsidian-mcp-complete

by jagoff

obsidian_regex_replace

Perform regex or literal find-and-replace across the Obsidian vault with dry-run previews to verify changes before applying.

Instructions

Regex or literal find-and-replace across the vault with dry-run previews by default.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
vaultNoOptional configured vault name. Defaults to the server default vault.
searchYes
replaceYes
regexNo
caseSensitiveNo
wholeWordNo
flexibleWhitespaceNo
pathPrefixNo
dryRunNo
limitNo

Implementation Reference

  • src/tools.ts:548-564 (registration)
    Tool registration for obsidian_regex_replace in registerObsidianTools(). Defines Zod schema for inputs and delegates to regexReplaceAcrossVault().
    tool(
      "obsidian_regex_replace",
      "Regex or literal find-and-replace across the vault with dry-run previews by default.",
      {
        vault: vaultArg,
        search: z.string(),
        replace: z.string(),
        regex: z.boolean().optional().default(true),
        caseSensitive: z.boolean().optional().default(false),
        wholeWord: z.boolean().optional().default(false),
        flexibleWhitespace: z.boolean().optional().default(false),
        pathPrefix: z.string().optional(),
        dryRun: z.boolean().optional().default(true),
        limit: z.number().int().min(1).max(5000).optional().default(1000),
      },
      async (args) => regexReplaceAcrossVault(vaults, args.vault, args),
    );
  • Core handler: iterates vault markdown files, applies regex/literal pattern using buildSearchPattern, counts replacements, optionally writes changes or returns preview diff.
    export async function regexReplaceAcrossVault(
      vaults: VaultManager,
      vault: string | undefined,
      options: {
        search: string;
        replace: string;
        regex?: boolean;
        caseSensitive?: boolean;
        wholeWord?: boolean;
        flexibleWhitespace?: boolean;
        pathPrefix?: string;
        dryRun?: boolean;
        limit?: number;
      },
    ): Promise<{ changed: RegexReplaceResult[]; totalReplacements: number; dryRun: boolean }> {
      const files = await vaults.markdownFiles(vault);
      const pattern = buildSearchPattern(options);
      const flags = `g${options.caseSensitive ? "" : "i"}`;
      const re = new RegExp(pattern, flags);
      const changed: RegexReplaceResult[] = [];
      let totalReplacements = 0;
      for (const file of files) {
        if (options.pathPrefix && !file.toLowerCase().startsWith(options.pathPrefix.toLowerCase())) continue;
        const read = await vaults.readText(file, vault);
        let count = 0;
        const next = read.text.replace(re, (...parts) => {
          count += 1;
          return options.replace;
        });
        if (count === 0) continue;
        totalReplacements += count;
        changed.push({
          path: read.path,
          replacements: count,
          preview: options.dryRun ? previewDiff(read.text, next) : undefined,
        });
        if (!options.dryRun) await vaults.writeText(read.path, next, vault, { overwrite: true });
        if (changed.length >= (options.limit ?? 1000)) break;
      }
      return { changed, totalReplacements, dryRun: options.dryRun ?? true };
    }
  • Type definition for the result of each file processed by regexReplaceAcrossVault.
    export type RegexReplaceResult = {
      path: string;
      replacements: number;
      preview?: string;
    };
  • Helper to build the RegExp pattern string from options (regex literal, flexible whitespace, whole word).
    function buildSearchPattern(options: { search: string; regex?: boolean; wholeWord?: boolean; flexibleWhitespace?: boolean }): string {
      let pattern = options.regex ? options.search : escapeRegExp(options.search);
      if (!options.regex && options.flexibleWhitespace) pattern = pattern.replace(/\\\s+/g, "\\s+").replace(/\s+/g, "\\s+");
      if (options.wholeWord) pattern = `\\b(?:${pattern})\\b`;
      return pattern;
    }
  • Helper to produce a unified-diff-style preview of changes (up to 20 lines).
    function previewDiff(before: string, after: string): string {
      const beforeLines = before.split("\n");
      const afterLines = after.split("\n");
      const out: string[] = [];
      const max = Math.max(beforeLines.length, afterLines.length);
      for (let i = 0; i < max && out.length < 20; i += 1) {
        if (beforeLines[i] !== afterLines[i]) {
          if (beforeLines[i] !== undefined) out.push(`-${beforeLines[i]}`);
          if (afterLines[i] !== undefined) out.push(`+${afterLines[i]}`);
        }
      }
      return out.join("\n");
    }
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Annotations are neutral (readOnlyHint false, destructiveHint false). The description adds behavioral context: dry-run previews by default, implying actual replacement occurs only when dryRun is false. This is valuable beyond annotations.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Single sentence, front-loaded with key information (regex/literal, vault-wide, dry-run). No extraneous content.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Missing return value format (list of changes? count?). Does not specify whether it applies to all files or specific pathPrefix. With no output schema, the description should clarify output structure.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is only 10% (only 'vault' described). The description does not explain parameters like caseSensitive, wholeWord, flexibleWhitespace, pathPrefix, or limit. It fails to compensate for low schema coverage.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's function: 'Regex or literal find-and-replace across the vault' with a key feature 'dry-run previews by default'. It distinguishes from sibling tools like obsidian_replace_in_note by specifying vault-wide scope.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies vault-wide usage but does not explicitly state when to use this tool vs alternatives like obsidian_replace_in_note (per-note). No when-not or exclusion guidance is provided.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/jagoff/obsidian-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server