Skip to main content
Glama

Search Shelf

search_shelf
Read-only

Search for text across files in a shelf using substring or regex patterns to locate specific content within stored documents.

Instructions

Search for text across files in a shelf

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
shelf_idYes
queryYes
modeNo
case_sensitiveNo
max_matchesNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
modeYes
queryYes
matchesYes
shelf_idYes
truncatedYes
scanned_bytesYes
scanned_filesYes
case_sensitiveYes

Implementation Reference

  • Main handler function that executes the search_shelf tool. It validates input, resolves the shelf source, builds a matcher (substring or regex), iterates through files to find matches, and returns structured results with matches, scanned files/bytes count, and truncation status.
    async (input, extra) => {
      try {
        const mode = input.mode ?? "substring";
        const caseSensitive = input.case_sensitive ?? false;
    
        const apiKey = context.getApiKey(extra);
        const source = await resolveShelfSource({
          client: context.createShelvClient(apiKey),
          shelfPublicId: input.shelf_id,
          mode: "archive-first",
        });
    
        const matcher = buildMatcher(input.query, mode, caseSensitive);
        const maxMatches = Math.min(
          input.max_matches ?? context.config.searchMaxMatches,
          context.config.searchMaxMatches,
        );
    
        const matches: Array<{
          path: string;
          line: string;
          line_number: number;
          snippet: string;
        }> = [];
    
        let scannedFiles = 0;
        let scannedBytes = 0;
        let truncated = false;
    
        for (const [filePath, content] of Object.entries(source.files)) {
          if (scannedFiles >= context.config.searchMaxFiles) {
            truncated = true;
            break;
          }
    
          const bytes = Buffer.byteLength(content, "utf8");
          if (scannedBytes + bytes > context.config.searchMaxBytes) {
            truncated = true;
            break;
          }
    
          scannedFiles += 1;
          scannedBytes += bytes;
    
          const lines = content.split(/\r?\n/);
          for (let index = 0; index < lines.length; index += 1) {
            const line = lines[index] || "";
            if (!matcher(line)) continue;
    
            matches.push({
              path: filePath,
              line,
              line_number: index + 1,
              snippet: line.slice(0, 300),
            });
    
            if (matches.length >= maxMatches) {
              truncated = true;
              break;
            }
          }
    
          if (truncated) break;
        }
    
        return successResult(
          `Found ${matches.length} matches across ${scannedFiles} files`,
          {
            shelf_id: input.shelf_id,
            query: input.query,
            mode,
            case_sensitive: caseSensitive,
            matches,
            scanned_files: scannedFiles,
            scanned_bytes: scannedBytes,
            truncated,
          },
        );
      } catch (error) {
        return errorResult(error);
      }
    },
  • Zod schemas defining the tool's input (shelf_id, query, mode, case_sensitive, max_matches) and output (shelf_id, query, mode, case_sensitive, matches array with path/line/line_number/snippet, scanned_files, scanned_bytes, truncated) structure.
    const inputSchema = {
      shelf_id: z.string().min(1),
      query: z.string().min(1),
      mode: z.enum(["substring", "regex"]).optional(),
      case_sensitive: z.boolean().optional(),
      max_matches: z.number().int().min(1).optional(),
    };
    
    const outputSchema = {
      shelf_id: z.string(),
      query: z.string(),
      mode: z.enum(["substring", "regex"]),
      case_sensitive: z.boolean(),
      matches: z.array(
        z.object({
          path: z.string(),
          line: z.string(),
          line_number: z.number(),
          snippet: z.string(),
        }),
      ),
      scanned_files: z.number(),
      scanned_bytes: z.number(),
      truncated: z.boolean(),
    };
  • Registers the search_shelf tool with the MCP server, providing its name, metadata (title, description, annotations), schemas, and the async handler function.
    export function registerSearchShelfTool(
      server: McpServer,
      context: ToolContext,
    ): void {
      server.registerTool(
        "search_shelf",
        {
          title: "Search Shelf",
          description: "Search for text across files in a shelf",
          inputSchema,
          outputSchema,
          annotations: { readOnlyHint: true },
        },
        async (input, extra) => {
          try {
            const mode = input.mode ?? "substring";
            const caseSensitive = input.case_sensitive ?? false;
    
            const apiKey = context.getApiKey(extra);
            const source = await resolveShelfSource({
              client: context.createShelvClient(apiKey),
              shelfPublicId: input.shelf_id,
              mode: "archive-first",
            });
    
            const matcher = buildMatcher(input.query, mode, caseSensitive);
            const maxMatches = Math.min(
              input.max_matches ?? context.config.searchMaxMatches,
              context.config.searchMaxMatches,
            );
    
            const matches: Array<{
              path: string;
              line: string;
              line_number: number;
              snippet: string;
            }> = [];
    
            let scannedFiles = 0;
            let scannedBytes = 0;
            let truncated = false;
    
            for (const [filePath, content] of Object.entries(source.files)) {
              if (scannedFiles >= context.config.searchMaxFiles) {
                truncated = true;
                break;
              }
    
              const bytes = Buffer.byteLength(content, "utf8");
              if (scannedBytes + bytes > context.config.searchMaxBytes) {
                truncated = true;
                break;
              }
    
              scannedFiles += 1;
              scannedBytes += bytes;
    
              const lines = content.split(/\r?\n/);
              for (let index = 0; index < lines.length; index += 1) {
                const line = lines[index] || "";
                if (!matcher(line)) continue;
    
                matches.push({
                  path: filePath,
                  line,
                  line_number: index + 1,
                  snippet: line.slice(0, 300),
                });
    
                if (matches.length >= maxMatches) {
                  truncated = true;
                  break;
                }
              }
    
              if (truncated) break;
            }
    
            return successResult(
              `Found ${matches.length} matches across ${scannedFiles} files`,
              {
                shelf_id: input.shelf_id,
                query: input.query,
                mode,
                case_sensitive: caseSensitive,
                matches,
                scanned_files: scannedFiles,
                scanned_bytes: scannedBytes,
                truncated,
              },
            );
          } catch (error) {
            return errorResult(error);
          }
        },
      );
    }
  • Helper function buildMatcher that creates a line matching function based on mode (substring or regex) and case sensitivity. Validates regex patterns and throws McpToolError for invalid expressions.
    function buildMatcher(
      query: string,
      mode: "substring" | "regex",
      caseSensitive: boolean,
    ): (line: string) => boolean {
      if (mode === "regex") {
        let regex: RegExp;
        try {
          regex = new RegExp(query, caseSensitive ? "" : "i");
        } catch {
          throw new McpToolError({
            code: "INPUT_ERROR",
            message: "Invalid regular expression",
            status: 400,
            retryable: false,
          });
        }
    
        return (line: string) => regex.test(line);
      }
    
      const needle = caseSensitive ? query : query.toLowerCase();
      return (line: string) => {
        const haystack = caseSensitive ? line : line.toLowerCase();
        return haystack.includes(needle);
      };
    }
  • Calls registerSearchShelfTool as part of the main registerShelvTools function, which registers all shelf-related tools with the MCP server.
    registerSearchShelfTool(server, context);
