Skip to main content
Glama

readwise_topic_search

Search documents in Readwise Reader by topic using regex matching on titles, summaries, notes, and tags to find relevant content.

Instructions

Search documents in Readwise Reader by topic using regex matching on title, summary, notes, and tags

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
searchTermsYesList of search terms to match against document content (case-insensitive regex matching)

Implementation Reference

  • The main handler function that executes the readwise_topic_search tool. It extracts searchTerms from input args, calls the client's searchDocumentsByTopic method, formats the matching documents into a structured JSON response with full metadata, appends any API messages, and returns as MCP text content.
    export async function handleTopicSearch(args: any) {
      const client = initializeClient();
      const { searchTerms } = args as { searchTerms: string[] };
      
      const response = await client.searchDocumentsByTopic(searchTerms);
      
      const searchResults = {
        searchTerms,
        totalMatches: response.data.length,
        documents: response.data.map((doc: any) => ({
          id: doc.id,
          url: doc.url,
          title: doc.title,
          author: doc.author,
          source: doc.source,
          category: doc.category,
          location: doc.location,
          tags: doc.tags,
          site_name: doc.site_name,
          word_count: doc.word_count,
          created_at: doc.created_at,
          updated_at: doc.updated_at,
          published_date: doc.published_date,
          summary: doc.summary,
          image_url: doc.image_url,
          source_url: doc.source_url,
          notes: doc.notes,
          reading_progress: doc.reading_progress,
          first_opened_at: doc.first_opened_at,
          last_opened_at: doc.last_opened_at,
          saved_at: doc.saved_at,
          last_moved_at: doc.last_moved_at,
        }))
      };
    
      let responseText = JSON.stringify(searchResults, null, 2);
      
      if (response.messages && response.messages.length > 0) {
        responseText += '\n\nMessages:\n' + response.messages.map(msg => `${msg.type.toUpperCase()}: ${msg.content}`).join('\n');
      }
    
      return {
        content: [
          {
            type: 'text',
            text: responseText,
          },
        ],
      };
    } 
  • Supporting utility in ReadwiseClient that implements the topic search logic: paginates to fetch all documents, builds case-insensitive regex from each searchTerm, concatenates title/summary/notes/tags for matching, filters documents matching any term, handles rate limiting.
    async searchDocumentsByTopic(searchTerms: string[]): Promise<APIResponse<ReadwiseDocument[]>> {
      try {
        // Fetch all documents without full content for performance
        const allDocuments: ReadwiseDocument[] = [];
        let nextPageCursor: string | undefined;
        
        do {
          const params: ListDocumentsParams = {
            withFullContent: false,
            withHtmlContent: false,
          };
          
          if (nextPageCursor) {
            params.pageCursor = nextPageCursor;
          }
          
          const response = await this.listDocuments(params);
          allDocuments.push(...response.data.results);
          nextPageCursor = response.data.nextPageCursor;
        } while (nextPageCursor);
    
        // Create regex patterns from search terms (case-insensitive)
        const regexPatterns = searchTerms.map(term => 
          new RegExp(term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'i')
        );
    
        // Filter documents that match any of the search terms
        const matchingDocuments = allDocuments.filter(doc => {
          // Extract searchable text fields
          const searchableFields = [
            doc.title || '',
            doc.summary || '',
            doc.notes || '',
            // Handle tags - they can be string array or object
            Array.isArray(doc.tags) ? doc.tags.join(' ') : '',
          ];
    
          const searchableText = searchableFields.join(' ').toLowerCase();
    
          // Check if any regex pattern matches
          return regexPatterns.some(pattern => pattern.test(searchableText));
        });
    
        return this.createResponse(matchingDocuments);
      } catch (error) {
        if (error instanceof Error && error.message.startsWith('RATE_LIMIT:')) {
          const seconds = parseInt(error.message.split(':')[1], 10);
          throw new Error(`Rate limit exceeded. Too many requests. Please retry after ${seconds} seconds.`);
        }
        throw error;
      }
    }
  • Tool schema definition including name, description, and inputSchema specifying an array of searchTerms (min 1 item) for regex-based topic search.
    {
      name: 'readwise_topic_search',
      description: 'Search documents in Readwise Reader by topic using regex matching on title, summary, notes, and tags',
      inputSchema: {
        type: 'object',
        properties: {
          searchTerms: {
            type: 'array',
            items: { type: 'string' },
            description: 'List of search terms to match against document content (case-insensitive regex matching)',
            minItems: 1,
          },
        },
        required: ['searchTerms'],
        additionalProperties: false,
      },
    },
  • Tool dispatch registration in the central handleToolCall switch statement, mapping 'readwise_topic_search' name to the handleTopicSearch function.
    case 'readwise_topic_search':
      return handleTopicSearch(args);
  • Import statement registering the handleTopicSearch handler into the dispatch module.
    import { handleListTags, handleTopicSearch } from './tag-search-handlers.js';
Behavior3/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions 'regex matching' and 'case-insensitive' (though the latter is in the schema, not the description), indicating search behavior, but lacks details on permissions, rate limits, pagination, or output format. It adds some context (search scope across multiple fields) but is incomplete for a search tool with no output schema.

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 that front-loads the core purpose ('Search documents in Readwise Reader by topic') and adds necessary details ('using regex matching on title, summary, notes, and tags') without redundancy. Every word contributes to understanding, making it appropriately sized and well-structured.

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

Completeness3/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 (search with regex), no annotations, and no output schema, the description is partially complete. It covers the search scope and method but lacks information on behavioral aspects like result limits, error handling, or authentication needs. For a search tool without structured output details, more context would be beneficial to fully guide usage.

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 100%, with the schema fully documenting the 'searchTerms' parameter (type, constraints, and description). The description adds minimal value beyond the schema by mentioning 'regex matching' and the fields searched (title, summary, notes, tags), but doesn't provide additional syntax or format details. 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 specific action ('Search documents') and target resource ('in Readwise Reader by topic'), distinguishing it from siblings like 'readwise_list_documents' (which likely lists without search) and 'readwise_search_highlights' (which searches highlights rather than documents). It specifies the search scope ('regex matching on title, summary, notes, and tags'), making the purpose explicit and differentiated.

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 usage for topic-based document searches but does not explicitly state when to use this tool versus alternatives. For example, it doesn't clarify if this should be used instead of 'readwise_list_documents' for filtered results or 'readwise_search_highlights' for content within documents. No exclusions or prerequisites are mentioned, leaving usage context inferred rather than guided.

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/arnaldo-delisio/readwise-mcp-enhanced'

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