Skip to main content
Glama

regex_search

Match a JavaScript regex against file contents across projects, knowledge base, or all files, returning line-numbered hits. Use when full-text search fails to find substrings or identifiers.

Instructions

Match a JS regex against the body of every file in scope (project, KB, or all) and return per-file hits with line numbers. Slower than FTS search because it reads each file's content; use only when FTS misses substrings, URLs, or code identifiers. Read-only; no side effects, auth, or rate limits. Capped at 500 files / 10 hits per file by default; the response reports files_truncated and per-file truncation so the agent can re-scope. project_id: null = KB only; omit = everywhere. Invalid regex throws.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
patternYesJavaScript RegExp source
project_idNoScope to one project, null for KB-only, omit for everything
case_insensitiveNo
max_filesNoCap on files scanned (default 500)
max_matches_per_fileNoPer-file hit cap (default 10)

Implementation Reference

  • The tool is registered via server.tool() with name 'regex_search'. The registration includes the description, Zod schema for parameters, and the async handler function.
    server.tool(
      "regex_search",
      "Match a JS regex against the body of every file in scope (project, KB, or all) and return per-file hits with line numbers. Slower than FTS `search` because it reads each file's content; use only when FTS misses substrings, URLs, or code identifiers. Read-only; no side effects, auth, or rate limits. Capped at 500 files / 10 hits per file by default; the response reports `files_truncated` and per-file truncation so the agent can re-scope. `project_id: null` = KB only; omit = everywhere. Invalid regex throws.",
      {
        pattern: z.string().describe("JavaScript RegExp source"),
        project_id: z.number().nullable().optional().describe("Scope to one project, null for KB-only, omit for everything"),
        case_insensitive: z.boolean().optional(),
        max_files: z.number().int().positive().max(2000).optional().describe("Cap on files scanned (default 500)"),
        max_matches_per_file: z.number().int().positive().max(100).optional().describe("Per-file hit cap (default 10)"),
      },
      async ({ pattern, project_id, case_insensitive, max_files, max_matches_per_file }) => {
        try {
          let re: RegExp;
          try {
            re = new RegExp(pattern, case_insensitive ? "i" : "");
          } catch (e: any) {
            throw new Error(`invalid regex: ${e?.message ?? e}`);
          }
          const fileCap = max_files ?? 500;
          const perFileCap = max_matches_per_file ?? 10;
          const db = getDatabase();
    
          let where = "";
          const params: any[] = [];
          if (project_id === null) {
            where = "WHERE project_id IS NULL";
          } else if (typeof project_id === "number") {
            where = "WHERE project_id = ?";
            params.push(project_id);
          }
          const rows = db
            .prepare(`SELECT id, path, title FROM files ${where} LIMIT ?`)
            .all(...params, fileCap) as { id: number; path: string; title: string }[];
    
          const hits: any[] = [];
          let scanned = 0;
          for (const r of rows) {
            scanned++;
            let content: string;
            try { content = readFileSync(r.path, "utf8"); } catch { continue; }
            const lines = content.split("\n");
            const fileHits: { line: number; text: string }[] = [];
            for (let i = 0; i < lines.length; i++) {
              if (re.test(lines[i])) {
                fileHits.push({ line: i + 1, text: lines[i] });
                if (fileHits.length >= perFileCap) break;
              }
            }
            if (fileHits.length > 0) {
              hits.push({ file_id: r.id, path: r.path, title: r.title, match_count: fileHits.length, matches: fileHits });
            }
          }
    
          return {
            content: [
              {
                type: "text",
                text: JSON.stringify(
                  {
                    pattern,
                    files_scanned: scanned,
                    files_truncated: rows.length === fileCap,
                    file_hit_count: hits.length,
                    total_match_count: hits.reduce((s, h) => s + h.match_count, 0),
                    hits,
                  },
                  null,
                  2
                ),
              },
            ],
          };
        } catch (e: any) {
          return {
            isError: true,
            content: [{ type: "text", text: JSON.stringify({ error: e?.message ?? String(e) }, null, 2) }],
          };
        }
      }
    );
  • Zod schema defining the input parameters: pattern (string), project_id (nullable number optional), case_insensitive (boolean optional), max_files (positive int up to 2000 optional), max_matches_per_file (positive int up to 100 optional).
    {
      pattern: z.string().describe("JavaScript RegExp source"),
      project_id: z.number().nullable().optional().describe("Scope to one project, null for KB-only, omit for everything"),
      case_insensitive: z.boolean().optional(),
      max_files: z.number().int().positive().max(2000).optional().describe("Cap on files scanned (default 500)"),
      max_matches_per_file: z.number().int().positive().max(100).optional().describe("Per-file hit cap (default 10)"),
    },
  • The handler function that executes regex_search: compiles the JS regex, queries the DB for files (scoped by project_id), reads each file from disk, tests each line against the regex, collects hits per file capped at max_matches_per_file, and returns a JSON response with files_scanned, file_hit_count, total_match_count and hits array.
    async ({ pattern, project_id, case_insensitive, max_files, max_matches_per_file }) => {
      try {
        let re: RegExp;
        try {
          re = new RegExp(pattern, case_insensitive ? "i" : "");
        } catch (e: any) {
          throw new Error(`invalid regex: ${e?.message ?? e}`);
        }
        const fileCap = max_files ?? 500;
        const perFileCap = max_matches_per_file ?? 10;
        const db = getDatabase();
    
        let where = "";
        const params: any[] = [];
        if (project_id === null) {
          where = "WHERE project_id IS NULL";
        } else if (typeof project_id === "number") {
          where = "WHERE project_id = ?";
          params.push(project_id);
        }
        const rows = db
          .prepare(`SELECT id, path, title FROM files ${where} LIMIT ?`)
          .all(...params, fileCap) as { id: number; path: string; title: string }[];
    
        const hits: any[] = [];
        let scanned = 0;
        for (const r of rows) {
          scanned++;
          let content: string;
          try { content = readFileSync(r.path, "utf8"); } catch { continue; }
          const lines = content.split("\n");
          const fileHits: { line: number; text: string }[] = [];
          for (let i = 0; i < lines.length; i++) {
            if (re.test(lines[i])) {
              fileHits.push({ line: i + 1, text: lines[i] });
              if (fileHits.length >= perFileCap) break;
            }
          }
          if (fileHits.length > 0) {
            hits.push({ file_id: r.id, path: r.path, title: r.title, match_count: fileHits.length, matches: fileHits });
          }
        }
    
        return {
          content: [
            {
              type: "text",
              text: JSON.stringify(
                {
                  pattern,
                  files_scanned: scanned,
                  files_truncated: rows.length === fileCap,
                  file_hit_count: hits.length,
                  total_match_count: hits.reduce((s, h) => s + h.match_count, 0),
                  hits,
                },
                null,
                2
              ),
            },
          ],
        };
      } catch (e: any) {
        return {
          isError: true,
          content: [{ type: "text", text: JSON.stringify({ error: e?.message ?? String(e) }, null, 2) }],
        };
      }
    }
  • Categorization of regex_search under the 'Search' category in the UI tool category mapping.
    regex_search: "Search",
Behavior5/5

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

Discloses read-only nature, no side effects, no auth/rate limits, default caps (500 files, 10 hits/file), truncation reporting, and error behavior on invalid regex. With no annotations provided, description fully covers behavioral traits.

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?

Concise and front-loaded; each sentence adds essential information. No redundancy or unnecessary details.

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?

Despite lacking output schema, the description covers all critical aspects: scoping, caps, truncation, error handling. Complete for a regex search tool.

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

Parameters4/5

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

Schema coverage is 80% (4 of 5 parameters described). Description adds meaning beyond schema: explains pattern usage, project_id values (null vs omit). However, case_insensitive is not addressed in description, slightly reducing completeness.

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 matches a JS regex against file bodies and returns per-file hits with line numbers. It distinguishes itself from the FTS 'search' sibling by specifying when to use it (for substrings, URLs, code identifiers missed by FTS).

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

Usage Guidelines5/5

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

Explicitly says when to use (when FTS misses) and when not to (favor 'search' for FTS). Also explains scoping via project_id (null for KB-only, omit for everything).

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/safiyu/ctxnest'

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