Behavior3/5

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

The annotation 'readOnlyHint: true' already indicates this is a safe read operation. The description adds minimal behavioral context by implying text-based searching across files, but doesn't disclose details like search scope, performance, or output format. With annotations covering safety, this is adequate but not rich.

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 with no wasted words. It's front-loaded with the core action and resource, making it easy to grasp immediately.

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?

Given the tool's moderate complexity (5 parameters, read-only), annotations provide safety info, and an output schema exists (so return values are documented elsewhere), the description is reasonably complete. However, it could benefit from more detail on parameter usage or search behavior to fully compensate for low schema coverage.

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 0%, so the schema provides no parameter descriptions. The description mentions 'text' and 'files in a shelf', which loosely relates to 'query' and 'shelf_id', but doesn't explain the purpose of parameters like 'mode', 'case_sensitive', or 'max_matches'. It adds some meaning but doesn't fully compensate for the coverage gap.

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 action ('Search for text') and target resource ('across files in a shelf'), which is specific and unambiguous. However, it doesn't explicitly differentiate from sibling tools like 'get_shelf_tree' or 'read_shelf_file', which might also involve shelf content access, so it doesn't reach the highest score.

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 like 'get_shelf_tree' or 'read_shelf_file', nor does it mention any prerequisites or exclusions. It's a basic statement of function without contextual usage advice.

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/shelv-dev/shelv-mcp'

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