Skip to main content
Glama
canova

Searchfox MCP Server

by canova

search_code

Find exact code strings in Mozilla repositories using literal matching. Search for specific terms, function names, or code snippets across Mozilla codebases.

Instructions

Search for code in Mozilla repositories using Searchfox. IMPORTANT: Uses exact string matching only - no search operators, no OR logic, no phrase matching with quotes. Multiple words are treated as a single literal string.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesSearch query using exact literal string matching. CRITICAL: Do NOT use multiple words expecting OR logic (e.g., 'profiler raptor' won't find files containing either word separately). Do NOT use quotes around terms (e.g., '"profiler" "raptor"' searches for literal quotes). Use single specific terms, function names, or exact code snippets. For broader searches, use separate queries or enable regexp mode.
repoNoRepository to search in (e.g., mozilla-central, comm-central)mozilla-central
pathNoFilter results by file path using glob patterns. Path matching uses substring matching - a path matches even if only part of it matches the glob. Use ^ and $ operators to match beginning or end of path (e.g., '^tools/profiler' to match paths starting with tools/profiler, 'profiler$' to match paths ending with profiler).
caseNoEnable case sensitive search (default: case insensitive)
regexpNoTreat query as regular expression pattern
limitNoMaximum number of results to return

Implementation Reference

  • Implements the 'search_code' tool logic: builds Searchfox search URL from options, fetches JSON response, parses complex nested structure of results (handling sections like 'normal', 'test', categories), extracts matches with path/line/snippet/context/bounds, applies limit, formats as JSON text response.
    private async searchCode(options: SearchOptions) {
      try {
        const searchParams = new URLSearchParams({
          q: options.query,
          case: options.case ? "true" : "false",
          regexp: options.regexp ? "true" : "false",
        });
    
        if (options.path) {
          searchParams.append("path", options.path);
        }
    
        const url = `${this.baseUrl}/${options.repo || "mozilla-central"}/search?${searchParams}`;
        const response = await fetch(url, {
          headers: {
            Accept: "application/json",
          },
        });
    
        if (!response.ok) {
          throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
    
        // Searchfox returns JSON with a specific structure
        const data = (await response.json()) as SearchfoxResponse;
        const results: SearchResult[] = [];
    
        // Process all sections dynamically (normal, test, thirdparty, generated, etc.)
        for (const [sectionKey, sectionValue] of Object.entries(data)) {
          // Skip metadata fields
          if (sectionKey.startsWith("*")) {
            continue;
          }
    
          // Handle sections that contain categorized results (like "normal", "test", "thirdparty")
          if (typeof sectionValue === "object" && sectionValue !== null) {
            // Check if it's a direct array (like "Textual Occurrences")
            if (Array.isArray(sectionValue)) {
              const files = sectionValue as SearchfoxFile[];
              for (const file of files) {
                if (file.lines && Array.isArray(file.lines)) {
                  for (const line of file.lines) {
                    if (options.limit && results.length >= options.limit) {
                      break;
                    }
    
                    results.push({
                      path: file.path,
                      line: line.lno,
                      column: line.bounds?.[0] || 0,
                      snippet: line.line,
                      context: sectionKey,
                      contextsym: line.contextsym,
                      peekRange: line.peekRange,
                      upsearch: line.upsearch,
                      bounds: line.bounds,
                    });
                  }
                }
              }
            } else {
              // Handle sections with categorized results (Record<string, Array<...>>)
              const categoryMap = sectionValue as Record<string, SearchfoxFile[]>;
              for (const [category, categoryResults] of Object.entries(
                categoryMap
              )) {
                if (Array.isArray(categoryResults)) {
                  for (const file of categoryResults) {
                    if (file.lines && Array.isArray(file.lines)) {
                      for (const line of file.lines) {
                        if (options.limit && results.length >= options.limit) {
                          break;
                        }
    
                        results.push({
                          path: file.path,
                          line: line.lno,
                          column: line.bounds?.[0] || 0,
                          snippet: line.line,
                          context: line.context || `${sectionKey}: ${category}`,
                          contextsym: line.contextsym,
                          peekRange: line.peekRange,
                          upsearch: line.upsearch,
                          bounds: line.bounds,
                        });
                      }
                    }
                  }
                }
              }
            }
          }
    
          // Break if we've reached the limit
          if (options.limit && results.length >= options.limit) {
            break;
          }
        }
    
        return {
          content: [
            {
              type: "text",
              text: JSON.stringify(
                {
                  query: options.query,
                  repo: options.repo || "mozilla-central",
                  count: results.length,
                  title: data["*title*"],
                  timedout: data["*timedout*"],
                  limits: data["*limits*"],
                  total_available: data["*timedout*"]
                    ? "Search timed out - more results may be available"
                    : undefined,
                  results,
                },
                null,
                2
              ),
            },
          ],
        };
      } catch (error) {
        throw new McpError(
          ErrorCode.InternalError,
          `Search failed: ${error instanceof Error ? error.message : String(error)}`
        );
      }
    }
  • src/index.ts:81-123 (registration)
    Registers the 'search_code' tool in the MCP server's ListTools handler, defining name, detailed description with usage notes, and comprehensive inputSchema with properties for query (required), repo, path (glob), case/regexp flags, limit.
    {
      name: "search_code",
      description:
        "Search for code in Mozilla repositories using Searchfox. IMPORTANT: Uses exact string matching only - no search operators, no OR logic, no phrase matching with quotes. Multiple words are treated as a single literal string.",
      inputSchema: {
        type: "object",
        properties: {
          query: {
            type: "string",
            description:
              "Search query using exact literal string matching. CRITICAL: Do NOT use multiple words expecting OR logic (e.g., 'profiler raptor' won't find files containing either word separately). Do NOT use quotes around terms (e.g., '\"profiler\" \"raptor\"' searches for literal quotes). Use single specific terms, function names, or exact code snippets. For broader searches, use separate queries or enable regexp mode.",
          },
          repo: {
            type: "string",
            description:
              "Repository to search in (e.g., mozilla-central, comm-central)",
            default: "mozilla-central",
          },
          path: {
            type: "string",
            description:
              "Filter results by file path using glob patterns. Path matching uses substring matching - a path matches even if only part of it matches the glob. Use ^ and $ operators to match beginning or end of path (e.g., '^tools/profiler' to match paths starting with tools/profiler, 'profiler$' to match paths ending with profiler).",
          },
          case: {
            type: "boolean",
            description:
              "Enable case sensitive search (default: case insensitive)",
            default: false,
          },
          regexp: {
            type: "boolean",
            description: "Treat query as regular expression pattern",
            default: false,
          },
          limit: {
            type: "number",
            description: "Maximum number of results to return",
            default: 50,
          },
        },
        required: ["query"],
      },
    },
  • TypeScript interface defining the input options for the searchCode handler, matching the tool's inputSchema properties.
    interface SearchOptions {
      query: string;
      repo?: string;
      path?: string;
      case?: boolean;
      regexp?: boolean;
      limit?: number;
    }
  • Dispatch handler in CallToolRequestSchema: validates 'search_code' arguments, constructs SearchOptions with defaults, invokes the searchCode method.
    case "search_code": {
      const searchArgs = args as Record<string, unknown>;
      if (!searchArgs.query || typeof searchArgs.query !== "string") {
        throw new McpError(
          ErrorCode.InvalidParams,
          "Query parameter is required and must be a string"
        );
      }
    
      const options: SearchOptions = {
        query: searchArgs.query,
        repo:
          typeof searchArgs.repo === "string"
            ? searchArgs.repo
            : "mozilla-central",
        path:
          typeof searchArgs.path === "string" ? searchArgs.path : undefined,
        case:
          typeof searchArgs.case === "boolean" ? searchArgs.case : false,
        regexp:
          typeof searchArgs.regexp === "boolean"
            ? searchArgs.regexp
            : false,
        limit: typeof searchArgs.limit === "number" ? searchArgs.limit : 50,
      };
    
      return await this.searchCode(options);
    }
  • TypeScript interface for formatted search results output by the handler.
    interface SearchResult {
      path: string;
      line: number;
      column: number;
      snippet: string;
      context?: string;
      contextsym?: string;
      peekRange?: string;
      upsearch?: string;
      bounds?: number[];
    }
Behavior4/5

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

Since no annotations are provided, the description carries the full burden of behavioral disclosure. It effectively describes key behavioral traits: exact string matching only, no search operators, no OR logic, no phrase matching with quotes, and how multiple words are treated. It also implies this is a read-only operation through the search context.

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 efficiently structured with two sentences: the first states the core purpose, and the second provides critical behavioral constraints. Every sentence earns its place by delivering essential information without redundancy.

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

Completeness4/5

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

For a search tool with no annotations and no output schema, the description provides good contextual completeness. It covers the search methodology constraints and basic usage guidance. The main gap is the lack of information about return format or result structure, which would be helpful given the absence of an output schema.

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?

With 100% schema description coverage, the schema already documents all 6 parameters thoroughly. The description adds some context about the query parameter's exact matching behavior, but doesn't provide additional semantic meaning beyond what's in the schema descriptions. 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.

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 purpose with specific verb ('Search for code') and resource ('in Mozilla repositories using Searchfox'). It distinguishes from the sibling tool 'get_file' by focusing on search functionality rather than file retrieval.

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?

The description provides explicit guidance on when to use this tool versus alternatives: it specifies exact string matching only, warns against using multiple words expecting OR logic, and advises using separate queries or regexp mode for broader searches. This gives clear context for appropriate usage.

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/canova/searchfox-mcp'

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