Skip to main content
Glama

search_pdf

Search for text within a PDF file and retrieve each match with its surrounding context, enabling quick location and review of specific content.

Instructions

Search for text in a PDF and return all matches with context

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
filePathYesAbsolute path to the PDF file
searchTermYesText to search for in the PDF
caseSensitiveNoWhether the search should be case sensitive

Implementation Reference

  • src/index.ts:78-100 (registration)
    Tool registration: 'search_pdf' tool definition with name, description, and inputSchema for filePath, searchTerm, and caseSensitive parameters.
    {
      name: 'search_pdf',
      description: 'Search for text in a PDF and return all matches with context',
      inputSchema: {
        type: 'object',
        properties: {
          filePath: {
            type: 'string',
            description: 'Absolute path to the PDF file',
          },
          searchTerm: {
            type: 'string',
            description: 'Text to search for in the PDF',
          },
          caseSensitive: {
            type: 'boolean',
            description: 'Whether the search should be case sensitive',
            default: false,
          },
        },
        required: ['filePath', 'searchTerm'],
      },
    },
  • Handler: 'search_pdf' case in the CallToolRequestSchema handler. It extracts filePath, searchTerm, and optional caseSensitive from args, calls searchInPDF(), and returns results as JSON.
    case 'search_pdf': {
      const { filePath, searchTerm, caseSensitive } = args as {
        filePath: string;
        searchTerm: string;
        caseSensitive?: boolean;
      };
      
      const results = await searchInPDF(filePath, searchTerm, caseSensitive);
      
      return {
        content: [
          {
            type: 'text',
            text: JSON.stringify(results, null, 2),
          },
        ],
      };
    }
  • Helper: searchInPDF() - the core implementation that reads a PDF file, iterates through each page, uses a regex to find matches, and returns SearchResult objects with page number, matched text, context (50 chars on each side), and position.
    export async function searchInPDF(
      filePath: string,
      searchTerm: string,
      caseSensitive: boolean = false
    ): Promise<SearchResult[]> {
      try {
        const dataBuffer = await fs.readFile(filePath);
        const parser = new PDFParse({ data: dataBuffer });
        const info = await parser.getInfo();
        
        const results: SearchResult[] = [];
        const searchRegex = new RegExp(
          searchTerm.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'),
          caseSensitive ? 'g' : 'gi'
        );
    
        // Search through each page
        for (let pageNo = 1; pageNo <= info.total; pageNo++) {
          const pageResult = await parser.getText({ partial: [pageNo] });
          const pageText = pageResult.text;
          
          let match;
          while ((match = searchRegex.exec(pageText)) !== null) {
            const contextStart = Math.max(0, match.index - 50);
            const contextEnd = Math.min(pageText.length, match.index + match[0].length + 50);
            const context = pageText.substring(contextStart, contextEnd).replace(/\n/g, ' ');
    
            results.push({
              page: pageNo,
              text: match[0],
              context: `...${context}...`,
              position: match.index,
            });
          }
        }
        
        await parser.destroy();
        return results;
      } catch (error) {
        throw new Error(`Failed to search PDF: ${error instanceof Error ? error.message : String(error)}`);
      }
    }
  • Schema: SearchResult interface defining the type returned by searchInPDF - includes page number, matched text, context (with surrounding chars), and position index.
    export interface SearchResult {
      page: number;
      text: string;
      context: string;
      position: number;
    }
Behavior2/5

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

No annotations are provided, and the description does not disclose whether the tool is read-only, requires specific file permissions, or any error behaviors. The read-only nature is implied but not confirmed.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single sentence of 10 words, efficiently conveying the core function. However, it sacrifices clarity for brevity, particularly around the return format ('context').

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?

Without an output schema, the description should explain the return value structure (e.g., list of matches with page numbers and surrounding text). The vague phrase 'context' does not sufficiently inform the agent.

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?

All three parameters are well-described in the input schema with clear descriptions, achieving 100% schema coverage. The tool description adds no additional semantic value beyond the schema.

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 searches for text in a PDF and returns matches with context. It distinguishes from sibling tools like extract_pdf_image or get_pdf_metadata by focusing on text search, but lacks detail on what 'context' entails.

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

Usage Guidelines3/5

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

The description implies use when finding text occurrences in a PDF, but does not explicitly compare with alternatives like read_pdf for full content extraction. No when-not-to-use guidance or prerequisites are given.

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/rturv/mcp-pdf-reader'

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