Skip to main content
Glama

search_notes

Find relevant notes with BM25 full-text search. Optionally narrow by directory or decide whether to search body or frontmatter.

Instructions

Full-text BM25 search. Pass { query } and optionally scope (path prefix), searchContent (default true), searchFrontmatter (default false), limit. Returns { root, results[] } sorted by relevance, each with path, score, excerpt.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The main tool handler for 'search_notes'. Calls SearchServiceImpl.search() with parsed query, scope, searchContent, searchFrontmatter, limit options. Returns results as JSON with root path.
    function makeSearchNotesTool(container: ServiceContainer): ToolHandler {
      return {
        name: "search_notes",
        description:
          "Full-text BM25 search. Pass `{ query }` and optionally `scope` (path prefix), `searchContent` (default true), `searchFrontmatter` (default false), `limit`. Returns `{ root, results[] }` sorted by relevance, each with `path`, `score`, `excerpt`.",
        inputSchema: SearchNotesSchema,
        async handler(args): Promise<ToolResponse> {
          try {
            const services = requireServices(container);
            const { query, scope, searchContent, searchFrontmatter, limit } =
              SearchNotesSchema.parse(args);
            log.info({ query, scope, searchContent, searchFrontmatter, limit }, "search_notes called");
            const results = await services.search.search(query, {
              scope,
              searchContent,
              searchFrontmatter,
              limit,
            });
            log.info({ query, resultCount: results.length }, "search_notes complete");
            return {
              content: [{ type: "text", text: JSON.stringify({ root: getRoot(container), results }, null, 2) }],
            };
          } catch (err) {
            log.error({ err }, "search_notes failed");
            return {
              content: [{ type: "text", text: JSON.stringify({
                root: getRoot(container),
                error: err instanceof Error ? err.message : String(err),
                possibleSolutions: ["Try a different search query", "Use list_directory to browse the directory structure", "Check the scope path exists with list_directory"],
              }) }],
              isError: true,
            };
          }
        },
      };
    }
  • Zod input schema for 'search_notes': defines query (string, required), scope (optional path prefix), searchContent (boolean, default true), searchFrontmatter (boolean, default false), and limit (optional positive int).
    const SearchNotesSchema = z.object({
      query: z
        .string()
        .describe("Full-text search query. Supports multiple words; results ranked by BM25."),
      scope: z
        .string()
        .optional()
        .describe(
          "Root-relative path prefix to restrict the search scope. Omit to search the entire directory.",
        ),
      searchContent: z
        .boolean()
        .optional()
        .default(true)
        .describe("Search within note body content. Default: true."),
      searchFrontmatter: z
        .boolean()
        .optional()
        .default(false)
        .describe("Search within frontmatter field values. Default: false."),
      limit: z
        .number()
        .int()
        .positive()
        .optional()
        .describe("Maximum number of results to return. Omit for default limit."),
    });
  • Registration of search tools (including search_notes) into the tool registry. Called from src/tools/index.ts registerTools().
    export function registerSearchTools(
      registry: Map<string, ToolHandler>,
      container: ServiceContainer,
    ): void {
      const tools = [makeSearchNotesTool(container)];
    
      for (const tool of tools) {
        registry.set(tool.name, tool);
      }
    }
  • Imports for search_notes tool: zod for schema validation, type imports for ToolHandler/ServiceContainer/ToolResponse, helper functions requireServices/getRoot from index.ts, and logger.
    import { z } from "zod";
    import type { ToolHandler, ServiceContainer, ToolResponse } from "../types.js";
    import { requireServices, getRoot } from "./index.js";
    import { createChildLog } from "../markscribe-log.js";
    
    const log = createChildLog({ module: "search-tools" });
  • SearchServiceImpl.search() - the actual BM25 full-text search implementation. Tokenizes query, collects notes in scope, computes BM25 scores (k1=1.2, b=0.75), extracts excerpts, and returns sorted results.
    async search(query: string, options?: SearchOptions): Promise<SearchResult[]> {
      const scope = options?.scope;
      const searchContent = options?.searchContent ?? true;
      const searchFrontmatterOpt = options?.searchFrontmatter ?? false;
      const limit = options?.limit;
    
      log.info(
        { query, scope, searchContent, searchFrontmatter: searchFrontmatterOpt, limit },
        "search",
      );
    
      const queryTerms = tokenize(query);
      if (queryTerms.length === 0) {
        log.debug("search: empty query terms, returning []");
        return [];
      }
    
      // Collect all notes in scope
      const allPaths = await this.collectPaths(scope);
      log.debug({ count: allPaths.length, scope }, "search: collected paths");
    
      type DocData = {
        path: string;
        tokens: string[];
        tf: Map<string, number>;
        contentText: string;
        frontmatterText: string;
        frontmatter: Record<string, unknown>;
      };
    
      // Read all notes with bounded concurrency
      const docs: DocData[] = [];
    
      for (let i = 0; i < allPaths.length; i += READ_CONCURRENCY) {
        const batch = allPaths.slice(i, i + READ_CONCURRENCY);
        const batchResults = await Promise.all(
          batch.map(async (notePath) => {
            try {
              return { note: await this.file.readNote(notePath), path: notePath };
            } catch {
              log.debug({ path: notePath }, "search: skipping unreadable note");
              return null;
            }
          }),
        );
    
        for (const result of batchResults) {
          if (!result) continue;
          const { note, path: notePath } = result;
    
          const contentText = note.content;
          const contentTokens = searchContent ? tokenize(contentText) : [];
          const contentTf = searchContent ? buildTermFreq(contentTokens) : new Map<string, number>();
    
          let frontmatterText = "";
          let frontmatterTokens: string[] = [];
          let frontmatterTf = new Map<string, number>();
    
          if (searchFrontmatterOpt) {
            frontmatterText = this.frontmatterToText(note.frontmatter);
            frontmatterTokens = tokenize(frontmatterText);
            frontmatterTf = buildTermFreq(frontmatterTokens);
          }
    
          const combinedTokens = [...contentTokens, ...frontmatterTokens];
          const combinedTf = this.mergeTf(contentTf, frontmatterTf);
    
          docs.push({
            path: notePath,
            tokens: combinedTokens,
            tf: combinedTf,
            contentText,
            frontmatterText,
            frontmatter: note.frontmatter,
          });
        }
      }
    
      if (docs.length === 0) {
        return [];
      }
    
      // Compute document frequency across corpus
      const df = new Map<string, number>();
      for (const doc of docs) {
        const seen = new Set<string>();
        for (const token of doc.tokens) {
          if (!seen.has(token)) {
            seen.add(token);
            df.set(token, (df.get(token) ?? 0) + 1);
          }
        }
      }
    
      const N = docs.length;
      const avgDocLen = docs.reduce((sum, d) => sum + d.tokens.length, 0) / N;
    
      const results: SearchResult[] = [];
    
      for (const doc of docs) {
        const docLen = doc.tokens.length;
        let score = 0;
    
        for (const term of queryTerms) {
          const tf = doc.tf.get(term) ?? 0;
          if (tf === 0) continue;
    
          const dfVal = df.get(term) ?? 0;
          const idf = Math.log((N - dfVal + 0.5) / (dfVal + 0.5) + 1);
          const termScore =
            (idf * (tf * (BM25_K1 + 1))) /
            (tf + BM25_K1 * (1 - BM25_B + BM25_B * (docLen / avgDocLen)));
          score += termScore;
        }
    
        if (score <= 0) continue;
    
        // Identify matched frontmatter fields
        const matchedFields: string[] = [];
        if (searchFrontmatterOpt) {
          for (const [field, fieldValue] of Object.entries(doc.frontmatter)) {
            const fieldText = Array.isArray(fieldValue)
              ? fieldValue.map(String).join(" ").toLowerCase()
              : String(fieldValue ?? "").toLowerCase();
            for (const term of queryTerms) {
              if (fieldText.includes(term)) {
                if (!matchedFields.includes(field)) {
                  matchedFields.push(field);
                }
              }
            }
          }
        }
    
        const excerptSource = searchContent ? doc.contentText : doc.frontmatterText;
        const excerpt = extractExcerpt(
          excerptSource || doc.contentText,
          queryTerms,
          this.excerptChars,
        );
    
        const result: SearchResult = {
          path: doc.path,
          score,
          excerpt,
        };
    
        if (matchedFields.length > 0) {
          result.matchedFields = matchedFields;
        }
    
        results.push(result);
      }
    
      // Sort by score descending
      results.sort((a, b) => b.score - a.score);
    
      const effectiveLimit = limit ?? this.maxResults;
      const limited = results.slice(0, effectiveLimit);
      log.info({ query, resultCount: limited.length }, "search complete");
      return limited;
    }
Behavior4/5

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

The description discloses the BM25 algorithm, ordering by relevance, and return fields (path, score, excerpt). Without annotations, it provides good behavioral context. However, it does not mention rate limits, authentication needs, or side effects, which are not critical for a search tool.

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 one concise sentence that front-loads the core functionality. Every word adds value, with no repetition or filler.

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

Completeness5/5

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

The description fully covers the tool's purpose, parameters, and return format. Given the lack of output schema, it compensates by explaining the response structure. No gaps remain for a search tool.

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

Parameters5/5

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

The description explains each parameter's meaning beyond the schema (e.g., scope as path prefix, default values for searchContent and searchFrontmatter). Since schema coverage is 100% from the description, it adds significant value.

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 performs 'Full-text BM25 search', specifies the return format with relevance scoring, and lists all parameters. It distinguishes itself from sibling tools by being the only general search tool, as others are specific (e.g., get_backlinks, find_orphans).

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

Usage Guidelines4/5

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

The description implies usage for full-text search, but lacks explicit guidance on when to use this versus alternatives. It could mention not to use for metadata-only searches, but the inclusion of searchFrontmatter parameter somewhat covers that. No when-not or exclusion criteria are 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/Erodenn/markscribe'

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