Skip to main content
Glama

search_by_tag

Search for notes containing a specific tag in Obsidian vaults, with options to preview content and limit results.

Instructions

Find all notes that contain a specific tag

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
tagYesTag to search for (with or without # prefix)
includeContentNoIf true, include first 200 characters of note content as a preview
maxResultsNoMaximum number of results

Implementation Reference

  • The handler function that implements the logic for 'search_by_tag', including searching for tags in note content and returning the matching results.
    async ({ tag, includeContent, maxResults }) => {
      try {
        const searchTag = tag.replace(/^#/, "").toLowerCase();
        const notes = await listNotes(vaultPath);
        const matchingNotes: { path: string; preview?: string }[] = [];
    
        for (const notePath of notes) {
          if (matchingNotes.length >= maxResults) break;
    
          let content: string;
          try {
            content = await readNote(vaultPath, notePath);
          } catch (err) {
            console.error(`Failed to read note for tag search: ${notePath}`, err);
            continue;
          }
    
          const tags = extractTags(content);
          const hasMatch = tags.some((t) => {
            const normalized = t.toLowerCase();
            return normalized === searchTag || normalized.startsWith(`${searchTag}/`);
          });
    
          if (hasMatch) {
            const entry: { path: string; preview?: string } = { path: notePath };
            if (includeContent) {
              entry.preview = content.slice(0, 200).trim();
            }
            matchingNotes.push(entry);
          }
        }
    
        if (matchingNotes.length === 0) {
          return {
            content: [
              { type: "text" as const, text: `No notes found with tag #${searchTag}` },
            ],
          };
        }
    
        const lines: string[] = [];
        lines.push(`Found ${matchingNotes.length} ${matchingNotes.length === 1 ? "note" : "notes"} with tag #${searchTag}`);
        lines.push("");
    
        for (const note of matchingNotes) {
          lines.push(`- ${note.path}`);
          if (note.preview) {
            lines.push(`  ${note.preview}`);
            lines.push("");
          }
        }
    
        return {
          content: [{ type: "text" as const, text: lines.join("\n") }],
        };
      } catch (err) {
        console.error("Error in search_by_tag:", err);
        return errorResult(`Error searching by tag: ${err instanceof Error ? err.message : String(err)}`);
      }
    },
  • The schema definition (inputSchema) for the 'search_by_tag' tool.
    {
      description: "Find all notes that contain a specific tag",
      inputSchema: {
        tag: z.string().describe("Tag to search for (with or without # prefix)"),
        includeContent: z
          .boolean()
          .optional()
          .default(false)
          .describe("If true, include first 200 characters of note content as a preview"),
        maxResults: z.number().optional().default(100).describe("Maximum number of results"),
      },
    },
  • The registration call for the 'search_by_tag' tool within the McpServer instance.
    server.registerTool(
      "search_by_tag",
      {
        description: "Find all notes that contain a specific tag",
        inputSchema: {
          tag: z.string().describe("Tag to search for (with or without # prefix)"),
          includeContent: z
            .boolean()
            .optional()
            .default(false)
            .describe("If true, include first 200 characters of note content as a preview"),
          maxResults: z.number().optional().default(100).describe("Maximum number of results"),
        },
      },
      async ({ tag, includeContent, maxResults }) => {
        try {
          const searchTag = tag.replace(/^#/, "").toLowerCase();
          const notes = await listNotes(vaultPath);
          const matchingNotes: { path: string; preview?: string }[] = [];
    
          for (const notePath of notes) {
            if (matchingNotes.length >= maxResults) break;
    
            let content: string;
            try {
              content = await readNote(vaultPath, notePath);
            } catch (err) {
              console.error(`Failed to read note for tag search: ${notePath}`, err);
              continue;
            }
    
            const tags = extractTags(content);
            const hasMatch = tags.some((t) => {
              const normalized = t.toLowerCase();
              return normalized === searchTag || normalized.startsWith(`${searchTag}/`);
            });
    
            if (hasMatch) {
              const entry: { path: string; preview?: string } = { path: notePath };
              if (includeContent) {
                entry.preview = content.slice(0, 200).trim();
              }
              matchingNotes.push(entry);
            }
          }
    
          if (matchingNotes.length === 0) {
            return {
              content: [
                { type: "text" as const, text: `No notes found with tag #${searchTag}` },
              ],
            };
          }
    
          const lines: string[] = [];
          lines.push(`Found ${matchingNotes.length} ${matchingNotes.length === 1 ? "note" : "notes"} with tag #${searchTag}`);
          lines.push("");
    
          for (const note of matchingNotes) {
            lines.push(`- ${note.path}`);
            if (note.preview) {
              lines.push(`  ${note.preview}`);
              lines.push("");
            }
          }
    
          return {
            content: [{ type: "text" as const, text: lines.join("\n") }],
          };
        } catch (err) {
          console.error("Error in search_by_tag:", err);
          return errorResult(`Error searching by tag: ${err instanceof Error ? err.message : String(err)}`);
        }
      },
    );
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. While 'Find' implies a read-only operation, the description doesn't specify whether this requires authentication, has rate limits, returns paginated results, or what format the results take. For a search tool with zero annotation coverage, this leaves significant behavioral questions unanswered.

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?

The description is a single, efficient sentence that directly states the tool's purpose without unnecessary words. It's appropriately sized for a straightforward search tool and front-loads the core functionality.

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

Completeness2/5

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

Given the lack of annotations and output schema, the description is incomplete. While the purpose is clear, there's no information about what the tool returns (note metadata, full content, IDs only), error conditions, or behavioral constraints. For a search tool that likely returns structured results, this leaves the agent guessing about the response format.

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

Parameters3/5

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

Schema description coverage is 100%, so the schema fully documents all three parameters. The description doesn't add any parameter semantics beyond what's in the schema - it mentions 'specific tag' which aligns with the 'tag' parameter but provides no additional context about format, validation, or usage patterns. This meets the baseline for high schema coverage.

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

Purpose4/5

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

The description clearly states the tool's purpose: 'Find all notes that contain a specific tag' - a specific verb ('Find') and resource ('notes') with a clear criterion ('contain a specific tag'). However, it doesn't differentiate from sibling tools like 'search_notes' or 'search_by_frontmatter', which likely have overlapping search functionality but different filtering criteria.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives. There's no mention of when this tool is appropriate versus 'search_notes', 'search_by_frontmatter', or 'get_tags', nor any prerequisites or exclusions. The agent must infer usage from the tool name alone.

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/rps321321/obsidian-mcp-pro'

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